viewer.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021
  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 result = Vector3.Zero();
  1840. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1841. return result;
  1842. };
  1843. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1844. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1845. };
  1846. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1847. var matrix = MathTmp.Matrix[0];
  1848. world.multiplyToRef(view, matrix);
  1849. matrix.multiplyToRef(projection, matrix);
  1850. matrix.invert();
  1851. var screenSource = MathTmp.Vector3[0];
  1852. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1853. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1854. screenSource.z = 2 * sourceZ - 1.0;
  1855. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1856. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1857. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1858. result.scaleInPlace(1.0 / num);
  1859. }
  1860. };
  1861. Vector3.Minimize = function (left, right) {
  1862. var min = left.clone();
  1863. min.MinimizeInPlace(right);
  1864. return min;
  1865. };
  1866. Vector3.Maximize = function (left, right) {
  1867. var max = left.clone();
  1868. max.MaximizeInPlace(right);
  1869. return max;
  1870. };
  1871. /**
  1872. * Returns the distance (float) between the vectors "value1" and "value2".
  1873. */
  1874. Vector3.Distance = function (value1, value2) {
  1875. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1876. };
  1877. /**
  1878. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1879. */
  1880. Vector3.DistanceSquared = function (value1, value2) {
  1881. var x = value1.x - value2.x;
  1882. var y = value1.y - value2.y;
  1883. var z = value1.z - value2.z;
  1884. return (x * x) + (y * y) + (z * z);
  1885. };
  1886. /**
  1887. * Returns a new Vector3 located at the center between "value1" and "value2".
  1888. */
  1889. Vector3.Center = function (value1, value2) {
  1890. var center = value1.add(value2);
  1891. center.scaleInPlace(0.5);
  1892. return center;
  1893. };
  1894. /**
  1895. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1896. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1897. * to something in order to rotate it from its local system to the given target system.
  1898. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1899. * Returns a new Vector3.
  1900. */
  1901. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1902. var rotation = Vector3.Zero();
  1903. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1904. return rotation;
  1905. };
  1906. /**
  1907. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1908. */
  1909. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1910. var quat = MathTmp.Quaternion[0];
  1911. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1912. quat.toEulerAnglesToRef(ref);
  1913. };
  1914. return Vector3;
  1915. }());
  1916. BABYLON.Vector3 = Vector3;
  1917. //Vector4 class created for EulerAngle class conversion to Quaternion
  1918. var Vector4 = /** @class */ (function () {
  1919. /**
  1920. * Creates a Vector4 object from the passed floats.
  1921. */
  1922. function Vector4(x, y, z, w) {
  1923. this.x = x;
  1924. this.y = y;
  1925. this.z = z;
  1926. this.w = w;
  1927. }
  1928. /**
  1929. * Returns the string with the Vector4 coordinates.
  1930. */
  1931. Vector4.prototype.toString = function () {
  1932. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1933. };
  1934. /**
  1935. * Returns the string "Vector4".
  1936. */
  1937. Vector4.prototype.getClassName = function () {
  1938. return "Vector4";
  1939. };
  1940. /**
  1941. * Returns the Vector4 hash code.
  1942. */
  1943. Vector4.prototype.getHashCode = function () {
  1944. var hash = this.x || 0;
  1945. hash = (hash * 397) ^ (this.y || 0);
  1946. hash = (hash * 397) ^ (this.z || 0);
  1947. hash = (hash * 397) ^ (this.w || 0);
  1948. return hash;
  1949. };
  1950. // Operators
  1951. /**
  1952. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1953. */
  1954. Vector4.prototype.asArray = function () {
  1955. var result = new Array();
  1956. this.toArray(result, 0);
  1957. return result;
  1958. };
  1959. /**
  1960. * Populates the passed array from the passed index with the Vector4 coordinates.
  1961. * Returns the Vector4.
  1962. */
  1963. Vector4.prototype.toArray = function (array, index) {
  1964. if (index === undefined) {
  1965. index = 0;
  1966. }
  1967. array[index] = this.x;
  1968. array[index + 1] = this.y;
  1969. array[index + 2] = this.z;
  1970. array[index + 3] = this.w;
  1971. return this;
  1972. };
  1973. /**
  1974. * Adds the passed vector to the current Vector4.
  1975. * Returns the updated Vector4.
  1976. */
  1977. Vector4.prototype.addInPlace = function (otherVector) {
  1978. this.x += otherVector.x;
  1979. this.y += otherVector.y;
  1980. this.z += otherVector.z;
  1981. this.w += otherVector.w;
  1982. return this;
  1983. };
  1984. /**
  1985. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1986. */
  1987. Vector4.prototype.add = function (otherVector) {
  1988. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1989. };
  1990. /**
  1991. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1992. * Returns the current Vector4.
  1993. */
  1994. Vector4.prototype.addToRef = function (otherVector, result) {
  1995. result.x = this.x + otherVector.x;
  1996. result.y = this.y + otherVector.y;
  1997. result.z = this.z + otherVector.z;
  1998. result.w = this.w + otherVector.w;
  1999. return this;
  2000. };
  2001. /**
  2002. * Subtract in place the passed vector from the current Vector4.
  2003. * Returns the updated Vector4.
  2004. */
  2005. Vector4.prototype.subtractInPlace = function (otherVector) {
  2006. this.x -= otherVector.x;
  2007. this.y -= otherVector.y;
  2008. this.z -= otherVector.z;
  2009. this.w -= otherVector.w;
  2010. return this;
  2011. };
  2012. /**
  2013. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2014. */
  2015. Vector4.prototype.subtract = function (otherVector) {
  2016. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2017. };
  2018. /**
  2019. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2020. * Returns the current Vector4.
  2021. */
  2022. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2023. result.x = this.x - otherVector.x;
  2024. result.y = this.y - otherVector.y;
  2025. result.z = this.z - otherVector.z;
  2026. result.w = this.w - otherVector.w;
  2027. return this;
  2028. };
  2029. /**
  2030. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2031. */
  2032. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2033. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2034. };
  2035. /**
  2036. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2037. * Returns the current Vector4.
  2038. */
  2039. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2040. result.x = this.x - x;
  2041. result.y = this.y - y;
  2042. result.z = this.z - z;
  2043. result.w = this.w - w;
  2044. return this;
  2045. };
  2046. /**
  2047. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2048. */
  2049. Vector4.prototype.negate = function () {
  2050. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2051. };
  2052. /**
  2053. * Multiplies the current Vector4 coordinates by scale (float).
  2054. * Returns the updated Vector4.
  2055. */
  2056. Vector4.prototype.scaleInPlace = function (scale) {
  2057. this.x *= scale;
  2058. this.y *= scale;
  2059. this.z *= scale;
  2060. this.w *= scale;
  2061. return this;
  2062. };
  2063. /**
  2064. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2065. */
  2066. Vector4.prototype.scale = function (scale) {
  2067. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2068. };
  2069. /**
  2070. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2071. * Returns the current Vector4.
  2072. */
  2073. Vector4.prototype.scaleToRef = function (scale, result) {
  2074. result.x = this.x * scale;
  2075. result.y = this.y * scale;
  2076. result.z = this.z * scale;
  2077. result.w = this.w * scale;
  2078. return this;
  2079. };
  2080. /**
  2081. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2082. */
  2083. Vector4.prototype.equals = function (otherVector) {
  2084. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2085. };
  2086. /**
  2087. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2088. */
  2089. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2090. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2091. return otherVector
  2092. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2093. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2094. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2095. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2096. };
  2097. /**
  2098. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2099. */
  2100. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2101. return this.x === x && this.y === y && this.z === z && this.w === w;
  2102. };
  2103. /**
  2104. * Multiplies in place the current Vector4 by the passed one.
  2105. * Returns the updated Vector4.
  2106. */
  2107. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2108. this.x *= otherVector.x;
  2109. this.y *= otherVector.y;
  2110. this.z *= otherVector.z;
  2111. this.w *= otherVector.w;
  2112. return this;
  2113. };
  2114. /**
  2115. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2116. */
  2117. Vector4.prototype.multiply = function (otherVector) {
  2118. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2119. };
  2120. /**
  2121. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2122. * Returns the current Vector4.
  2123. */
  2124. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2125. result.x = this.x * otherVector.x;
  2126. result.y = this.y * otherVector.y;
  2127. result.z = this.z * otherVector.z;
  2128. result.w = this.w * otherVector.w;
  2129. return this;
  2130. };
  2131. /**
  2132. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2133. */
  2134. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2135. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2136. };
  2137. /**
  2138. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2139. */
  2140. Vector4.prototype.divide = function (otherVector) {
  2141. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2142. };
  2143. /**
  2144. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2145. * Returns the current Vector4.
  2146. */
  2147. Vector4.prototype.divideToRef = function (otherVector, result) {
  2148. result.x = this.x / otherVector.x;
  2149. result.y = this.y / otherVector.y;
  2150. result.z = this.z / otherVector.z;
  2151. result.w = this.w / otherVector.w;
  2152. return this;
  2153. };
  2154. /**
  2155. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2156. */
  2157. Vector4.prototype.MinimizeInPlace = function (other) {
  2158. if (other.x < this.x)
  2159. this.x = other.x;
  2160. if (other.y < this.y)
  2161. this.y = other.y;
  2162. if (other.z < this.z)
  2163. this.z = other.z;
  2164. if (other.w < this.w)
  2165. this.w = other.w;
  2166. return this;
  2167. };
  2168. /**
  2169. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2170. */
  2171. Vector4.prototype.MaximizeInPlace = function (other) {
  2172. if (other.x > this.x)
  2173. this.x = other.x;
  2174. if (other.y > this.y)
  2175. this.y = other.y;
  2176. if (other.z > this.z)
  2177. this.z = other.z;
  2178. if (other.w > this.w)
  2179. this.w = other.w;
  2180. return this;
  2181. };
  2182. // Properties
  2183. /**
  2184. * Returns the Vector4 length (float).
  2185. */
  2186. Vector4.prototype.length = function () {
  2187. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2188. };
  2189. /**
  2190. * Returns the Vector4 squared length (float).
  2191. */
  2192. Vector4.prototype.lengthSquared = function () {
  2193. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2194. };
  2195. // Methods
  2196. /**
  2197. * Normalizes in place the Vector4.
  2198. * Returns the updated Vector4.
  2199. */
  2200. Vector4.prototype.normalize = function () {
  2201. var len = this.length();
  2202. if (len === 0)
  2203. return this;
  2204. var num = 1.0 / len;
  2205. this.x *= num;
  2206. this.y *= num;
  2207. this.z *= num;
  2208. this.w *= num;
  2209. return this;
  2210. };
  2211. /**
  2212. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2213. */
  2214. Vector4.prototype.toVector3 = function () {
  2215. return new Vector3(this.x, this.y, this.z);
  2216. };
  2217. /**
  2218. * Returns a new Vector4 copied from the current one.
  2219. */
  2220. Vector4.prototype.clone = function () {
  2221. return new Vector4(this.x, this.y, this.z, this.w);
  2222. };
  2223. /**
  2224. * Updates the current Vector4 with the passed one coordinates.
  2225. * Returns the updated Vector4.
  2226. */
  2227. Vector4.prototype.copyFrom = function (source) {
  2228. this.x = source.x;
  2229. this.y = source.y;
  2230. this.z = source.z;
  2231. this.w = source.w;
  2232. return this;
  2233. };
  2234. /**
  2235. * Updates the current Vector4 coordinates with the passed floats.
  2236. * Returns the updated Vector4.
  2237. */
  2238. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2239. this.x = x;
  2240. this.y = y;
  2241. this.z = z;
  2242. this.w = w;
  2243. return this;
  2244. };
  2245. /**
  2246. * Updates the current Vector4 coordinates with the passed floats.
  2247. * Returns the updated Vector4.
  2248. */
  2249. Vector4.prototype.set = function (x, y, z, w) {
  2250. return this.copyFromFloats(x, y, z, w);
  2251. };
  2252. // Statics
  2253. /**
  2254. * Returns a new Vector4 set from the starting index of the passed array.
  2255. */
  2256. Vector4.FromArray = function (array, offset) {
  2257. if (!offset) {
  2258. offset = 0;
  2259. }
  2260. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2261. };
  2262. /**
  2263. * Updates the passed vector "result" from the starting index of the passed array.
  2264. */
  2265. Vector4.FromArrayToRef = function (array, offset, result) {
  2266. result.x = array[offset];
  2267. result.y = array[offset + 1];
  2268. result.z = array[offset + 2];
  2269. result.w = array[offset + 3];
  2270. };
  2271. /**
  2272. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2273. */
  2274. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2275. Vector4.FromArrayToRef(array, offset, result);
  2276. };
  2277. /**
  2278. * Updates the passed vector "result" coordinates from the passed floats.
  2279. */
  2280. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2281. result.x = x;
  2282. result.y = y;
  2283. result.z = z;
  2284. result.w = w;
  2285. };
  2286. /**
  2287. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2288. */
  2289. Vector4.Zero = function () {
  2290. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2291. };
  2292. /**
  2293. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2294. */
  2295. Vector4.One = function () {
  2296. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2297. };
  2298. /**
  2299. * Returns a new normalized Vector4 from the passed one.
  2300. */
  2301. Vector4.Normalize = function (vector) {
  2302. var result = Vector4.Zero();
  2303. Vector4.NormalizeToRef(vector, result);
  2304. return result;
  2305. };
  2306. /**
  2307. * Updates the passed vector "result" from the normalization of the passed one.
  2308. */
  2309. Vector4.NormalizeToRef = function (vector, result) {
  2310. result.copyFrom(vector);
  2311. result.normalize();
  2312. };
  2313. Vector4.Minimize = function (left, right) {
  2314. var min = left.clone();
  2315. min.MinimizeInPlace(right);
  2316. return min;
  2317. };
  2318. Vector4.Maximize = function (left, right) {
  2319. var max = left.clone();
  2320. max.MaximizeInPlace(right);
  2321. return max;
  2322. };
  2323. /**
  2324. * Returns the distance (float) between the vectors "value1" and "value2".
  2325. */
  2326. Vector4.Distance = function (value1, value2) {
  2327. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2328. };
  2329. /**
  2330. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2331. */
  2332. Vector4.DistanceSquared = function (value1, value2) {
  2333. var x = value1.x - value2.x;
  2334. var y = value1.y - value2.y;
  2335. var z = value1.z - value2.z;
  2336. var w = value1.w - value2.w;
  2337. return (x * x) + (y * y) + (z * z) + (w * w);
  2338. };
  2339. /**
  2340. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2341. */
  2342. Vector4.Center = function (value1, value2) {
  2343. var center = value1.add(value2);
  2344. center.scaleInPlace(0.5);
  2345. return center;
  2346. };
  2347. /**
  2348. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2349. * This methods computes transformed normalized direction vectors only.
  2350. */
  2351. Vector4.TransformNormal = function (vector, transformation) {
  2352. var result = Vector4.Zero();
  2353. Vector4.TransformNormalToRef(vector, transformation, result);
  2354. return result;
  2355. };
  2356. /**
  2357. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2358. * This methods computes transformed normalized direction vectors only.
  2359. */
  2360. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2361. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2362. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2363. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2364. result.x = x;
  2365. result.y = y;
  2366. result.z = z;
  2367. result.w = vector.w;
  2368. };
  2369. /**
  2370. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2371. * This methods computes transformed normalized direction vectors only.
  2372. */
  2373. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2374. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2375. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2376. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2377. result.w = w;
  2378. };
  2379. return Vector4;
  2380. }());
  2381. BABYLON.Vector4 = Vector4;
  2382. var Size = /** @class */ (function () {
  2383. /**
  2384. * Creates a Size object from the passed width and height (floats).
  2385. */
  2386. function Size(width, height) {
  2387. this.width = width;
  2388. this.height = height;
  2389. }
  2390. // Returns a string with the Size width and height.
  2391. Size.prototype.toString = function () {
  2392. return "{W: " + this.width + ", H: " + this.height + "}";
  2393. };
  2394. /**
  2395. * Returns the string "Size"
  2396. */
  2397. Size.prototype.getClassName = function () {
  2398. return "Size";
  2399. };
  2400. /**
  2401. * Returns the Size hash code.
  2402. */
  2403. Size.prototype.getHashCode = function () {
  2404. var hash = this.width || 0;
  2405. hash = (hash * 397) ^ (this.height || 0);
  2406. return hash;
  2407. };
  2408. /**
  2409. * Updates the current size from the passed one.
  2410. * Returns the updated Size.
  2411. */
  2412. Size.prototype.copyFrom = function (src) {
  2413. this.width = src.width;
  2414. this.height = src.height;
  2415. };
  2416. /**
  2417. * Updates in place the current Size from the passed floats.
  2418. * Returns the updated Size.
  2419. */
  2420. Size.prototype.copyFromFloats = function (width, height) {
  2421. this.width = width;
  2422. this.height = height;
  2423. return this;
  2424. };
  2425. /**
  2426. * Updates in place the current Size from the passed floats.
  2427. * Returns the updated Size.
  2428. */
  2429. Size.prototype.set = function (width, height) {
  2430. return this.copyFromFloats(width, height);
  2431. };
  2432. /**
  2433. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2434. */
  2435. Size.prototype.multiplyByFloats = function (w, h) {
  2436. return new Size(this.width * w, this.height * h);
  2437. };
  2438. /**
  2439. * Returns a new Size copied from the passed one.
  2440. */
  2441. Size.prototype.clone = function () {
  2442. return new Size(this.width, this.height);
  2443. };
  2444. /**
  2445. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2446. */
  2447. Size.prototype.equals = function (other) {
  2448. if (!other) {
  2449. return false;
  2450. }
  2451. return (this.width === other.width) && (this.height === other.height);
  2452. };
  2453. Object.defineProperty(Size.prototype, "surface", {
  2454. /**
  2455. * Returns the surface of the Size : width * height (float).
  2456. */
  2457. get: function () {
  2458. return this.width * this.height;
  2459. },
  2460. enumerable: true,
  2461. configurable: true
  2462. });
  2463. /**
  2464. * Returns a new Size set to (0.0, 0.0)
  2465. */
  2466. Size.Zero = function () {
  2467. return new Size(0.0, 0.0);
  2468. };
  2469. /**
  2470. * Returns a new Size set as the addition result of the current Size and the passed one.
  2471. */
  2472. Size.prototype.add = function (otherSize) {
  2473. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2474. return r;
  2475. };
  2476. /**
  2477. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2478. */
  2479. Size.prototype.subtract = function (otherSize) {
  2480. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2481. return r;
  2482. };
  2483. /**
  2484. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2485. */
  2486. Size.Lerp = function (start, end, amount) {
  2487. var w = start.width + ((end.width - start.width) * amount);
  2488. var h = start.height + ((end.height - start.height) * amount);
  2489. return new Size(w, h);
  2490. };
  2491. return Size;
  2492. }());
  2493. BABYLON.Size = Size;
  2494. var Quaternion = /** @class */ (function () {
  2495. /**
  2496. * Creates a new Quaternion from the passed floats.
  2497. */
  2498. function Quaternion(x, y, z, w) {
  2499. if (x === void 0) { x = 0.0; }
  2500. if (y === void 0) { y = 0.0; }
  2501. if (z === void 0) { z = 0.0; }
  2502. if (w === void 0) { w = 1.0; }
  2503. this.x = x;
  2504. this.y = y;
  2505. this.z = z;
  2506. this.w = w;
  2507. }
  2508. /**
  2509. * Returns a string with the Quaternion coordinates.
  2510. */
  2511. Quaternion.prototype.toString = function () {
  2512. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2513. };
  2514. /**
  2515. * Returns the string "Quaternion".
  2516. */
  2517. Quaternion.prototype.getClassName = function () {
  2518. return "Quaternion";
  2519. };
  2520. /**
  2521. * Returns the Quaternion hash code.
  2522. */
  2523. Quaternion.prototype.getHashCode = function () {
  2524. var hash = this.x || 0;
  2525. hash = (hash * 397) ^ (this.y || 0);
  2526. hash = (hash * 397) ^ (this.z || 0);
  2527. hash = (hash * 397) ^ (this.w || 0);
  2528. return hash;
  2529. };
  2530. /**
  2531. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2532. */
  2533. Quaternion.prototype.asArray = function () {
  2534. return [this.x, this.y, this.z, this.w];
  2535. };
  2536. /**
  2537. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2538. */
  2539. Quaternion.prototype.equals = function (otherQuaternion) {
  2540. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2541. };
  2542. /**
  2543. * Returns a new Quaternion copied from the current one.
  2544. */
  2545. Quaternion.prototype.clone = function () {
  2546. return new Quaternion(this.x, this.y, this.z, this.w);
  2547. };
  2548. /**
  2549. * Updates the current Quaternion from the passed one coordinates.
  2550. * Returns the updated Quaterion.
  2551. */
  2552. Quaternion.prototype.copyFrom = function (other) {
  2553. this.x = other.x;
  2554. this.y = other.y;
  2555. this.z = other.z;
  2556. this.w = other.w;
  2557. return this;
  2558. };
  2559. /**
  2560. * Updates the current Quaternion from the passed float coordinates.
  2561. * Returns the updated Quaterion.
  2562. */
  2563. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2564. this.x = x;
  2565. this.y = y;
  2566. this.z = z;
  2567. this.w = w;
  2568. return this;
  2569. };
  2570. /**
  2571. * Updates the current Quaternion from the passed float coordinates.
  2572. * Returns the updated Quaterion.
  2573. */
  2574. Quaternion.prototype.set = function (x, y, z, w) {
  2575. return this.copyFromFloats(x, y, z, w);
  2576. };
  2577. /**
  2578. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2579. */
  2580. Quaternion.prototype.add = function (other) {
  2581. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2585. */
  2586. Quaternion.prototype.subtract = function (other) {
  2587. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2588. };
  2589. /**
  2590. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2591. */
  2592. Quaternion.prototype.scale = function (value) {
  2593. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2594. };
  2595. /**
  2596. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2597. */
  2598. Quaternion.prototype.multiply = function (q1) {
  2599. var result = new Quaternion(0, 0, 0, 1.0);
  2600. this.multiplyToRef(q1, result);
  2601. return result;
  2602. };
  2603. /**
  2604. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2605. * Returns the current Quaternion.
  2606. */
  2607. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2608. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2609. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2610. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2611. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2612. result.copyFromFloats(x, y, z, w);
  2613. return this;
  2614. };
  2615. /**
  2616. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2617. * Returns the updated Quaternion.
  2618. */
  2619. Quaternion.prototype.multiplyInPlace = function (q1) {
  2620. this.multiplyToRef(q1, this);
  2621. return this;
  2622. };
  2623. /**
  2624. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2625. * Returns the current Quaternion.
  2626. */
  2627. Quaternion.prototype.conjugateToRef = function (ref) {
  2628. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2629. return this;
  2630. };
  2631. /**
  2632. * Conjugates in place the current Quaternion.
  2633. * Returns the updated Quaternion.
  2634. */
  2635. Quaternion.prototype.conjugateInPlace = function () {
  2636. this.x *= -1;
  2637. this.y *= -1;
  2638. this.z *= -1;
  2639. return this;
  2640. };
  2641. /**
  2642. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2643. */
  2644. Quaternion.prototype.conjugate = function () {
  2645. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2646. return result;
  2647. };
  2648. /**
  2649. * Returns the Quaternion length (float).
  2650. */
  2651. Quaternion.prototype.length = function () {
  2652. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2653. };
  2654. /**
  2655. * Normalize in place the current Quaternion.
  2656. * Returns the updated Quaternion.
  2657. */
  2658. Quaternion.prototype.normalize = function () {
  2659. var length = 1.0 / this.length();
  2660. this.x *= length;
  2661. this.y *= length;
  2662. this.z *= length;
  2663. this.w *= length;
  2664. return this;
  2665. };
  2666. /**
  2667. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2668. */
  2669. Quaternion.prototype.toEulerAngles = function (order) {
  2670. if (order === void 0) { order = "YZX"; }
  2671. var result = Vector3.Zero();
  2672. this.toEulerAnglesToRef(result, order);
  2673. return result;
  2674. };
  2675. /**
  2676. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2677. * Returns the current Quaternion.
  2678. */
  2679. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2680. if (order === void 0) { order = "YZX"; }
  2681. var qz = this.z;
  2682. var qx = this.x;
  2683. var qy = this.y;
  2684. var qw = this.w;
  2685. var sqw = qw * qw;
  2686. var sqz = qz * qz;
  2687. var sqx = qx * qx;
  2688. var sqy = qy * qy;
  2689. var zAxisY = qy * qz - qx * qw;
  2690. var limit = .4999999;
  2691. if (zAxisY < -limit) {
  2692. result.y = 2 * Math.atan2(qy, qw);
  2693. result.x = Math.PI / 2;
  2694. result.z = 0;
  2695. }
  2696. else if (zAxisY > limit) {
  2697. result.y = 2 * Math.atan2(qy, qw);
  2698. result.x = -Math.PI / 2;
  2699. result.z = 0;
  2700. }
  2701. else {
  2702. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2703. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2704. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2705. }
  2706. return this;
  2707. };
  2708. /**
  2709. * Updates the passed rotation matrix with the current Quaternion values.
  2710. * Returns the current Quaternion.
  2711. */
  2712. Quaternion.prototype.toRotationMatrix = function (result) {
  2713. var xx = this.x * this.x;
  2714. var yy = this.y * this.y;
  2715. var zz = this.z * this.z;
  2716. var xy = this.x * this.y;
  2717. var zw = this.z * this.w;
  2718. var zx = this.z * this.x;
  2719. var yw = this.y * this.w;
  2720. var yz = this.y * this.z;
  2721. var xw = this.x * this.w;
  2722. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2723. result.m[1] = 2.0 * (xy + zw);
  2724. result.m[2] = 2.0 * (zx - yw);
  2725. result.m[3] = 0;
  2726. result.m[4] = 2.0 * (xy - zw);
  2727. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2728. result.m[6] = 2.0 * (yz + xw);
  2729. result.m[7] = 0;
  2730. result.m[8] = 2.0 * (zx + yw);
  2731. result.m[9] = 2.0 * (yz - xw);
  2732. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2733. result.m[11] = 0;
  2734. result.m[12] = 0;
  2735. result.m[13] = 0;
  2736. result.m[14] = 0;
  2737. result.m[15] = 1.0;
  2738. result._markAsUpdated();
  2739. return this;
  2740. };
  2741. /**
  2742. * Updates the current Quaternion from the passed rotation matrix values.
  2743. * Returns the updated Quaternion.
  2744. */
  2745. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2746. Quaternion.FromRotationMatrixToRef(matrix, this);
  2747. return this;
  2748. };
  2749. // Statics
  2750. /**
  2751. * Returns a new Quaternion set from the passed rotation matrix values.
  2752. */
  2753. Quaternion.FromRotationMatrix = function (matrix) {
  2754. var result = new Quaternion();
  2755. Quaternion.FromRotationMatrixToRef(matrix, result);
  2756. return result;
  2757. };
  2758. /**
  2759. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2760. */
  2761. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2762. var data = matrix.m;
  2763. var m11 = data[0], m12 = data[4], m13 = data[8];
  2764. var m21 = data[1], m22 = data[5], m23 = data[9];
  2765. var m31 = data[2], m32 = data[6], m33 = data[10];
  2766. var trace = m11 + m22 + m33;
  2767. var s;
  2768. if (trace > 0) {
  2769. s = 0.5 / Math.sqrt(trace + 1.0);
  2770. result.w = 0.25 / s;
  2771. result.x = (m32 - m23) * s;
  2772. result.y = (m13 - m31) * s;
  2773. result.z = (m21 - m12) * s;
  2774. }
  2775. else if (m11 > m22 && m11 > m33) {
  2776. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2777. result.w = (m32 - m23) / s;
  2778. result.x = 0.25 * s;
  2779. result.y = (m12 + m21) / s;
  2780. result.z = (m13 + m31) / s;
  2781. }
  2782. else if (m22 > m33) {
  2783. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2784. result.w = (m13 - m31) / s;
  2785. result.x = (m12 + m21) / s;
  2786. result.y = 0.25 * s;
  2787. result.z = (m23 + m32) / s;
  2788. }
  2789. else {
  2790. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2791. result.w = (m21 - m12) / s;
  2792. result.x = (m13 + m31) / s;
  2793. result.y = (m23 + m32) / s;
  2794. result.z = 0.25 * s;
  2795. }
  2796. };
  2797. /**
  2798. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2799. */
  2800. Quaternion.Zero = function () {
  2801. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2802. };
  2803. /**
  2804. * Returns a new Quaternion as the inverted current Quaternion.
  2805. */
  2806. Quaternion.Inverse = function (q) {
  2807. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2808. };
  2809. /**
  2810. * Returns the identity Quaternion.
  2811. */
  2812. Quaternion.Identity = function () {
  2813. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2814. };
  2815. Quaternion.IsIdentity = function (quaternion) {
  2816. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2817. };
  2818. /**
  2819. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2820. */
  2821. Quaternion.RotationAxis = function (axis, angle) {
  2822. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2823. };
  2824. /**
  2825. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2826. */
  2827. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2828. var sin = Math.sin(angle / 2);
  2829. axis.normalize();
  2830. result.w = Math.cos(angle / 2);
  2831. result.x = axis.x * sin;
  2832. result.y = axis.y * sin;
  2833. result.z = axis.z * sin;
  2834. return result;
  2835. };
  2836. /**
  2837. * Retuns a new Quaternion set from the starting index of the passed array.
  2838. */
  2839. Quaternion.FromArray = function (array, offset) {
  2840. if (!offset) {
  2841. offset = 0;
  2842. }
  2843. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2844. };
  2845. /**
  2846. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2847. */
  2848. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2849. var q = new Quaternion();
  2850. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2851. return q;
  2852. };
  2853. /**
  2854. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2855. */
  2856. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2857. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2858. var halfRoll = roll * 0.5;
  2859. var halfPitch = pitch * 0.5;
  2860. var halfYaw = yaw * 0.5;
  2861. var sinRoll = Math.sin(halfRoll);
  2862. var cosRoll = Math.cos(halfRoll);
  2863. var sinPitch = Math.sin(halfPitch);
  2864. var cosPitch = Math.cos(halfPitch);
  2865. var sinYaw = Math.sin(halfYaw);
  2866. var cosYaw = Math.cos(halfYaw);
  2867. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2868. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2869. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2870. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2871. };
  2872. /**
  2873. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2874. */
  2875. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2876. var result = new Quaternion();
  2877. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2878. return result;
  2879. };
  2880. /**
  2881. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2882. */
  2883. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2884. // Produces a quaternion from Euler angles in the z-x-z orientation
  2885. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2886. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2887. var halfBeta = beta * 0.5;
  2888. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2889. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2890. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2891. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2892. };
  2893. /**
  2894. * Returns a new Quaternion as 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.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2899. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2900. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2901. return quat;
  2902. };
  2903. /**
  2904. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2905. * cf to Vector3.RotationFromAxis() documentation.
  2906. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2907. */
  2908. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2909. var rotMat = MathTmp.Matrix[0];
  2910. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2911. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2912. };
  2913. Quaternion.Slerp = function (left, right, amount) {
  2914. var result = Quaternion.Identity();
  2915. Quaternion.SlerpToRef(left, right, amount, result);
  2916. return result;
  2917. };
  2918. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2919. var num2;
  2920. var num3;
  2921. var num = amount;
  2922. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2923. var flag = false;
  2924. if (num4 < 0) {
  2925. flag = true;
  2926. num4 = -num4;
  2927. }
  2928. if (num4 > 0.999999) {
  2929. num3 = 1 - num;
  2930. num2 = flag ? -num : num;
  2931. }
  2932. else {
  2933. var num5 = Math.acos(num4);
  2934. var num6 = (1.0 / Math.sin(num5));
  2935. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2936. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2937. }
  2938. result.x = (num3 * left.x) + (num2 * right.x);
  2939. result.y = (num3 * left.y) + (num2 * right.y);
  2940. result.z = (num3 * left.z) + (num2 * right.z);
  2941. result.w = (num3 * left.w) + (num2 * right.w);
  2942. };
  2943. /**
  2944. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2945. */
  2946. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2947. var squared = amount * amount;
  2948. var cubed = amount * squared;
  2949. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2950. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2951. var part3 = (cubed - (2.0 * squared)) + amount;
  2952. var part4 = cubed - squared;
  2953. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2954. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2955. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2956. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2957. return new Quaternion(x, y, z, w);
  2958. };
  2959. return Quaternion;
  2960. }());
  2961. BABYLON.Quaternion = Quaternion;
  2962. var Matrix = /** @class */ (function () {
  2963. function Matrix() {
  2964. this._isIdentity = false;
  2965. this._isIdentityDirty = true;
  2966. this.m = new Float32Array(16);
  2967. this._markAsUpdated();
  2968. }
  2969. Matrix.prototype._markAsUpdated = function () {
  2970. this.updateFlag = Matrix._updateFlagSeed++;
  2971. this._isIdentityDirty = true;
  2972. };
  2973. // Properties
  2974. /**
  2975. * Boolean : True is the matrix is the identity matrix
  2976. */
  2977. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2978. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2979. if (this._isIdentityDirty) {
  2980. this._isIdentityDirty = false;
  2981. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2982. this._isIdentity = false;
  2983. }
  2984. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2985. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2986. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2987. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2988. this._isIdentity = false;
  2989. }
  2990. else {
  2991. this._isIdentity = true;
  2992. }
  2993. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2994. this._isIdentity = false;
  2995. }
  2996. }
  2997. return this._isIdentity;
  2998. };
  2999. /**
  3000. * Returns the matrix determinant (float).
  3001. */
  3002. Matrix.prototype.determinant = function () {
  3003. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3004. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3005. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3006. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3007. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3008. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3009. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3010. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3011. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3012. };
  3013. // Methods
  3014. /**
  3015. * Returns the matrix underlying array.
  3016. */
  3017. Matrix.prototype.toArray = function () {
  3018. return this.m;
  3019. };
  3020. /**
  3021. * Returns the matrix underlying array.
  3022. */
  3023. Matrix.prototype.asArray = function () {
  3024. return this.toArray();
  3025. };
  3026. /**
  3027. * Inverts in place the Matrix.
  3028. * Returns the Matrix inverted.
  3029. */
  3030. Matrix.prototype.invert = function () {
  3031. this.invertToRef(this);
  3032. return this;
  3033. };
  3034. /**
  3035. * Sets all the matrix elements to zero.
  3036. * Returns the Matrix.
  3037. */
  3038. Matrix.prototype.reset = function () {
  3039. for (var index = 0; index < 16; index++) {
  3040. this.m[index] = 0.0;
  3041. }
  3042. this._markAsUpdated();
  3043. return this;
  3044. };
  3045. /**
  3046. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3047. */
  3048. Matrix.prototype.add = function (other) {
  3049. var result = new Matrix();
  3050. this.addToRef(other, result);
  3051. return result;
  3052. };
  3053. /**
  3054. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3055. * Returns the Matrix.
  3056. */
  3057. Matrix.prototype.addToRef = function (other, result) {
  3058. for (var index = 0; index < 16; index++) {
  3059. result.m[index] = this.m[index] + other.m[index];
  3060. }
  3061. result._markAsUpdated();
  3062. return this;
  3063. };
  3064. /**
  3065. * Adds in place the passed matrix to the current Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.addToSelf = function (other) {
  3069. for (var index = 0; index < 16; index++) {
  3070. this.m[index] += other.m[index];
  3071. }
  3072. this._markAsUpdated();
  3073. return this;
  3074. };
  3075. /**
  3076. * Sets the passed matrix with the current inverted Matrix.
  3077. * Returns the unmodified current Matrix.
  3078. */
  3079. Matrix.prototype.invertToRef = function (other) {
  3080. var l1 = this.m[0];
  3081. var l2 = this.m[1];
  3082. var l3 = this.m[2];
  3083. var l4 = this.m[3];
  3084. var l5 = this.m[4];
  3085. var l6 = this.m[5];
  3086. var l7 = this.m[6];
  3087. var l8 = this.m[7];
  3088. var l9 = this.m[8];
  3089. var l10 = this.m[9];
  3090. var l11 = this.m[10];
  3091. var l12 = this.m[11];
  3092. var l13 = this.m[12];
  3093. var l14 = this.m[13];
  3094. var l15 = this.m[14];
  3095. var l16 = this.m[15];
  3096. var l17 = (l11 * l16) - (l12 * l15);
  3097. var l18 = (l10 * l16) - (l12 * l14);
  3098. var l19 = (l10 * l15) - (l11 * l14);
  3099. var l20 = (l9 * l16) - (l12 * l13);
  3100. var l21 = (l9 * l15) - (l11 * l13);
  3101. var l22 = (l9 * l14) - (l10 * l13);
  3102. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3103. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3104. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3105. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3106. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3107. var l28 = (l7 * l16) - (l8 * l15);
  3108. var l29 = (l6 * l16) - (l8 * l14);
  3109. var l30 = (l6 * l15) - (l7 * l14);
  3110. var l31 = (l5 * l16) - (l8 * l13);
  3111. var l32 = (l5 * l15) - (l7 * l13);
  3112. var l33 = (l5 * l14) - (l6 * l13);
  3113. var l34 = (l7 * l12) - (l8 * l11);
  3114. var l35 = (l6 * l12) - (l8 * l10);
  3115. var l36 = (l6 * l11) - (l7 * l10);
  3116. var l37 = (l5 * l12) - (l8 * l9);
  3117. var l38 = (l5 * l11) - (l7 * l9);
  3118. var l39 = (l5 * l10) - (l6 * l9);
  3119. other.m[0] = l23 * l27;
  3120. other.m[4] = l24 * l27;
  3121. other.m[8] = l25 * l27;
  3122. other.m[12] = l26 * l27;
  3123. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3124. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3125. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3126. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3127. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3128. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3129. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3130. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3131. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3132. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3133. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3134. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3135. other._markAsUpdated();
  3136. return this;
  3137. };
  3138. /**
  3139. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3140. * Returns the updated Matrix.
  3141. */
  3142. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3143. this.m[12] = x;
  3144. this.m[13] = y;
  3145. this.m[14] = z;
  3146. this._markAsUpdated();
  3147. return this;
  3148. };
  3149. /**
  3150. * Inserts the translation vector in the current Matrix.
  3151. * Returns the updated Matrix.
  3152. */
  3153. Matrix.prototype.setTranslation = function (vector3) {
  3154. this.m[12] = vector3.x;
  3155. this.m[13] = vector3.y;
  3156. this.m[14] = vector3.z;
  3157. this._markAsUpdated();
  3158. return this;
  3159. };
  3160. /**
  3161. * Returns a new Vector3 as the extracted translation from the Matrix.
  3162. */
  3163. Matrix.prototype.getTranslation = function () {
  3164. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3165. };
  3166. /**
  3167. * Fill a Vector3 with the extracted translation from the Matrix.
  3168. */
  3169. Matrix.prototype.getTranslationToRef = function (result) {
  3170. result.x = this.m[12];
  3171. result.y = this.m[13];
  3172. result.z = this.m[14];
  3173. return this;
  3174. };
  3175. /**
  3176. * Remove rotation and scaling part from the Matrix.
  3177. * Returns the updated Matrix.
  3178. */
  3179. Matrix.prototype.removeRotationAndScaling = function () {
  3180. this.setRowFromFloats(0, 1, 0, 0, 0);
  3181. this.setRowFromFloats(1, 0, 1, 0, 0);
  3182. this.setRowFromFloats(2, 0, 0, 1, 0);
  3183. return this;
  3184. };
  3185. /**
  3186. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3187. */
  3188. Matrix.prototype.multiply = function (other) {
  3189. var result = new Matrix();
  3190. this.multiplyToRef(other, result);
  3191. return result;
  3192. };
  3193. /**
  3194. * Updates the current Matrix from the passed one values.
  3195. * Returns the updated Matrix.
  3196. */
  3197. Matrix.prototype.copyFrom = function (other) {
  3198. for (var index = 0; index < 16; index++) {
  3199. this.m[index] = other.m[index];
  3200. }
  3201. this._markAsUpdated();
  3202. return this;
  3203. };
  3204. /**
  3205. * Populates the passed array from the starting index with the Matrix values.
  3206. * Returns the Matrix.
  3207. */
  3208. Matrix.prototype.copyToArray = function (array, offset) {
  3209. if (offset === void 0) { offset = 0; }
  3210. for (var index = 0; index < 16; index++) {
  3211. array[offset + index] = this.m[index];
  3212. }
  3213. return this;
  3214. };
  3215. /**
  3216. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3217. */
  3218. Matrix.prototype.multiplyToRef = function (other, result) {
  3219. this.multiplyToArray(other, result.m, 0);
  3220. result._markAsUpdated();
  3221. return this;
  3222. };
  3223. /**
  3224. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3225. */
  3226. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3227. var tm0 = this.m[0];
  3228. var tm1 = this.m[1];
  3229. var tm2 = this.m[2];
  3230. var tm3 = this.m[3];
  3231. var tm4 = this.m[4];
  3232. var tm5 = this.m[5];
  3233. var tm6 = this.m[6];
  3234. var tm7 = this.m[7];
  3235. var tm8 = this.m[8];
  3236. var tm9 = this.m[9];
  3237. var tm10 = this.m[10];
  3238. var tm11 = this.m[11];
  3239. var tm12 = this.m[12];
  3240. var tm13 = this.m[13];
  3241. var tm14 = this.m[14];
  3242. var tm15 = this.m[15];
  3243. var om0 = other.m[0];
  3244. var om1 = other.m[1];
  3245. var om2 = other.m[2];
  3246. var om3 = other.m[3];
  3247. var om4 = other.m[4];
  3248. var om5 = other.m[5];
  3249. var om6 = other.m[6];
  3250. var om7 = other.m[7];
  3251. var om8 = other.m[8];
  3252. var om9 = other.m[9];
  3253. var om10 = other.m[10];
  3254. var om11 = other.m[11];
  3255. var om12 = other.m[12];
  3256. var om13 = other.m[13];
  3257. var om14 = other.m[14];
  3258. var om15 = other.m[15];
  3259. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3260. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3261. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3262. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3263. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3264. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3265. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3266. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3267. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3268. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3269. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3270. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3271. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3272. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3273. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3274. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3275. return this;
  3276. };
  3277. /**
  3278. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3279. */
  3280. Matrix.prototype.equals = function (value) {
  3281. return value &&
  3282. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3283. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3284. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3285. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3286. };
  3287. /**
  3288. * Returns a new Matrix from the current Matrix.
  3289. */
  3290. Matrix.prototype.clone = function () {
  3291. 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]);
  3292. };
  3293. /**
  3294. * Returns the string "Matrix"
  3295. */
  3296. Matrix.prototype.getClassName = function () {
  3297. return "Matrix";
  3298. };
  3299. /**
  3300. * Returns the Matrix hash code.
  3301. */
  3302. Matrix.prototype.getHashCode = function () {
  3303. var hash = this.m[0] || 0;
  3304. for (var i = 1; i < 16; i++) {
  3305. hash = (hash * 397) ^ (this.m[i] || 0);
  3306. }
  3307. return hash;
  3308. };
  3309. /**
  3310. * Decomposes the current Matrix into :
  3311. * - a scale vector3 passed as a reference to update,
  3312. * - a rotation quaternion passed as a reference to update,
  3313. * - a translation vector3 passed as a reference to update.
  3314. * Returns the boolean `true`.
  3315. */
  3316. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3317. translation.x = this.m[12];
  3318. translation.y = this.m[13];
  3319. translation.z = this.m[14];
  3320. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3321. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3322. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3323. if (this.determinant() <= 0) {
  3324. scale.y *= -1;
  3325. }
  3326. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3327. rotation.x = 0;
  3328. rotation.y = 0;
  3329. rotation.z = 0;
  3330. rotation.w = 1;
  3331. return false;
  3332. }
  3333. 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]);
  3334. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3335. return true;
  3336. };
  3337. /**
  3338. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3339. */
  3340. Matrix.prototype.getRotationMatrix = function () {
  3341. var result = Matrix.Identity();
  3342. this.getRotationMatrixToRef(result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3347. * Returns the current Matrix.
  3348. */
  3349. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3350. var m = this.m;
  3351. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3352. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3353. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3354. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3355. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3356. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3357. 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);
  3358. return this;
  3359. };
  3360. // Statics
  3361. /**
  3362. * Returns a new Matrix set from the starting index of the passed array.
  3363. */
  3364. Matrix.FromArray = function (array, offset) {
  3365. var result = new Matrix();
  3366. if (!offset) {
  3367. offset = 0;
  3368. }
  3369. Matrix.FromArrayToRef(array, offset, result);
  3370. return result;
  3371. };
  3372. /**
  3373. * Sets the passed "result" matrix from the starting index of the passed array.
  3374. */
  3375. Matrix.FromArrayToRef = function (array, offset, result) {
  3376. for (var index = 0; index < 16; index++) {
  3377. result.m[index] = array[index + offset];
  3378. }
  3379. result._markAsUpdated();
  3380. };
  3381. /**
  3382. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3383. */
  3384. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3385. for (var index = 0; index < 16; index++) {
  3386. result.m[index] = array[index + offset] * scale;
  3387. }
  3388. result._markAsUpdated();
  3389. };
  3390. /**
  3391. * Sets the passed matrix "result" with the 16 passed floats.
  3392. */
  3393. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3394. result.m[0] = initialM11;
  3395. result.m[1] = initialM12;
  3396. result.m[2] = initialM13;
  3397. result.m[3] = initialM14;
  3398. result.m[4] = initialM21;
  3399. result.m[5] = initialM22;
  3400. result.m[6] = initialM23;
  3401. result.m[7] = initialM24;
  3402. result.m[8] = initialM31;
  3403. result.m[9] = initialM32;
  3404. result.m[10] = initialM33;
  3405. result.m[11] = initialM34;
  3406. result.m[12] = initialM41;
  3407. result.m[13] = initialM42;
  3408. result.m[14] = initialM43;
  3409. result.m[15] = initialM44;
  3410. result._markAsUpdated();
  3411. };
  3412. /**
  3413. * Returns the index-th row of the current matrix as a new Vector4.
  3414. */
  3415. Matrix.prototype.getRow = function (index) {
  3416. if (index < 0 || index > 3) {
  3417. return null;
  3418. }
  3419. var i = index * 4;
  3420. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3421. };
  3422. /**
  3423. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3424. * Returns the updated Matrix.
  3425. */
  3426. Matrix.prototype.setRow = function (index, row) {
  3427. if (index < 0 || index > 3) {
  3428. return this;
  3429. }
  3430. var i = index * 4;
  3431. this.m[i + 0] = row.x;
  3432. this.m[i + 1] = row.y;
  3433. this.m[i + 2] = row.z;
  3434. this.m[i + 3] = row.w;
  3435. this._markAsUpdated();
  3436. return this;
  3437. };
  3438. /**
  3439. * Compute the transpose of the matrix.
  3440. * Returns a new Matrix.
  3441. */
  3442. Matrix.prototype.transpose = function () {
  3443. return Matrix.Transpose(this);
  3444. };
  3445. /**
  3446. * Compute the transpose of the matrix.
  3447. * Returns the current matrix.
  3448. */
  3449. Matrix.prototype.transposeToRef = function (result) {
  3450. Matrix.TransposeToRef(this, result);
  3451. return this;
  3452. };
  3453. /**
  3454. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3455. * Returns the updated Matrix.
  3456. */
  3457. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3458. if (index < 0 || index > 3) {
  3459. return this;
  3460. }
  3461. var i = index * 4;
  3462. this.m[i + 0] = x;
  3463. this.m[i + 1] = y;
  3464. this.m[i + 2] = z;
  3465. this.m[i + 3] = w;
  3466. this._markAsUpdated();
  3467. return this;
  3468. };
  3469. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3470. /**
  3471. * Static identity matrix to be used as readonly matrix
  3472. * Must not be updated.
  3473. */
  3474. get: function () {
  3475. return Matrix._identityReadOnly;
  3476. },
  3477. enumerable: true,
  3478. configurable: true
  3479. });
  3480. /**
  3481. * Returns a new Matrix set from the 16 passed floats.
  3482. */
  3483. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3484. var result = new Matrix();
  3485. result.m[0] = initialM11;
  3486. result.m[1] = initialM12;
  3487. result.m[2] = initialM13;
  3488. result.m[3] = initialM14;
  3489. result.m[4] = initialM21;
  3490. result.m[5] = initialM22;
  3491. result.m[6] = initialM23;
  3492. result.m[7] = initialM24;
  3493. result.m[8] = initialM31;
  3494. result.m[9] = initialM32;
  3495. result.m[10] = initialM33;
  3496. result.m[11] = initialM34;
  3497. result.m[12] = initialM41;
  3498. result.m[13] = initialM42;
  3499. result.m[14] = initialM43;
  3500. result.m[15] = initialM44;
  3501. return result;
  3502. };
  3503. /**
  3504. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3505. */
  3506. Matrix.Compose = function (scale, rotation, translation) {
  3507. var result = Matrix.Identity();
  3508. Matrix.ComposeToRef(scale, rotation, translation, result);
  3509. return result;
  3510. };
  3511. /**
  3512. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3513. */
  3514. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3515. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3516. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3517. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3518. result.setTranslation(translation);
  3519. };
  3520. /**
  3521. * Returns a new indentity Matrix.
  3522. */
  3523. Matrix.Identity = function () {
  3524. 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);
  3525. };
  3526. /**
  3527. * Sets the passed "result" as an identity matrix.
  3528. */
  3529. Matrix.IdentityToRef = function (result) {
  3530. 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);
  3531. };
  3532. /**
  3533. * Returns a new zero Matrix.
  3534. */
  3535. Matrix.Zero = function () {
  3536. 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);
  3537. };
  3538. /**
  3539. * Returns a new rotation matrix for "angle" radians around the X axis.
  3540. */
  3541. Matrix.RotationX = function (angle) {
  3542. var result = new Matrix();
  3543. Matrix.RotationXToRef(angle, result);
  3544. return result;
  3545. };
  3546. /**
  3547. * Returns a new Matrix as the passed inverted one.
  3548. */
  3549. Matrix.Invert = function (source) {
  3550. var result = new Matrix();
  3551. source.invertToRef(result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3556. */
  3557. Matrix.RotationXToRef = function (angle, result) {
  3558. var s = Math.sin(angle);
  3559. var c = Math.cos(angle);
  3560. result.m[0] = 1.0;
  3561. result.m[15] = 1.0;
  3562. result.m[5] = c;
  3563. result.m[10] = c;
  3564. result.m[9] = -s;
  3565. result.m[6] = s;
  3566. result.m[1] = 0.0;
  3567. result.m[2] = 0.0;
  3568. result.m[3] = 0.0;
  3569. result.m[4] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[11] = 0.0;
  3573. result.m[12] = 0.0;
  3574. result.m[13] = 0.0;
  3575. result.m[14] = 0.0;
  3576. result._markAsUpdated();
  3577. };
  3578. /**
  3579. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3580. */
  3581. Matrix.RotationY = function (angle) {
  3582. var result = new Matrix();
  3583. Matrix.RotationYToRef(angle, result);
  3584. return result;
  3585. };
  3586. /**
  3587. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3588. */
  3589. Matrix.RotationYToRef = function (angle, result) {
  3590. var s = Math.sin(angle);
  3591. var c = Math.cos(angle);
  3592. result.m[5] = 1.0;
  3593. result.m[15] = 1.0;
  3594. result.m[0] = c;
  3595. result.m[2] = -s;
  3596. result.m[8] = s;
  3597. result.m[10] = c;
  3598. result.m[1] = 0.0;
  3599. result.m[3] = 0.0;
  3600. result.m[4] = 0.0;
  3601. result.m[6] = 0.0;
  3602. result.m[7] = 0.0;
  3603. result.m[9] = 0.0;
  3604. result.m[11] = 0.0;
  3605. result.m[12] = 0.0;
  3606. result.m[13] = 0.0;
  3607. result.m[14] = 0.0;
  3608. result._markAsUpdated();
  3609. };
  3610. /**
  3611. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3612. */
  3613. Matrix.RotationZ = function (angle) {
  3614. var result = new Matrix();
  3615. Matrix.RotationZToRef(angle, result);
  3616. return result;
  3617. };
  3618. /**
  3619. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3620. */
  3621. Matrix.RotationZToRef = function (angle, result) {
  3622. var s = Math.sin(angle);
  3623. var c = Math.cos(angle);
  3624. result.m[10] = 1.0;
  3625. result.m[15] = 1.0;
  3626. result.m[0] = c;
  3627. result.m[1] = s;
  3628. result.m[4] = -s;
  3629. result.m[5] = c;
  3630. result.m[2] = 0.0;
  3631. result.m[3] = 0.0;
  3632. result.m[6] = 0.0;
  3633. result.m[7] = 0.0;
  3634. result.m[8] = 0.0;
  3635. result.m[9] = 0.0;
  3636. result.m[11] = 0.0;
  3637. result.m[12] = 0.0;
  3638. result.m[13] = 0.0;
  3639. result.m[14] = 0.0;
  3640. result._markAsUpdated();
  3641. };
  3642. /**
  3643. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3644. */
  3645. Matrix.RotationAxis = function (axis, angle) {
  3646. var result = Matrix.Zero();
  3647. Matrix.RotationAxisToRef(axis, angle, result);
  3648. return result;
  3649. };
  3650. /**
  3651. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3652. */
  3653. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3654. var s = Math.sin(-angle);
  3655. var c = Math.cos(-angle);
  3656. var c1 = 1 - c;
  3657. axis.normalize();
  3658. result.m[0] = (axis.x * axis.x) * c1 + c;
  3659. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3660. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3661. result.m[3] = 0.0;
  3662. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3663. result.m[5] = (axis.y * axis.y) * c1 + c;
  3664. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3665. result.m[7] = 0.0;
  3666. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3667. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3668. result.m[10] = (axis.z * axis.z) * c1 + c;
  3669. result.m[11] = 0.0;
  3670. result.m[15] = 1.0;
  3671. result._markAsUpdated();
  3672. };
  3673. /**
  3674. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3675. */
  3676. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3677. var result = new Matrix();
  3678. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3679. return result;
  3680. };
  3681. /**
  3682. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3683. */
  3684. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3685. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3686. this._tempQuaternion.toRotationMatrix(result);
  3687. };
  3688. /**
  3689. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3690. */
  3691. Matrix.Scaling = function (x, y, z) {
  3692. var result = Matrix.Zero();
  3693. Matrix.ScalingToRef(x, y, z, result);
  3694. return result;
  3695. };
  3696. /**
  3697. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3698. */
  3699. Matrix.ScalingToRef = function (x, y, z, result) {
  3700. result.m[0] = x;
  3701. result.m[1] = 0.0;
  3702. result.m[2] = 0.0;
  3703. result.m[3] = 0.0;
  3704. result.m[4] = 0.0;
  3705. result.m[5] = y;
  3706. result.m[6] = 0.0;
  3707. result.m[7] = 0.0;
  3708. result.m[8] = 0.0;
  3709. result.m[9] = 0.0;
  3710. result.m[10] = z;
  3711. result.m[11] = 0.0;
  3712. result.m[12] = 0.0;
  3713. result.m[13] = 0.0;
  3714. result.m[14] = 0.0;
  3715. result.m[15] = 1.0;
  3716. result._markAsUpdated();
  3717. };
  3718. /**
  3719. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3720. */
  3721. Matrix.Translation = function (x, y, z) {
  3722. var result = Matrix.Identity();
  3723. Matrix.TranslationToRef(x, y, z, result);
  3724. return result;
  3725. };
  3726. /**
  3727. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3728. */
  3729. Matrix.TranslationToRef = function (x, y, z, result) {
  3730. 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);
  3731. };
  3732. /**
  3733. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3734. */
  3735. Matrix.Lerp = function (startValue, endValue, gradient) {
  3736. var result = Matrix.Zero();
  3737. for (var index = 0; index < 16; index++) {
  3738. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3739. }
  3740. result._markAsUpdated();
  3741. return result;
  3742. };
  3743. /**
  3744. * Returns a new Matrix whose values are computed by :
  3745. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3746. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3747. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3748. */
  3749. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3750. var startScale = new Vector3(0, 0, 0);
  3751. var startRotation = new Quaternion();
  3752. var startTranslation = new Vector3(0, 0, 0);
  3753. startValue.decompose(startScale, startRotation, startTranslation);
  3754. var endScale = new Vector3(0, 0, 0);
  3755. var endRotation = new Quaternion();
  3756. var endTranslation = new Vector3(0, 0, 0);
  3757. endValue.decompose(endScale, endRotation, endTranslation);
  3758. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3759. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3760. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3761. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3762. };
  3763. /**
  3764. * 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".
  3765. * This methods works for a Left-Handed system.
  3766. */
  3767. Matrix.LookAtLH = function (eye, target, up) {
  3768. var result = Matrix.Zero();
  3769. Matrix.LookAtLHToRef(eye, target, up, result);
  3770. return result;
  3771. };
  3772. /**
  3773. * 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".
  3774. * This methods works for a Left-Handed system.
  3775. */
  3776. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3777. // Z axis
  3778. target.subtractToRef(eye, this._zAxis);
  3779. this._zAxis.normalize();
  3780. // X axis
  3781. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3782. if (this._xAxis.lengthSquared() === 0) {
  3783. this._xAxis.x = 1.0;
  3784. }
  3785. else {
  3786. this._xAxis.normalize();
  3787. }
  3788. // Y axis
  3789. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3790. this._yAxis.normalize();
  3791. // Eye angles
  3792. var ex = -Vector3.Dot(this._xAxis, eye);
  3793. var ey = -Vector3.Dot(this._yAxis, eye);
  3794. var ez = -Vector3.Dot(this._zAxis, eye);
  3795. 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);
  3796. };
  3797. /**
  3798. * 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".
  3799. * This methods works for a Right-Handed system.
  3800. */
  3801. Matrix.LookAtRH = function (eye, target, up) {
  3802. var result = Matrix.Zero();
  3803. Matrix.LookAtRHToRef(eye, target, up, result);
  3804. return result;
  3805. };
  3806. /**
  3807. * 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".
  3808. * This methods works for a Left-Handed system.
  3809. */
  3810. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3811. // Z axis
  3812. eye.subtractToRef(target, this._zAxis);
  3813. this._zAxis.normalize();
  3814. // X axis
  3815. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3816. if (this._xAxis.lengthSquared() === 0) {
  3817. this._xAxis.x = 1.0;
  3818. }
  3819. else {
  3820. this._xAxis.normalize();
  3821. }
  3822. // Y axis
  3823. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3824. this._yAxis.normalize();
  3825. // Eye angles
  3826. var ex = -Vector3.Dot(this._xAxis, eye);
  3827. var ey = -Vector3.Dot(this._yAxis, eye);
  3828. var ez = -Vector3.Dot(this._zAxis, eye);
  3829. 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);
  3830. };
  3831. /**
  3832. * 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.
  3833. */
  3834. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3835. var matrix = Matrix.Zero();
  3836. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3837. return matrix;
  3838. };
  3839. /**
  3840. * 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.
  3841. */
  3842. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3843. var n = znear;
  3844. var f = zfar;
  3845. var a = 2.0 / width;
  3846. var b = 2.0 / height;
  3847. var c = 2.0 / (f - n);
  3848. var d = -(f + n) / (f - n);
  3849. 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);
  3850. };
  3851. /**
  3852. * 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.
  3853. */
  3854. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3855. var matrix = Matrix.Zero();
  3856. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3857. return matrix;
  3858. };
  3859. /**
  3860. * 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.
  3861. */
  3862. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3863. var n = znear;
  3864. var f = zfar;
  3865. var a = 2.0 / (right - left);
  3866. var b = 2.0 / (top - bottom);
  3867. var c = 2.0 / (f - n);
  3868. var d = -(f + n) / (f - n);
  3869. var i0 = (left + right) / (left - right);
  3870. var i1 = (top + bottom) / (bottom - top);
  3871. 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);
  3872. };
  3873. /**
  3874. * 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.
  3875. */
  3876. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3877. var matrix = Matrix.Zero();
  3878. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3879. return matrix;
  3880. };
  3881. /**
  3882. * 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.
  3883. */
  3884. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3885. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3886. result.m[10] *= -1.0;
  3887. };
  3888. /**
  3889. * 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.
  3890. */
  3891. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3892. var matrix = Matrix.Zero();
  3893. var n = znear;
  3894. var f = zfar;
  3895. var a = 2.0 * n / width;
  3896. var b = 2.0 * n / height;
  3897. var c = (f + n) / (f - n);
  3898. var d = -2.0 * f * n / (f - n);
  3899. 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);
  3900. return matrix;
  3901. };
  3902. /**
  3903. * 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.
  3904. */
  3905. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3906. var matrix = Matrix.Zero();
  3907. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3908. return matrix;
  3909. };
  3910. /**
  3911. * 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.
  3912. */
  3913. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3914. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3915. var n = znear;
  3916. var f = zfar;
  3917. var t = 1.0 / (Math.tan(fov * 0.5));
  3918. var a = isVerticalFovFixed ? (t / aspect) : t;
  3919. var b = isVerticalFovFixed ? t : (t * aspect);
  3920. var c = (f + n) / (f - n);
  3921. var d = -2.0 * f * n / (f - n);
  3922. 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);
  3923. };
  3924. /**
  3925. * 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.
  3926. */
  3927. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3928. var matrix = Matrix.Zero();
  3929. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3930. return matrix;
  3931. };
  3932. /**
  3933. * 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.
  3934. */
  3935. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3936. //alternatively this could be expressed as:
  3937. // m = PerspectiveFovLHToRef
  3938. // m[10] *= -1.0;
  3939. // m[11] *= -1.0;
  3940. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3941. var n = znear;
  3942. var f = zfar;
  3943. var t = 1.0 / (Math.tan(fov * 0.5));
  3944. var a = isVerticalFovFixed ? (t / aspect) : t;
  3945. var b = isVerticalFovFixed ? t : (t * aspect);
  3946. var c = -(f + n) / (f - n);
  3947. var d = -2 * f * n / (f - n);
  3948. 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);
  3949. };
  3950. /**
  3951. * 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.
  3952. */
  3953. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3954. if (rightHanded === void 0) { rightHanded = false; }
  3955. var rightHandedFactor = rightHanded ? -1 : 1;
  3956. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3957. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3958. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3959. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3960. var xScale = 2.0 / (leftTan + rightTan);
  3961. var yScale = 2.0 / (upTan + downTan);
  3962. result.m[0] = xScale;
  3963. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3964. result.m[5] = yScale;
  3965. result.m[6] = result.m[7] = 0.0;
  3966. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3967. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3968. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3969. result.m[10] = -zfar / (znear - zfar);
  3970. result.m[11] = 1.0 * rightHandedFactor;
  3971. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3972. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3973. // result.m[14] = (znear * zfar) / (znear - zfar);
  3974. result._markAsUpdated();
  3975. };
  3976. /**
  3977. * Returns the final transformation matrix : world * view * projection * viewport
  3978. */
  3979. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3980. var cw = viewport.width;
  3981. var ch = viewport.height;
  3982. var cx = viewport.x;
  3983. var cy = viewport.y;
  3984. 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);
  3985. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3986. };
  3987. /**
  3988. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3989. */
  3990. Matrix.GetAsMatrix2x2 = function (matrix) {
  3991. return new Float32Array([
  3992. matrix.m[0], matrix.m[1],
  3993. matrix.m[4], matrix.m[5]
  3994. ]);
  3995. };
  3996. /**
  3997. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3998. */
  3999. Matrix.GetAsMatrix3x3 = function (matrix) {
  4000. return new Float32Array([
  4001. matrix.m[0], matrix.m[1], matrix.m[2],
  4002. matrix.m[4], matrix.m[5], matrix.m[6],
  4003. matrix.m[8], matrix.m[9], matrix.m[10]
  4004. ]);
  4005. };
  4006. /**
  4007. * Compute the transpose of the passed Matrix.
  4008. * Returns a new Matrix.
  4009. */
  4010. Matrix.Transpose = function (matrix) {
  4011. var result = new Matrix();
  4012. Matrix.TransposeToRef(matrix, result);
  4013. return result;
  4014. };
  4015. /**
  4016. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4017. */
  4018. Matrix.TransposeToRef = function (matrix, result) {
  4019. result.m[0] = matrix.m[0];
  4020. result.m[1] = matrix.m[4];
  4021. result.m[2] = matrix.m[8];
  4022. result.m[3] = matrix.m[12];
  4023. result.m[4] = matrix.m[1];
  4024. result.m[5] = matrix.m[5];
  4025. result.m[6] = matrix.m[9];
  4026. result.m[7] = matrix.m[13];
  4027. result.m[8] = matrix.m[2];
  4028. result.m[9] = matrix.m[6];
  4029. result.m[10] = matrix.m[10];
  4030. result.m[11] = matrix.m[14];
  4031. result.m[12] = matrix.m[3];
  4032. result.m[13] = matrix.m[7];
  4033. result.m[14] = matrix.m[11];
  4034. result.m[15] = matrix.m[15];
  4035. };
  4036. /**
  4037. * Returns a new Matrix as the reflection matrix across the passed plane.
  4038. */
  4039. Matrix.Reflection = function (plane) {
  4040. var matrix = new Matrix();
  4041. Matrix.ReflectionToRef(plane, matrix);
  4042. return matrix;
  4043. };
  4044. /**
  4045. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4046. */
  4047. Matrix.ReflectionToRef = function (plane, result) {
  4048. plane.normalize();
  4049. var x = plane.normal.x;
  4050. var y = plane.normal.y;
  4051. var z = plane.normal.z;
  4052. var temp = -2 * x;
  4053. var temp2 = -2 * y;
  4054. var temp3 = -2 * z;
  4055. result.m[0] = (temp * x) + 1;
  4056. result.m[1] = temp2 * x;
  4057. result.m[2] = temp3 * x;
  4058. result.m[3] = 0.0;
  4059. result.m[4] = temp * y;
  4060. result.m[5] = (temp2 * y) + 1;
  4061. result.m[6] = temp3 * y;
  4062. result.m[7] = 0.0;
  4063. result.m[8] = temp * z;
  4064. result.m[9] = temp2 * z;
  4065. result.m[10] = (temp3 * z) + 1;
  4066. result.m[11] = 0.0;
  4067. result.m[12] = temp * plane.d;
  4068. result.m[13] = temp2 * plane.d;
  4069. result.m[14] = temp3 * plane.d;
  4070. result.m[15] = 1.0;
  4071. result._markAsUpdated();
  4072. };
  4073. /**
  4074. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4075. */
  4076. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4077. result.m[0] = xaxis.x;
  4078. result.m[1] = xaxis.y;
  4079. result.m[2] = xaxis.z;
  4080. result.m[3] = 0.0;
  4081. result.m[4] = yaxis.x;
  4082. result.m[5] = yaxis.y;
  4083. result.m[6] = yaxis.z;
  4084. result.m[7] = 0.0;
  4085. result.m[8] = zaxis.x;
  4086. result.m[9] = zaxis.y;
  4087. result.m[10] = zaxis.z;
  4088. result.m[11] = 0.0;
  4089. result.m[12] = 0.0;
  4090. result.m[13] = 0.0;
  4091. result.m[14] = 0.0;
  4092. result.m[15] = 1.0;
  4093. result._markAsUpdated();
  4094. };
  4095. /**
  4096. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4097. */
  4098. Matrix.FromQuaternionToRef = function (quat, result) {
  4099. var xx = quat.x * quat.x;
  4100. var yy = quat.y * quat.y;
  4101. var zz = quat.z * quat.z;
  4102. var xy = quat.x * quat.y;
  4103. var zw = quat.z * quat.w;
  4104. var zx = quat.z * quat.x;
  4105. var yw = quat.y * quat.w;
  4106. var yz = quat.y * quat.z;
  4107. var xw = quat.x * quat.w;
  4108. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4109. result.m[1] = 2.0 * (xy + zw);
  4110. result.m[2] = 2.0 * (zx - yw);
  4111. result.m[3] = 0.0;
  4112. result.m[4] = 2.0 * (xy - zw);
  4113. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4114. result.m[6] = 2.0 * (yz + xw);
  4115. result.m[7] = 0.0;
  4116. result.m[8] = 2.0 * (zx + yw);
  4117. result.m[9] = 2.0 * (yz - xw);
  4118. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4119. result.m[11] = 0.0;
  4120. result.m[12] = 0.0;
  4121. result.m[13] = 0.0;
  4122. result.m[14] = 0.0;
  4123. result.m[15] = 1.0;
  4124. result._markAsUpdated();
  4125. };
  4126. Matrix._tempQuaternion = new Quaternion();
  4127. Matrix._xAxis = Vector3.Zero();
  4128. Matrix._yAxis = Vector3.Zero();
  4129. Matrix._zAxis = Vector3.Zero();
  4130. Matrix._updateFlagSeed = 0;
  4131. Matrix._identityReadOnly = Matrix.Identity();
  4132. return Matrix;
  4133. }());
  4134. BABYLON.Matrix = Matrix;
  4135. var Plane = /** @class */ (function () {
  4136. /**
  4137. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4138. */
  4139. function Plane(a, b, c, d) {
  4140. this.normal = new Vector3(a, b, c);
  4141. this.d = d;
  4142. }
  4143. /**
  4144. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4145. */
  4146. Plane.prototype.asArray = function () {
  4147. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4148. };
  4149. // Methods
  4150. /**
  4151. * Returns a new plane copied from the current Plane.
  4152. */
  4153. Plane.prototype.clone = function () {
  4154. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4155. };
  4156. /**
  4157. * Returns the string "Plane".
  4158. */
  4159. Plane.prototype.getClassName = function () {
  4160. return "Plane";
  4161. };
  4162. /**
  4163. * Returns the Plane hash code.
  4164. */
  4165. Plane.prototype.getHashCode = function () {
  4166. var hash = this.normal.getHashCode();
  4167. hash = (hash * 397) ^ (this.d || 0);
  4168. return hash;
  4169. };
  4170. /**
  4171. * Normalize the current Plane in place.
  4172. * Returns the updated Plane.
  4173. */
  4174. Plane.prototype.normalize = function () {
  4175. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4176. var magnitude = 0.0;
  4177. if (norm !== 0) {
  4178. magnitude = 1.0 / norm;
  4179. }
  4180. this.normal.x *= magnitude;
  4181. this.normal.y *= magnitude;
  4182. this.normal.z *= magnitude;
  4183. this.d *= magnitude;
  4184. return this;
  4185. };
  4186. /**
  4187. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4188. */
  4189. Plane.prototype.transform = function (transformation) {
  4190. var transposedMatrix = Matrix.Transpose(transformation);
  4191. var x = this.normal.x;
  4192. var y = this.normal.y;
  4193. var z = this.normal.z;
  4194. var d = this.d;
  4195. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4196. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4197. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4198. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4199. return new Plane(normalX, normalY, normalZ, finalD);
  4200. };
  4201. /**
  4202. * Returns the dot product (float) of the point coordinates and the plane normal.
  4203. */
  4204. Plane.prototype.dotCoordinate = function (point) {
  4205. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4206. };
  4207. /**
  4208. * Updates the current Plane from the plane defined by the three passed points.
  4209. * Returns the updated Plane.
  4210. */
  4211. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4212. var x1 = point2.x - point1.x;
  4213. var y1 = point2.y - point1.y;
  4214. var z1 = point2.z - point1.z;
  4215. var x2 = point3.x - point1.x;
  4216. var y2 = point3.y - point1.y;
  4217. var z2 = point3.z - point1.z;
  4218. var yz = (y1 * z2) - (z1 * y2);
  4219. var xz = (z1 * x2) - (x1 * z2);
  4220. var xy = (x1 * y2) - (y1 * x2);
  4221. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4222. var invPyth;
  4223. if (pyth !== 0) {
  4224. invPyth = 1.0 / pyth;
  4225. }
  4226. else {
  4227. invPyth = 0.0;
  4228. }
  4229. this.normal.x = yz * invPyth;
  4230. this.normal.y = xz * invPyth;
  4231. this.normal.z = xy * invPyth;
  4232. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4233. return this;
  4234. };
  4235. /**
  4236. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4237. */
  4238. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4239. var dot = Vector3.Dot(this.normal, direction);
  4240. return (dot <= epsilon);
  4241. };
  4242. /**
  4243. * Returns the signed distance (float) from the passed point to the Plane.
  4244. */
  4245. Plane.prototype.signedDistanceTo = function (point) {
  4246. return Vector3.Dot(point, this.normal) + this.d;
  4247. };
  4248. // Statics
  4249. /**
  4250. * Returns a new Plane from the passed array.
  4251. */
  4252. Plane.FromArray = function (array) {
  4253. return new Plane(array[0], array[1], array[2], array[3]);
  4254. };
  4255. /**
  4256. * Returns a new Plane defined by the three passed points.
  4257. */
  4258. Plane.FromPoints = function (point1, point2, point3) {
  4259. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4260. result.copyFromPoints(point1, point2, point3);
  4261. return result;
  4262. };
  4263. /**
  4264. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4265. * Note : the vector "normal" is updated because normalized.
  4266. */
  4267. Plane.FromPositionAndNormal = function (origin, normal) {
  4268. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4269. normal.normalize();
  4270. result.normal = normal;
  4271. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4272. return result;
  4273. };
  4274. /**
  4275. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4276. */
  4277. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4278. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4279. return Vector3.Dot(point, normal) + d;
  4280. };
  4281. return Plane;
  4282. }());
  4283. BABYLON.Plane = Plane;
  4284. var Viewport = /** @class */ (function () {
  4285. /**
  4286. * Creates a Viewport object located at (x, y) and sized (width, height).
  4287. */
  4288. function Viewport(x, y, width, height) {
  4289. this.x = x;
  4290. this.y = y;
  4291. this.width = width;
  4292. this.height = height;
  4293. }
  4294. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4295. if (renderWidthOrEngine.getRenderWidth) {
  4296. var engine = renderWidthOrEngine;
  4297. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4298. }
  4299. var renderWidth = renderWidthOrEngine;
  4300. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4301. };
  4302. /**
  4303. * Returns a new Viewport copied from the current one.
  4304. */
  4305. Viewport.prototype.clone = function () {
  4306. return new Viewport(this.x, this.y, this.width, this.height);
  4307. };
  4308. return Viewport;
  4309. }());
  4310. BABYLON.Viewport = Viewport;
  4311. var Frustum = /** @class */ (function () {
  4312. function Frustum() {
  4313. }
  4314. /**
  4315. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4316. */
  4317. Frustum.GetPlanes = function (transform) {
  4318. var frustumPlanes = [];
  4319. for (var index = 0; index < 6; index++) {
  4320. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4321. }
  4322. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4323. return frustumPlanes;
  4324. };
  4325. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4326. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4327. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4328. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4329. frustumPlane.d = transform.m[15] + transform.m[14];
  4330. frustumPlane.normalize();
  4331. };
  4332. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4333. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4334. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4335. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4336. frustumPlane.d = transform.m[15] - transform.m[14];
  4337. frustumPlane.normalize();
  4338. };
  4339. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4340. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4341. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4342. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4343. frustumPlane.d = transform.m[15] + transform.m[12];
  4344. frustumPlane.normalize();
  4345. };
  4346. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4347. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4348. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4349. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4350. frustumPlane.d = transform.m[15] - transform.m[12];
  4351. frustumPlane.normalize();
  4352. };
  4353. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4354. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4355. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4356. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4357. frustumPlane.d = transform.m[15] - transform.m[13];
  4358. frustumPlane.normalize();
  4359. };
  4360. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4361. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4362. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4363. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4364. frustumPlane.d = transform.m[15] + transform.m[13];
  4365. frustumPlane.normalize();
  4366. };
  4367. /**
  4368. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4369. */
  4370. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4371. // Near
  4372. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4373. // Far
  4374. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4375. // Left
  4376. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4377. // Right
  4378. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4379. // Top
  4380. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4381. // Bottom
  4382. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4383. };
  4384. return Frustum;
  4385. }());
  4386. BABYLON.Frustum = Frustum;
  4387. var Space;
  4388. (function (Space) {
  4389. Space[Space["LOCAL"] = 0] = "LOCAL";
  4390. Space[Space["WORLD"] = 1] = "WORLD";
  4391. Space[Space["BONE"] = 2] = "BONE";
  4392. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4393. var Axis = /** @class */ (function () {
  4394. function Axis() {
  4395. }
  4396. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4397. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4398. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4399. return Axis;
  4400. }());
  4401. BABYLON.Axis = Axis;
  4402. ;
  4403. var BezierCurve = /** @class */ (function () {
  4404. function BezierCurve() {
  4405. }
  4406. /**
  4407. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4408. */
  4409. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4410. // Extract X (which is equal to time here)
  4411. var f0 = 1 - 3 * x2 + 3 * x1;
  4412. var f1 = 3 * x2 - 6 * x1;
  4413. var f2 = 3 * x1;
  4414. var refinedT = t;
  4415. for (var i = 0; i < 5; i++) {
  4416. var refinedT2 = refinedT * refinedT;
  4417. var refinedT3 = refinedT2 * refinedT;
  4418. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4419. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4420. refinedT -= (x - t) * slope;
  4421. refinedT = Math.min(1, Math.max(0, refinedT));
  4422. }
  4423. // Resolve cubic bezier for the given x
  4424. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4425. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4426. Math.pow(refinedT, 3);
  4427. };
  4428. return BezierCurve;
  4429. }());
  4430. BABYLON.BezierCurve = BezierCurve;
  4431. var Orientation;
  4432. (function (Orientation) {
  4433. Orientation[Orientation["CW"] = 0] = "CW";
  4434. Orientation[Orientation["CCW"] = 1] = "CCW";
  4435. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4436. var Angle = /** @class */ (function () {
  4437. /**
  4438. * Creates an Angle object of "radians" radians (float).
  4439. */
  4440. function Angle(radians) {
  4441. var _this = this;
  4442. /**
  4443. * Returns the Angle value in degrees (float).
  4444. */
  4445. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4446. /**
  4447. * Returns the Angle value in radians (float).
  4448. */
  4449. this.radians = function () { return _this._radians; };
  4450. this._radians = radians;
  4451. if (this._radians < 0.0)
  4452. this._radians += (2.0 * Math.PI);
  4453. }
  4454. /**
  4455. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4456. */
  4457. Angle.BetweenTwoPoints = function (a, b) {
  4458. var delta = b.subtract(a);
  4459. var theta = Math.atan2(delta.y, delta.x);
  4460. return new Angle(theta);
  4461. };
  4462. /**
  4463. * Returns a new Angle object from the passed float in radians.
  4464. */
  4465. Angle.FromRadians = function (radians) {
  4466. return new Angle(radians);
  4467. };
  4468. /**
  4469. * Returns a new Angle object from the passed float in degrees.
  4470. */
  4471. Angle.FromDegrees = function (degrees) {
  4472. return new Angle(degrees * Math.PI / 180.0);
  4473. };
  4474. return Angle;
  4475. }());
  4476. BABYLON.Angle = Angle;
  4477. var Arc2 = /** @class */ (function () {
  4478. /**
  4479. * Creates an Arc object from the three passed points : start, middle and end.
  4480. */
  4481. function Arc2(startPoint, midPoint, endPoint) {
  4482. this.startPoint = startPoint;
  4483. this.midPoint = midPoint;
  4484. this.endPoint = endPoint;
  4485. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4486. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4487. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4488. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4489. 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);
  4490. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4491. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4492. var a1 = this.startAngle.degrees();
  4493. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4494. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4495. // angles correction
  4496. if (a2 - a1 > +180.0)
  4497. a2 -= 360.0;
  4498. if (a2 - a1 < -180.0)
  4499. a2 += 360.0;
  4500. if (a3 - a2 > +180.0)
  4501. a3 -= 360.0;
  4502. if (a3 - a2 < -180.0)
  4503. a3 += 360.0;
  4504. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4505. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4506. }
  4507. return Arc2;
  4508. }());
  4509. BABYLON.Arc2 = Arc2;
  4510. var Path2 = /** @class */ (function () {
  4511. /**
  4512. * Creates a Path2 object from the starting 2D coordinates x and y.
  4513. */
  4514. function Path2(x, y) {
  4515. this._points = new Array();
  4516. this._length = 0.0;
  4517. this.closed = false;
  4518. this._points.push(new Vector2(x, y));
  4519. }
  4520. /**
  4521. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4522. * Returns the updated Path2.
  4523. */
  4524. Path2.prototype.addLineTo = function (x, y) {
  4525. if (this.closed) {
  4526. //Tools.Error("cannot add lines to closed paths");
  4527. return this;
  4528. }
  4529. var newPoint = new Vector2(x, y);
  4530. var previousPoint = this._points[this._points.length - 1];
  4531. this._points.push(newPoint);
  4532. this._length += newPoint.subtract(previousPoint).length();
  4533. return this;
  4534. };
  4535. /**
  4536. * 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.
  4537. * Returns the updated Path2.
  4538. */
  4539. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4540. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4541. if (this.closed) {
  4542. //Tools.Error("cannot add arcs to closed paths");
  4543. return this;
  4544. }
  4545. var startPoint = this._points[this._points.length - 1];
  4546. var midPoint = new Vector2(midX, midY);
  4547. var endPoint = new Vector2(endX, endY);
  4548. var arc = new Arc2(startPoint, midPoint, endPoint);
  4549. var increment = arc.angle.radians() / numberOfSegments;
  4550. if (arc.orientation === Orientation.CW)
  4551. increment *= -1;
  4552. var currentAngle = arc.startAngle.radians() + increment;
  4553. for (var i = 0; i < numberOfSegments; i++) {
  4554. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4555. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4556. this.addLineTo(x, y);
  4557. currentAngle += increment;
  4558. }
  4559. return this;
  4560. };
  4561. /**
  4562. * Closes the Path2.
  4563. * Returns the Path2.
  4564. */
  4565. Path2.prototype.close = function () {
  4566. this.closed = true;
  4567. return this;
  4568. };
  4569. /**
  4570. * Returns the Path2 total length (float).
  4571. */
  4572. Path2.prototype.length = function () {
  4573. var result = this._length;
  4574. if (!this.closed) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var firstPoint = this._points[0];
  4577. result += (firstPoint.subtract(lastPoint).length());
  4578. }
  4579. return result;
  4580. };
  4581. /**
  4582. * Returns the Path2 internal array of points.
  4583. */
  4584. Path2.prototype.getPoints = function () {
  4585. return this._points;
  4586. };
  4587. /**
  4588. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4589. */
  4590. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4591. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4592. //Tools.Error("normalized length position should be between 0 and 1.");
  4593. return Vector2.Zero();
  4594. }
  4595. var lengthPosition = normalizedLengthPosition * this.length();
  4596. var previousOffset = 0;
  4597. for (var i = 0; i < this._points.length; i++) {
  4598. var j = (i + 1) % this._points.length;
  4599. var a = this._points[i];
  4600. var b = this._points[j];
  4601. var bToA = b.subtract(a);
  4602. var nextOffset = (bToA.length() + previousOffset);
  4603. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4604. var dir = bToA.normalize();
  4605. var localOffset = lengthPosition - previousOffset;
  4606. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4607. }
  4608. previousOffset = nextOffset;
  4609. }
  4610. //Tools.Error("internal error");
  4611. return Vector2.Zero();
  4612. };
  4613. /**
  4614. * Returns a new Path2 starting at the coordinates (x, y).
  4615. */
  4616. Path2.StartingAt = function (x, y) {
  4617. return new Path2(x, y);
  4618. };
  4619. return Path2;
  4620. }());
  4621. BABYLON.Path2 = Path2;
  4622. var Path3D = /** @class */ (function () {
  4623. /**
  4624. * new Path3D(path, normal, raw)
  4625. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4626. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4627. * path : an array of Vector3, the curve axis of the Path3D
  4628. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4629. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4630. */
  4631. function Path3D(path, firstNormal, raw) {
  4632. if (firstNormal === void 0) { firstNormal = null; }
  4633. this.path = path;
  4634. this._curve = new Array();
  4635. this._distances = new Array();
  4636. this._tangents = new Array();
  4637. this._normals = new Array();
  4638. this._binormals = new Array();
  4639. for (var p = 0; p < path.length; p++) {
  4640. this._curve[p] = path[p].clone(); // hard copy
  4641. }
  4642. this._raw = raw || false;
  4643. this._compute(firstNormal);
  4644. }
  4645. /**
  4646. * Returns the Path3D array of successive Vector3 designing its curve.
  4647. */
  4648. Path3D.prototype.getCurve = function () {
  4649. return this._curve;
  4650. };
  4651. /**
  4652. * Returns an array populated with tangent vectors on each Path3D curve point.
  4653. */
  4654. Path3D.prototype.getTangents = function () {
  4655. return this._tangents;
  4656. };
  4657. /**
  4658. * Returns an array populated with normal vectors on each Path3D curve point.
  4659. */
  4660. Path3D.prototype.getNormals = function () {
  4661. return this._normals;
  4662. };
  4663. /**
  4664. * Returns an array populated with binormal vectors on each Path3D curve point.
  4665. */
  4666. Path3D.prototype.getBinormals = function () {
  4667. return this._binormals;
  4668. };
  4669. /**
  4670. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4671. */
  4672. Path3D.prototype.getDistances = function () {
  4673. return this._distances;
  4674. };
  4675. /**
  4676. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4677. * Returns the same object updated.
  4678. */
  4679. Path3D.prototype.update = function (path, firstNormal) {
  4680. if (firstNormal === void 0) { firstNormal = null; }
  4681. for (var p = 0; p < path.length; p++) {
  4682. this._curve[p].x = path[p].x;
  4683. this._curve[p].y = path[p].y;
  4684. this._curve[p].z = path[p].z;
  4685. }
  4686. this._compute(firstNormal);
  4687. return this;
  4688. };
  4689. // private function compute() : computes tangents, normals and binormals
  4690. Path3D.prototype._compute = function (firstNormal) {
  4691. var l = this._curve.length;
  4692. // first and last tangents
  4693. this._tangents[0] = this._getFirstNonNullVector(0);
  4694. if (!this._raw) {
  4695. this._tangents[0].normalize();
  4696. }
  4697. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4698. if (!this._raw) {
  4699. this._tangents[l - 1].normalize();
  4700. }
  4701. // normals and binormals at first point : arbitrary vector with _normalVector()
  4702. var tg0 = this._tangents[0];
  4703. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4704. this._normals[0] = pp0;
  4705. if (!this._raw) {
  4706. this._normals[0].normalize();
  4707. }
  4708. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4709. if (!this._raw) {
  4710. this._binormals[0].normalize();
  4711. }
  4712. this._distances[0] = 0.0;
  4713. // normals and binormals : next points
  4714. var prev; // previous vector (segment)
  4715. var cur; // current vector (segment)
  4716. var curTang; // current tangent
  4717. // previous normal
  4718. var prevBinor; // previous binormal
  4719. for (var i = 1; i < l; i++) {
  4720. // tangents
  4721. prev = this._getLastNonNullVector(i);
  4722. if (i < l - 1) {
  4723. cur = this._getFirstNonNullVector(i);
  4724. this._tangents[i] = prev.add(cur);
  4725. this._tangents[i].normalize();
  4726. }
  4727. this._distances[i] = this._distances[i - 1] + prev.length();
  4728. // normals and binormals
  4729. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4730. curTang = this._tangents[i];
  4731. prevBinor = this._binormals[i - 1];
  4732. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4733. if (!this._raw) {
  4734. this._normals[i].normalize();
  4735. }
  4736. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4737. if (!this._raw) {
  4738. this._binormals[i].normalize();
  4739. }
  4740. }
  4741. };
  4742. // private function getFirstNonNullVector(index)
  4743. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4744. Path3D.prototype._getFirstNonNullVector = function (index) {
  4745. var i = 1;
  4746. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4747. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4748. i++;
  4749. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4750. }
  4751. return nNVector;
  4752. };
  4753. // private function getLastNonNullVector(index)
  4754. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4755. Path3D.prototype._getLastNonNullVector = function (index) {
  4756. var i = 1;
  4757. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4758. while (nLVector.length() === 0 && index > i + 1) {
  4759. i++;
  4760. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4761. }
  4762. return nLVector;
  4763. };
  4764. // private function normalVector(v0, vt, va) :
  4765. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4766. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4767. Path3D.prototype._normalVector = function (v0, vt, va) {
  4768. var normal0;
  4769. var tgl = vt.length();
  4770. if (tgl === 0.0) {
  4771. tgl = 1.0;
  4772. }
  4773. if (va === undefined || va === null) {
  4774. var point;
  4775. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4776. point = new Vector3(0.0, -1.0, 0.0);
  4777. }
  4778. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4779. point = new Vector3(1.0, 0.0, 0.0);
  4780. }
  4781. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4782. point = new Vector3(0.0, 0.0, 1.0);
  4783. }
  4784. else {
  4785. point = Vector3.Zero();
  4786. }
  4787. normal0 = Vector3.Cross(vt, point);
  4788. }
  4789. else {
  4790. normal0 = Vector3.Cross(vt, va);
  4791. Vector3.CrossToRef(normal0, vt, normal0);
  4792. }
  4793. normal0.normalize();
  4794. return normal0;
  4795. };
  4796. return Path3D;
  4797. }());
  4798. BABYLON.Path3D = Path3D;
  4799. var Curve3 = /** @class */ (function () {
  4800. /**
  4801. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4802. * A Curve3 is designed from a series of successive Vector3.
  4803. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4804. */
  4805. function Curve3(points) {
  4806. this._length = 0.0;
  4807. this._points = points;
  4808. this._length = this._computeLength(points);
  4809. }
  4810. /**
  4811. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4812. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4813. * @param v1 (Vector3) the control point
  4814. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4815. * @param nbPoints (integer) the wanted number of points in the curve
  4816. */
  4817. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4818. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4819. var bez = new Array();
  4820. var equation = function (t, val0, val1, val2) {
  4821. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4822. return res;
  4823. };
  4824. for (var i = 0; i <= nbPoints; i++) {
  4825. 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)));
  4826. }
  4827. return new Curve3(bez);
  4828. };
  4829. /**
  4830. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4831. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4832. * @param v1 (Vector3) the first control point
  4833. * @param v2 (Vector3) the second control point
  4834. * @param v3 (Vector3) the end point of the Cubic Bezier
  4835. * @param nbPoints (integer) the wanted number of points in the curve
  4836. */
  4837. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4838. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4839. var bez = new Array();
  4840. var equation = function (t, val0, val1, val2, val3) {
  4841. 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;
  4842. return res;
  4843. };
  4844. for (var i = 0; i <= nbPoints; i++) {
  4845. 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)));
  4846. }
  4847. return new Curve3(bez);
  4848. };
  4849. /**
  4850. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4851. * @param p1 (Vector3) the origin point of the Hermite Spline
  4852. * @param t1 (Vector3) the tangent vector at the origin point
  4853. * @param p2 (Vector3) the end point of the Hermite Spline
  4854. * @param t2 (Vector3) the tangent vector at the end point
  4855. * @param nbPoints (integer) the wanted number of points in the curve
  4856. */
  4857. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4858. var hermite = new Array();
  4859. var step = 1.0 / nbPoints;
  4860. for (var i = 0; i <= nbPoints; i++) {
  4861. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4862. }
  4863. return new Curve3(hermite);
  4864. };
  4865. /**
  4866. * Returns a Curve3 object along a CatmullRom Spline curve :
  4867. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4868. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4869. */
  4870. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4871. var totalPoints = new Array();
  4872. totalPoints.push(points[0].clone());
  4873. Array.prototype.push.apply(totalPoints, points);
  4874. totalPoints.push(points[points.length - 1].clone());
  4875. var catmullRom = new Array();
  4876. var step = 1.0 / nbPoints;
  4877. var amount = 0.0;
  4878. for (var i = 0; i < totalPoints.length - 3; i++) {
  4879. amount = 0;
  4880. for (var c = 0; c < nbPoints; c++) {
  4881. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4882. amount += step;
  4883. }
  4884. }
  4885. i--;
  4886. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4887. return new Curve3(catmullRom);
  4888. };
  4889. /**
  4890. * Returns the Curve3 stored array of successive Vector3
  4891. */
  4892. Curve3.prototype.getPoints = function () {
  4893. return this._points;
  4894. };
  4895. /**
  4896. * Returns the computed length (float) of the curve.
  4897. */
  4898. Curve3.prototype.length = function () {
  4899. return this._length;
  4900. };
  4901. /**
  4902. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4903. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4904. * curveA and curveB keep unchanged.
  4905. */
  4906. Curve3.prototype.continue = function (curve) {
  4907. var lastPoint = this._points[this._points.length - 1];
  4908. var continuedPoints = this._points.slice();
  4909. var curvePoints = curve.getPoints();
  4910. for (var i = 1; i < curvePoints.length; i++) {
  4911. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4912. }
  4913. var continuedCurve = new Curve3(continuedPoints);
  4914. return continuedCurve;
  4915. };
  4916. Curve3.prototype._computeLength = function (path) {
  4917. var l = 0;
  4918. for (var i = 1; i < path.length; i++) {
  4919. l += (path[i].subtract(path[i - 1])).length();
  4920. }
  4921. return l;
  4922. };
  4923. return Curve3;
  4924. }());
  4925. BABYLON.Curve3 = Curve3;
  4926. // Vertex formats
  4927. var PositionNormalVertex = /** @class */ (function () {
  4928. function PositionNormalVertex(position, normal) {
  4929. if (position === void 0) { position = Vector3.Zero(); }
  4930. if (normal === void 0) { normal = Vector3.Up(); }
  4931. this.position = position;
  4932. this.normal = normal;
  4933. }
  4934. PositionNormalVertex.prototype.clone = function () {
  4935. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4936. };
  4937. return PositionNormalVertex;
  4938. }());
  4939. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4940. var PositionNormalTextureVertex = /** @class */ (function () {
  4941. function PositionNormalTextureVertex(position, normal, uv) {
  4942. if (position === void 0) { position = Vector3.Zero(); }
  4943. if (normal === void 0) { normal = Vector3.Up(); }
  4944. if (uv === void 0) { uv = Vector2.Zero(); }
  4945. this.position = position;
  4946. this.normal = normal;
  4947. this.uv = uv;
  4948. }
  4949. PositionNormalTextureVertex.prototype.clone = function () {
  4950. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4951. };
  4952. return PositionNormalTextureVertex;
  4953. }());
  4954. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4955. // Temporary pre-allocated objects for engine internal use
  4956. // usage in any internal function :
  4957. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4958. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4959. var Tmp = /** @class */ (function () {
  4960. function Tmp() {
  4961. }
  4962. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4963. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4964. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4965. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4966. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4967. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4968. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4969. Matrix.Zero(), Matrix.Zero(),
  4970. Matrix.Zero(), Matrix.Zero(),
  4971. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4972. return Tmp;
  4973. }());
  4974. BABYLON.Tmp = Tmp;
  4975. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4976. var MathTmp = /** @class */ (function () {
  4977. function MathTmp() {
  4978. }
  4979. MathTmp.Vector3 = [Vector3.Zero()];
  4980. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4981. MathTmp.Quaternion = [Quaternion.Zero()];
  4982. return MathTmp;
  4983. }());
  4984. })(BABYLON || (BABYLON = {}));
  4985. //# sourceMappingURL=babylon.math.js.map
  4986. var BABYLON;
  4987. (function (BABYLON) {
  4988. var Scalar = /** @class */ (function () {
  4989. function Scalar() {
  4990. }
  4991. /**
  4992. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4993. */
  4994. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4995. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4996. var num = a - b;
  4997. return -epsilon <= num && num <= epsilon;
  4998. };
  4999. /**
  5000. * Returns a string : the upper case translation of the number i to hexadecimal.
  5001. */
  5002. Scalar.ToHex = function (i) {
  5003. var str = i.toString(16);
  5004. if (i <= 15) {
  5005. return ("0" + str).toUpperCase();
  5006. }
  5007. return str.toUpperCase();
  5008. };
  5009. /**
  5010. * Returns -1 if value is negative and +1 is value is positive.
  5011. * Returns the value itself if it's equal to zero.
  5012. */
  5013. Scalar.Sign = function (value) {
  5014. value = +value; // convert to a number
  5015. if (value === 0 || isNaN(value))
  5016. return value;
  5017. return value > 0 ? 1 : -1;
  5018. };
  5019. /**
  5020. * Returns the value itself if it's between min and max.
  5021. * Returns min if the value is lower than min.
  5022. * Returns max if the value is greater than max.
  5023. */
  5024. Scalar.Clamp = function (value, min, max) {
  5025. if (min === void 0) { min = 0; }
  5026. if (max === void 0) { max = 1; }
  5027. return Math.min(max, Math.max(min, value));
  5028. };
  5029. /**
  5030. * Returns the log2 of value.
  5031. */
  5032. Scalar.Log2 = function (value) {
  5033. return Math.log(value) * Math.LOG2E;
  5034. };
  5035. /**
  5036. * Loops the value, so that it is never larger than length and never smaller than 0.
  5037. *
  5038. * This is similar to the modulo operator but it works with floating point numbers.
  5039. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5040. * With t = 5 and length = 2.5, the result would be 0.0.
  5041. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5042. */
  5043. Scalar.Repeat = function (value, length) {
  5044. return value - Math.floor(value / length) * length;
  5045. };
  5046. /**
  5047. * Normalize the value between 0.0 and 1.0 using min and max values
  5048. */
  5049. Scalar.Normalize = function (value, min, max) {
  5050. return (value - min) / (max - min);
  5051. };
  5052. /**
  5053. * Denormalize the value from 0.0 and 1.0 using min and max values
  5054. */
  5055. Scalar.Denormalize = function (normalized, min, max) {
  5056. return (normalized * (max - min) + min);
  5057. };
  5058. /**
  5059. * Calculates the shortest difference between two given angles given in degrees.
  5060. */
  5061. Scalar.DeltaAngle = function (current, target) {
  5062. var num = Scalar.Repeat(target - current, 360.0);
  5063. if (num > 180.0) {
  5064. num -= 360.0;
  5065. }
  5066. return num;
  5067. };
  5068. /**
  5069. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5070. *
  5071. * The returned value will move back and forth between 0 and length
  5072. */
  5073. Scalar.PingPong = function (tx, length) {
  5074. var t = Scalar.Repeat(tx, length * 2.0);
  5075. return length - Math.abs(t - length);
  5076. };
  5077. /**
  5078. * Interpolates between min and max with smoothing at the limits.
  5079. *
  5080. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5081. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5082. */
  5083. Scalar.SmoothStep = function (from, to, tx) {
  5084. var t = Scalar.Clamp(tx);
  5085. t = -2.0 * t * t * t + 3.0 * t * t;
  5086. return to * t + from * (1.0 - t);
  5087. };
  5088. /**
  5089. * Moves a value current towards target.
  5090. *
  5091. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5092. * Negative values of maxDelta pushes the value away from target.
  5093. */
  5094. Scalar.MoveTowards = function (current, target, maxDelta) {
  5095. var result = 0;
  5096. if (Math.abs(target - current) <= maxDelta) {
  5097. result = target;
  5098. }
  5099. else {
  5100. result = current + Scalar.Sign(target - current) * maxDelta;
  5101. }
  5102. return result;
  5103. };
  5104. /**
  5105. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5106. *
  5107. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5108. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5109. */
  5110. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5111. var num = Scalar.DeltaAngle(current, target);
  5112. var result = 0;
  5113. if (-maxDelta < num && num < maxDelta) {
  5114. result = target;
  5115. }
  5116. else {
  5117. target = current + num;
  5118. result = Scalar.MoveTowards(current, target, maxDelta);
  5119. }
  5120. return result;
  5121. };
  5122. /**
  5123. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5124. */
  5125. Scalar.Lerp = function (start, end, amount) {
  5126. return start + ((end - start) * amount);
  5127. };
  5128. /**
  5129. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5130. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5131. */
  5132. Scalar.LerpAngle = function (start, end, amount) {
  5133. var num = Scalar.Repeat(end - start, 360.0);
  5134. if (num > 180.0) {
  5135. num -= 360.0;
  5136. }
  5137. return start + num * Scalar.Clamp(amount);
  5138. };
  5139. /**
  5140. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5141. */
  5142. Scalar.InverseLerp = function (a, b, value) {
  5143. var result = 0;
  5144. if (a != b) {
  5145. result = Scalar.Clamp((value - a) / (b - a));
  5146. }
  5147. else {
  5148. result = 0.0;
  5149. }
  5150. return result;
  5151. };
  5152. /**
  5153. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5154. */
  5155. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5156. var squared = amount * amount;
  5157. var cubed = amount * squared;
  5158. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5159. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5160. var part3 = (cubed - (2.0 * squared)) + amount;
  5161. var part4 = cubed - squared;
  5162. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5163. };
  5164. /**
  5165. * Returns a random float number between and min and max values
  5166. */
  5167. Scalar.RandomRange = function (min, max) {
  5168. if (min === max)
  5169. return min;
  5170. return ((Math.random() * (max - min)) + min);
  5171. };
  5172. /**
  5173. * This function returns percentage of a number in a given range.
  5174. *
  5175. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5176. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5177. */
  5178. Scalar.RangeToPercent = function (number, min, max) {
  5179. return ((number - min) / (max - min));
  5180. };
  5181. /**
  5182. * This function returns number that corresponds to the percentage in a given range.
  5183. *
  5184. * PercentToRange(0.34,0,100) will return 34.
  5185. */
  5186. Scalar.PercentToRange = function (percent, min, max) {
  5187. return ((max - min) * percent + min);
  5188. };
  5189. /**
  5190. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5191. * @param angle The angle to normalize in radian.
  5192. * @return The converted angle.
  5193. */
  5194. Scalar.NormalizeRadians = function (angle) {
  5195. // More precise but slower version kept for reference.
  5196. // angle = angle % Tools.TwoPi;
  5197. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5198. //if (angle > Math.PI) {
  5199. // angle -= Tools.TwoPi;
  5200. //}
  5201. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5202. return angle;
  5203. };
  5204. /**
  5205. * Two pi constants convenient for computation.
  5206. */
  5207. Scalar.TwoPi = Math.PI * 2;
  5208. return Scalar;
  5209. }());
  5210. BABYLON.Scalar = Scalar;
  5211. })(BABYLON || (BABYLON = {}));
  5212. //# sourceMappingURL=babylon.math.scalar.js.map
  5213. //# sourceMappingURL=babylon.mixins.js.map
  5214. var BABYLON;
  5215. (function (BABYLON) {
  5216. var __decoratorInitialStore = {};
  5217. var __mergedStore = {};
  5218. var _copySource = function (creationFunction, source, instanciate) {
  5219. var destination = creationFunction();
  5220. // Tags
  5221. if (BABYLON.Tags) {
  5222. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5223. }
  5224. var classStore = getMergedStore(destination);
  5225. // Properties
  5226. for (var property in classStore) {
  5227. var propertyDescriptor = classStore[property];
  5228. var sourceProperty = source[property];
  5229. var propertyType = propertyDescriptor.type;
  5230. if (sourceProperty !== undefined && sourceProperty !== null) {
  5231. switch (propertyType) {
  5232. case 0: // Value
  5233. case 6:// Mesh reference
  5234. destination[property] = sourceProperty;
  5235. break;
  5236. case 1:// Texture
  5237. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5238. break;
  5239. case 2: // Color3
  5240. case 3: // FresnelParameters
  5241. case 4: // Vector2
  5242. case 5: // Vector3
  5243. case 7: // Color Curves
  5244. case 10:// Quaternion
  5245. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5246. break;
  5247. }
  5248. }
  5249. }
  5250. return destination;
  5251. };
  5252. function getDirectStore(target) {
  5253. var classKey = target.getClassName();
  5254. if (!__decoratorInitialStore[classKey]) {
  5255. __decoratorInitialStore[classKey] = {};
  5256. }
  5257. return __decoratorInitialStore[classKey];
  5258. }
  5259. /**
  5260. * Return the list of properties flagged as serializable
  5261. * @param target: host object
  5262. */
  5263. function getMergedStore(target) {
  5264. var classKey = target.getClassName();
  5265. if (__mergedStore[classKey]) {
  5266. return __mergedStore[classKey];
  5267. }
  5268. __mergedStore[classKey] = {};
  5269. var store = __mergedStore[classKey];
  5270. var currentTarget = target;
  5271. var currentKey = classKey;
  5272. while (currentKey) {
  5273. var initialStore = __decoratorInitialStore[currentKey];
  5274. for (var property in initialStore) {
  5275. store[property] = initialStore[property];
  5276. }
  5277. var parent_1 = void 0;
  5278. var done = false;
  5279. do {
  5280. parent_1 = Object.getPrototypeOf(currentTarget);
  5281. if (!parent_1.getClassName) {
  5282. done = true;
  5283. break;
  5284. }
  5285. if (parent_1.getClassName() !== currentKey) {
  5286. break;
  5287. }
  5288. currentTarget = parent_1;
  5289. } while (parent_1);
  5290. if (done) {
  5291. break;
  5292. }
  5293. currentKey = parent_1.getClassName();
  5294. currentTarget = parent_1;
  5295. }
  5296. return store;
  5297. }
  5298. function generateSerializableMember(type, sourceName) {
  5299. return function (target, propertyKey) {
  5300. var classStore = getDirectStore(target);
  5301. if (!classStore[propertyKey]) {
  5302. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5303. }
  5304. };
  5305. }
  5306. function generateExpandMember(setCallback, targetKey) {
  5307. if (targetKey === void 0) { targetKey = null; }
  5308. return function (target, propertyKey) {
  5309. var key = targetKey || ("_" + propertyKey);
  5310. Object.defineProperty(target, propertyKey, {
  5311. get: function () {
  5312. return this[key];
  5313. },
  5314. set: function (value) {
  5315. if (this[key] === value) {
  5316. return;
  5317. }
  5318. this[key] = value;
  5319. target[setCallback].apply(this);
  5320. },
  5321. enumerable: true,
  5322. configurable: true
  5323. });
  5324. };
  5325. }
  5326. function expandToProperty(callback, targetKey) {
  5327. if (targetKey === void 0) { targetKey = null; }
  5328. return generateExpandMember(callback, targetKey);
  5329. }
  5330. BABYLON.expandToProperty = expandToProperty;
  5331. function serialize(sourceName) {
  5332. return generateSerializableMember(0, sourceName); // value member
  5333. }
  5334. BABYLON.serialize = serialize;
  5335. function serializeAsTexture(sourceName) {
  5336. return generateSerializableMember(1, sourceName); // texture member
  5337. }
  5338. BABYLON.serializeAsTexture = serializeAsTexture;
  5339. function serializeAsColor3(sourceName) {
  5340. return generateSerializableMember(2, sourceName); // color3 member
  5341. }
  5342. BABYLON.serializeAsColor3 = serializeAsColor3;
  5343. function serializeAsFresnelParameters(sourceName) {
  5344. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5345. }
  5346. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5347. function serializeAsVector2(sourceName) {
  5348. return generateSerializableMember(4, sourceName); // vector2 member
  5349. }
  5350. BABYLON.serializeAsVector2 = serializeAsVector2;
  5351. function serializeAsVector3(sourceName) {
  5352. return generateSerializableMember(5, sourceName); // vector3 member
  5353. }
  5354. BABYLON.serializeAsVector3 = serializeAsVector3;
  5355. function serializeAsMeshReference(sourceName) {
  5356. return generateSerializableMember(6, sourceName); // mesh reference member
  5357. }
  5358. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5359. function serializeAsColorCurves(sourceName) {
  5360. return generateSerializableMember(7, sourceName); // color curves
  5361. }
  5362. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5363. function serializeAsColor4(sourceName) {
  5364. return generateSerializableMember(8, sourceName); // color 4
  5365. }
  5366. BABYLON.serializeAsColor4 = serializeAsColor4;
  5367. function serializeAsImageProcessingConfiguration(sourceName) {
  5368. return generateSerializableMember(9, sourceName); // image processing
  5369. }
  5370. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5371. function serializeAsQuaternion(sourceName) {
  5372. return generateSerializableMember(10, sourceName); // quaternion member
  5373. }
  5374. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  5375. var SerializationHelper = /** @class */ (function () {
  5376. function SerializationHelper() {
  5377. }
  5378. SerializationHelper.Serialize = function (entity, serializationObject) {
  5379. if (!serializationObject) {
  5380. serializationObject = {};
  5381. }
  5382. // Tags
  5383. if (BABYLON.Tags) {
  5384. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5385. }
  5386. var serializedProperties = getMergedStore(entity);
  5387. // Properties
  5388. for (var property in serializedProperties) {
  5389. var propertyDescriptor = serializedProperties[property];
  5390. var targetPropertyName = propertyDescriptor.sourceName || property;
  5391. var propertyType = propertyDescriptor.type;
  5392. var sourceProperty = entity[property];
  5393. if (sourceProperty !== undefined && sourceProperty !== null) {
  5394. switch (propertyType) {
  5395. case 0:// Value
  5396. serializationObject[targetPropertyName] = sourceProperty;
  5397. break;
  5398. case 1:// Texture
  5399. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5400. break;
  5401. case 2:// Color3
  5402. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5403. break;
  5404. case 3:// FresnelParameters
  5405. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5406. break;
  5407. case 4:// Vector2
  5408. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5409. break;
  5410. case 5:// Vector3
  5411. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5412. break;
  5413. case 6:// Mesh reference
  5414. serializationObject[targetPropertyName] = sourceProperty.id;
  5415. break;
  5416. case 7:// Color Curves
  5417. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5418. break;
  5419. case 8:// Color 4
  5420. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5421. break;
  5422. case 9:// Image Processing
  5423. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5424. break;
  5425. }
  5426. }
  5427. }
  5428. return serializationObject;
  5429. };
  5430. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5431. if (rootUrl === void 0) { rootUrl = null; }
  5432. var destination = creationFunction();
  5433. if (!rootUrl) {
  5434. rootUrl = "";
  5435. }
  5436. // Tags
  5437. if (BABYLON.Tags) {
  5438. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5439. }
  5440. var classStore = getMergedStore(destination);
  5441. // Properties
  5442. for (var property in classStore) {
  5443. var propertyDescriptor = classStore[property];
  5444. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5445. var propertyType = propertyDescriptor.type;
  5446. if (sourceProperty !== undefined && sourceProperty !== null) {
  5447. var dest = destination;
  5448. switch (propertyType) {
  5449. case 0:// Value
  5450. dest[property] = sourceProperty;
  5451. break;
  5452. case 1:// Texture
  5453. if (scene) {
  5454. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5455. }
  5456. break;
  5457. case 2:// Color3
  5458. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5459. break;
  5460. case 3:// FresnelParameters
  5461. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5462. break;
  5463. case 4:// Vector2
  5464. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5465. break;
  5466. case 5:// Vector3
  5467. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5468. break;
  5469. case 6:// Mesh reference
  5470. if (scene) {
  5471. dest[property] = scene.getLastMeshByID(sourceProperty);
  5472. }
  5473. break;
  5474. case 7:// Color Curves
  5475. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5476. break;
  5477. case 8:// Color 4
  5478. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5479. break;
  5480. case 9:// Image Processing
  5481. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5482. break;
  5483. }
  5484. }
  5485. }
  5486. return destination;
  5487. };
  5488. SerializationHelper.Clone = function (creationFunction, source) {
  5489. return _copySource(creationFunction, source, false);
  5490. };
  5491. SerializationHelper.Instanciate = function (creationFunction, source) {
  5492. return _copySource(creationFunction, source, true);
  5493. };
  5494. return SerializationHelper;
  5495. }());
  5496. BABYLON.SerializationHelper = SerializationHelper;
  5497. })(BABYLON || (BABYLON = {}));
  5498. //# sourceMappingURL=babylon.decorators.js.map
  5499. var BABYLON;
  5500. (function (BABYLON) {
  5501. /**
  5502. * A class serves as a medium between the observable and its observers
  5503. */
  5504. var EventState = /** @class */ (function () {
  5505. /**
  5506. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5507. */
  5508. function EventState(mask, skipNextObservers, target, currentTarget) {
  5509. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5510. this.initalize(mask, skipNextObservers, target, currentTarget);
  5511. }
  5512. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5513. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5514. this.mask = mask;
  5515. this.skipNextObservers = skipNextObservers;
  5516. this.target = target;
  5517. this.currentTarget = currentTarget;
  5518. return this;
  5519. };
  5520. return EventState;
  5521. }());
  5522. BABYLON.EventState = EventState;
  5523. /**
  5524. * Represent an Observer registered to a given Observable object.
  5525. */
  5526. var Observer = /** @class */ (function () {
  5527. function Observer(callback, mask, scope) {
  5528. if (scope === void 0) { scope = null; }
  5529. this.callback = callback;
  5530. this.mask = mask;
  5531. this.scope = scope;
  5532. }
  5533. return Observer;
  5534. }());
  5535. BABYLON.Observer = Observer;
  5536. /**
  5537. * Represent a list of observers registered to multiple Observables object.
  5538. */
  5539. var MultiObserver = /** @class */ (function () {
  5540. function MultiObserver() {
  5541. }
  5542. MultiObserver.prototype.dispose = function () {
  5543. if (this._observers && this._observables) {
  5544. for (var index = 0; index < this._observers.length; index++) {
  5545. this._observables[index].remove(this._observers[index]);
  5546. }
  5547. }
  5548. this._observers = null;
  5549. this._observables = null;
  5550. };
  5551. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5552. if (mask === void 0) { mask = -1; }
  5553. if (scope === void 0) { scope = null; }
  5554. var result = new MultiObserver();
  5555. result._observers = new Array();
  5556. result._observables = observables;
  5557. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5558. var observable = observables_1[_i];
  5559. var observer = observable.add(callback, mask, false, scope);
  5560. if (observer) {
  5561. result._observers.push(observer);
  5562. }
  5563. }
  5564. return result;
  5565. };
  5566. return MultiObserver;
  5567. }());
  5568. BABYLON.MultiObserver = MultiObserver;
  5569. /**
  5570. * The Observable class is a simple implementation of the Observable pattern.
  5571. * 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.
  5572. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5573. * 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).
  5574. * 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.
  5575. */
  5576. var Observable = /** @class */ (function () {
  5577. function Observable(onObserverAdded) {
  5578. this._observers = new Array();
  5579. this._eventState = new EventState(0);
  5580. if (onObserverAdded) {
  5581. this._onObserverAdded = onObserverAdded;
  5582. }
  5583. }
  5584. /**
  5585. * Create a new Observer with the specified callback
  5586. * @param callback the callback that will be executed for that Observer
  5587. * @param mask the mask used to filter observers
  5588. * @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.
  5589. * @param scope optional scope for the callback to be called from
  5590. */
  5591. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5592. if (mask === void 0) { mask = -1; }
  5593. if (insertFirst === void 0) { insertFirst = false; }
  5594. if (scope === void 0) { scope = null; }
  5595. if (!callback) {
  5596. return null;
  5597. }
  5598. var observer = new Observer(callback, mask, scope);
  5599. if (insertFirst) {
  5600. this._observers.unshift(observer);
  5601. }
  5602. else {
  5603. this._observers.push(observer);
  5604. }
  5605. if (this._onObserverAdded) {
  5606. this._onObserverAdded(observer);
  5607. }
  5608. return observer;
  5609. };
  5610. /**
  5611. * Remove an Observer from the Observable object
  5612. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5613. */
  5614. Observable.prototype.remove = function (observer) {
  5615. if (!observer) {
  5616. return false;
  5617. }
  5618. var index = this._observers.indexOf(observer);
  5619. if (index !== -1) {
  5620. this._observers.splice(index, 1);
  5621. return true;
  5622. }
  5623. return false;
  5624. };
  5625. /**
  5626. * Remove a callback from the Observable object
  5627. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5628. */
  5629. Observable.prototype.removeCallback = function (callback) {
  5630. for (var index = 0; index < this._observers.length; index++) {
  5631. if (this._observers[index].callback === callback) {
  5632. this._observers.splice(index, 1);
  5633. return true;
  5634. }
  5635. }
  5636. return false;
  5637. };
  5638. /**
  5639. * Notify all Observers by calling their respective callback with the given data
  5640. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5641. * @param eventData
  5642. * @param mask
  5643. */
  5644. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5645. if (mask === void 0) { mask = -1; }
  5646. if (!this._observers.length) {
  5647. return true;
  5648. }
  5649. var state = this._eventState;
  5650. state.mask = mask;
  5651. state.target = target;
  5652. state.currentTarget = currentTarget;
  5653. state.skipNextObservers = false;
  5654. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5655. var obs = _a[_i];
  5656. if (obs.mask & mask) {
  5657. if (obs.scope) {
  5658. obs.callback.apply(obs.scope, [eventData, state]);
  5659. }
  5660. else {
  5661. obs.callback(eventData, state);
  5662. }
  5663. }
  5664. if (state.skipNextObservers) {
  5665. return false;
  5666. }
  5667. }
  5668. return true;
  5669. };
  5670. /**
  5671. * Notify a specific observer
  5672. * @param eventData
  5673. * @param mask
  5674. */
  5675. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5676. if (mask === void 0) { mask = -1; }
  5677. var state = this._eventState;
  5678. state.mask = mask;
  5679. state.skipNextObservers = false;
  5680. observer.callback(eventData, state);
  5681. };
  5682. /**
  5683. * return true is the Observable has at least one Observer registered
  5684. */
  5685. Observable.prototype.hasObservers = function () {
  5686. return this._observers.length > 0;
  5687. };
  5688. /**
  5689. * Clear the list of observers
  5690. */
  5691. Observable.prototype.clear = function () {
  5692. this._observers = new Array();
  5693. this._onObserverAdded = null;
  5694. };
  5695. /**
  5696. * Clone the current observable
  5697. */
  5698. Observable.prototype.clone = function () {
  5699. var result = new Observable();
  5700. result._observers = this._observers.slice(0);
  5701. return result;
  5702. };
  5703. /**
  5704. * Does this observable handles observer registered with a given mask
  5705. * @param {number} trigger - the mask to be tested
  5706. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5707. **/
  5708. Observable.prototype.hasSpecificMask = function (mask) {
  5709. if (mask === void 0) { mask = -1; }
  5710. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5711. var obs = _a[_i];
  5712. if (obs.mask & mask || obs.mask === mask) {
  5713. return true;
  5714. }
  5715. }
  5716. return false;
  5717. };
  5718. return Observable;
  5719. }());
  5720. BABYLON.Observable = Observable;
  5721. })(BABYLON || (BABYLON = {}));
  5722. //# sourceMappingURL=babylon.observable.js.map
  5723. var BABYLON;
  5724. (function (BABYLON) {
  5725. var SmartArray = /** @class */ (function () {
  5726. function SmartArray(capacity) {
  5727. this.length = 0;
  5728. this.data = new Array(capacity);
  5729. this._id = SmartArray._GlobalId++;
  5730. }
  5731. SmartArray.prototype.push = function (value) {
  5732. this.data[this.length++] = value;
  5733. if (this.length > this.data.length) {
  5734. this.data.length *= 2;
  5735. }
  5736. };
  5737. SmartArray.prototype.forEach = function (func) {
  5738. for (var index = 0; index < this.length; index++) {
  5739. func(this.data[index]);
  5740. }
  5741. };
  5742. SmartArray.prototype.sort = function (compareFn) {
  5743. this.data.sort(compareFn);
  5744. };
  5745. SmartArray.prototype.reset = function () {
  5746. this.length = 0;
  5747. };
  5748. SmartArray.prototype.dispose = function () {
  5749. this.reset();
  5750. if (this.data) {
  5751. this.data.length = 0;
  5752. this.data = [];
  5753. }
  5754. };
  5755. SmartArray.prototype.concat = function (array) {
  5756. if (array.length === 0) {
  5757. return;
  5758. }
  5759. if (this.length + array.length > this.data.length) {
  5760. this.data.length = (this.length + array.length) * 2;
  5761. }
  5762. for (var index = 0; index < array.length; index++) {
  5763. this.data[this.length++] = (array.data || array)[index];
  5764. }
  5765. };
  5766. SmartArray.prototype.indexOf = function (value) {
  5767. var position = this.data.indexOf(value);
  5768. if (position >= this.length) {
  5769. return -1;
  5770. }
  5771. return position;
  5772. };
  5773. SmartArray.prototype.contains = function (value) {
  5774. return this.data.indexOf(value) !== -1;
  5775. };
  5776. // Statics
  5777. SmartArray._GlobalId = 0;
  5778. return SmartArray;
  5779. }());
  5780. BABYLON.SmartArray = SmartArray;
  5781. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5782. __extends(SmartArrayNoDuplicate, _super);
  5783. function SmartArrayNoDuplicate() {
  5784. var _this = _super !== null && _super.apply(this, arguments) || this;
  5785. _this._duplicateId = 0;
  5786. return _this;
  5787. }
  5788. SmartArrayNoDuplicate.prototype.push = function (value) {
  5789. _super.prototype.push.call(this, value);
  5790. if (!value.__smartArrayFlags) {
  5791. value.__smartArrayFlags = {};
  5792. }
  5793. value.__smartArrayFlags[this._id] = this._duplicateId;
  5794. };
  5795. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5796. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5797. return false;
  5798. }
  5799. this.push(value);
  5800. return true;
  5801. };
  5802. SmartArrayNoDuplicate.prototype.reset = function () {
  5803. _super.prototype.reset.call(this);
  5804. this._duplicateId++;
  5805. };
  5806. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5807. if (array.length === 0) {
  5808. return;
  5809. }
  5810. if (this.length + array.length > this.data.length) {
  5811. this.data.length = (this.length + array.length) * 2;
  5812. }
  5813. for (var index = 0; index < array.length; index++) {
  5814. var item = (array.data || array)[index];
  5815. this.pushNoDuplicate(item);
  5816. }
  5817. };
  5818. return SmartArrayNoDuplicate;
  5819. }(SmartArray));
  5820. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5821. })(BABYLON || (BABYLON = {}));
  5822. //# sourceMappingURL=babylon.smartArray.js.map
  5823. var BABYLON;
  5824. (function (BABYLON) {
  5825. // Screenshots
  5826. var screenshotCanvas;
  5827. var cloneValue = function (source, destinationObject) {
  5828. if (!source)
  5829. return null;
  5830. if (source instanceof BABYLON.Mesh) {
  5831. return null;
  5832. }
  5833. if (source instanceof BABYLON.SubMesh) {
  5834. return source.clone(destinationObject);
  5835. }
  5836. else if (source.clone) {
  5837. return source.clone();
  5838. }
  5839. return null;
  5840. };
  5841. var Tools = /** @class */ (function () {
  5842. function Tools() {
  5843. }
  5844. /**
  5845. * Interpolates between a and b via alpha
  5846. * @param a The lower value (returned when alpha = 0)
  5847. * @param b The upper value (returned when alpha = 1)
  5848. * @param alpha The interpolation-factor
  5849. * @return The mixed value
  5850. */
  5851. Tools.Mix = function (a, b, alpha) {
  5852. return a * (1 - alpha) + b * alpha;
  5853. };
  5854. Tools.Instantiate = function (className) {
  5855. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5856. return Tools.RegisteredExternalClasses[className];
  5857. }
  5858. var arr = className.split(".");
  5859. var fn = (window || this);
  5860. for (var i = 0, len = arr.length; i < len; i++) {
  5861. fn = fn[arr[i]];
  5862. }
  5863. if (typeof fn !== "function") {
  5864. return null;
  5865. }
  5866. return fn;
  5867. };
  5868. Tools.SetImmediate = function (action) {
  5869. if (window.setImmediate) {
  5870. window.setImmediate(action);
  5871. }
  5872. else {
  5873. setTimeout(action, 1);
  5874. }
  5875. };
  5876. Tools.IsExponentOfTwo = function (value) {
  5877. var count = 1;
  5878. do {
  5879. count *= 2;
  5880. } while (count < value);
  5881. return count === value;
  5882. };
  5883. /**
  5884. * Find the next highest power of two.
  5885. * @param x Number to start search from.
  5886. * @return Next highest power of two.
  5887. */
  5888. Tools.CeilingPOT = function (x) {
  5889. x--;
  5890. x |= x >> 1;
  5891. x |= x >> 2;
  5892. x |= x >> 4;
  5893. x |= x >> 8;
  5894. x |= x >> 16;
  5895. x++;
  5896. return x;
  5897. };
  5898. /**
  5899. * Find the next lowest power of two.
  5900. * @param x Number to start search from.
  5901. * @return Next lowest power of two.
  5902. */
  5903. Tools.FloorPOT = function (x) {
  5904. x = x | (x >> 1);
  5905. x = x | (x >> 2);
  5906. x = x | (x >> 4);
  5907. x = x | (x >> 8);
  5908. x = x | (x >> 16);
  5909. return x - (x >> 1);
  5910. };
  5911. /**
  5912. * Find the nearest power of two.
  5913. * @param x Number to start search from.
  5914. * @return Next nearest power of two.
  5915. */
  5916. Tools.NearestPOT = function (x) {
  5917. var c = Tools.CeilingPOT(x);
  5918. var f = Tools.FloorPOT(x);
  5919. return (c - x) > (x - f) ? f : c;
  5920. };
  5921. Tools.GetExponentOfTwo = function (value, max, mode) {
  5922. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5923. var pot;
  5924. switch (mode) {
  5925. case BABYLON.Engine.SCALEMODE_FLOOR:
  5926. pot = Tools.FloorPOT(value);
  5927. break;
  5928. case BABYLON.Engine.SCALEMODE_NEAREST:
  5929. pot = Tools.NearestPOT(value);
  5930. break;
  5931. case BABYLON.Engine.SCALEMODE_CEILING:
  5932. default:
  5933. pot = Tools.CeilingPOT(value);
  5934. break;
  5935. }
  5936. return Math.min(pot, max);
  5937. };
  5938. Tools.GetFilename = function (path) {
  5939. var index = path.lastIndexOf("/");
  5940. if (index < 0)
  5941. return path;
  5942. return path.substring(index + 1);
  5943. };
  5944. Tools.GetFolderPath = function (uri) {
  5945. var index = uri.lastIndexOf("/");
  5946. if (index < 0)
  5947. return "";
  5948. return uri.substring(0, index + 1);
  5949. };
  5950. Tools.GetDOMTextContent = function (element) {
  5951. var result = "";
  5952. var child = element.firstChild;
  5953. while (child) {
  5954. if (child.nodeType === 3) {
  5955. result += child.textContent;
  5956. }
  5957. child = child.nextSibling;
  5958. }
  5959. return result;
  5960. };
  5961. Tools.ToDegrees = function (angle) {
  5962. return angle * 180 / Math.PI;
  5963. };
  5964. Tools.ToRadians = function (angle) {
  5965. return angle * Math.PI / 180;
  5966. };
  5967. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5968. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5969. var output = "";
  5970. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5971. var i = 0;
  5972. var bytes = new Uint8Array(buffer);
  5973. while (i < bytes.length) {
  5974. chr1 = bytes[i++];
  5975. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5976. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5977. enc1 = chr1 >> 2;
  5978. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5979. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5980. enc4 = chr3 & 63;
  5981. if (isNaN(chr2)) {
  5982. enc3 = enc4 = 64;
  5983. }
  5984. else if (isNaN(chr3)) {
  5985. enc4 = 64;
  5986. }
  5987. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5988. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5989. }
  5990. return "data:image/png;base64," + output;
  5991. };
  5992. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5993. if (bias === void 0) { bias = null; }
  5994. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5995. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5996. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5997. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5998. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5999. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6000. }
  6001. if (bias) {
  6002. minimum.x -= minimum.x * bias.x + bias.y;
  6003. minimum.y -= minimum.y * bias.x + bias.y;
  6004. minimum.z -= minimum.z * bias.x + bias.y;
  6005. maximum.x += maximum.x * bias.x + bias.y;
  6006. maximum.y += maximum.y * bias.x + bias.y;
  6007. maximum.z += maximum.z * bias.x + bias.y;
  6008. }
  6009. return {
  6010. minimum: minimum,
  6011. maximum: maximum
  6012. };
  6013. };
  6014. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6015. if (bias === void 0) { bias = null; }
  6016. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6017. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6018. if (!stride) {
  6019. stride = 3;
  6020. }
  6021. for (var index = start; index < start + count; index++) {
  6022. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6023. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6024. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6025. }
  6026. if (bias) {
  6027. minimum.x -= minimum.x * bias.x + bias.y;
  6028. minimum.y -= minimum.y * bias.x + bias.y;
  6029. minimum.z -= minimum.z * bias.x + bias.y;
  6030. maximum.x += maximum.x * bias.x + bias.y;
  6031. maximum.y += maximum.y * bias.x + bias.y;
  6032. maximum.z += maximum.z * bias.x + bias.y;
  6033. }
  6034. return {
  6035. minimum: minimum,
  6036. maximum: maximum
  6037. };
  6038. };
  6039. Tools.Vector2ArrayFeeder = function (array) {
  6040. return function (index) {
  6041. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6042. var length = isFloatArray ? array.length / 2 : array.length;
  6043. if (index >= length) {
  6044. return null;
  6045. }
  6046. if (isFloatArray) {
  6047. var fa = array;
  6048. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6049. }
  6050. var a = array;
  6051. return a[index];
  6052. };
  6053. };
  6054. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6055. if (bias === void 0) { bias = null; }
  6056. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6057. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6058. var i = 0;
  6059. var cur = feeder(i++);
  6060. while (cur) {
  6061. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6062. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6063. cur = feeder(i++);
  6064. }
  6065. if (bias) {
  6066. minimum.x -= minimum.x * bias.x + bias.y;
  6067. minimum.y -= minimum.y * bias.x + bias.y;
  6068. maximum.x += maximum.x * bias.x + bias.y;
  6069. maximum.y += maximum.y * bias.x + bias.y;
  6070. }
  6071. return {
  6072. minimum: minimum,
  6073. maximum: maximum
  6074. };
  6075. };
  6076. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6077. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6078. return null;
  6079. return Array.isArray(obj) ? obj : [obj];
  6080. };
  6081. // Misc.
  6082. Tools.GetPointerPrefix = function () {
  6083. var eventPrefix = "pointer";
  6084. // Check if pointer events are supported
  6085. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6086. eventPrefix = "mouse";
  6087. }
  6088. return eventPrefix;
  6089. };
  6090. /**
  6091. * @param func - the function to be called
  6092. * @param requester - the object that will request the next frame. Falls back to window.
  6093. */
  6094. Tools.QueueNewFrame = function (func, requester) {
  6095. if (!Tools.IsWindowObjectExist()) {
  6096. return setTimeout(func, 16);
  6097. }
  6098. if (!requester) {
  6099. requester = window;
  6100. }
  6101. if (requester.requestAnimationFrame) {
  6102. return requester.requestAnimationFrame(func);
  6103. }
  6104. else if (requester.msRequestAnimationFrame) {
  6105. return requester.msRequestAnimationFrame(func);
  6106. }
  6107. else if (requester.webkitRequestAnimationFrame) {
  6108. return requester.webkitRequestAnimationFrame(func);
  6109. }
  6110. else if (requester.mozRequestAnimationFrame) {
  6111. return requester.mozRequestAnimationFrame(func);
  6112. }
  6113. else if (requester.oRequestAnimationFrame) {
  6114. return requester.oRequestAnimationFrame(func);
  6115. }
  6116. else {
  6117. return window.setTimeout(func, 16);
  6118. }
  6119. };
  6120. Tools.RequestFullscreen = function (element) {
  6121. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6122. if (!requestFunction)
  6123. return;
  6124. requestFunction.call(element);
  6125. };
  6126. Tools.ExitFullscreen = function () {
  6127. if (document.exitFullscreen) {
  6128. document.exitFullscreen();
  6129. }
  6130. else if (document.mozCancelFullScreen) {
  6131. document.mozCancelFullScreen();
  6132. }
  6133. else if (document.webkitCancelFullScreen) {
  6134. document.webkitCancelFullScreen();
  6135. }
  6136. else if (document.msCancelFullScreen) {
  6137. document.msCancelFullScreen();
  6138. }
  6139. };
  6140. Tools.SetCorsBehavior = function (url, img) {
  6141. if (Tools.CorsBehavior) {
  6142. switch (typeof (Tools.CorsBehavior)) {
  6143. case "function":
  6144. var result = Tools.CorsBehavior(url);
  6145. if (result) {
  6146. img.crossOrigin = result;
  6147. }
  6148. break;
  6149. case "string":
  6150. default:
  6151. img.crossOrigin = Tools.CorsBehavior;
  6152. break;
  6153. }
  6154. }
  6155. };
  6156. // External files
  6157. Tools.CleanUrl = function (url) {
  6158. url = url.replace(/#/mg, "%23");
  6159. return url;
  6160. };
  6161. Tools.LoadImage = function (url, onLoad, onError, database) {
  6162. if (url instanceof ArrayBuffer) {
  6163. url = Tools.EncodeArrayBufferTobase64(url);
  6164. }
  6165. url = Tools.CleanUrl(url);
  6166. url = Tools.PreprocessUrl(url);
  6167. var img = new Image();
  6168. if (url.substr(0, 5) !== "data:") {
  6169. Tools.SetCorsBehavior(url, img);
  6170. }
  6171. img.onload = function () {
  6172. onLoad(img);
  6173. };
  6174. img.onerror = function (err) {
  6175. Tools.Error("Error while trying to load image: " + url);
  6176. if (onError) {
  6177. onError("Error while trying to load image: " + url, err);
  6178. }
  6179. };
  6180. var noIndexedDB = function () {
  6181. img.src = url;
  6182. };
  6183. var loadFromIndexedDB = function () {
  6184. if (database) {
  6185. database.loadImageFromDB(url, img);
  6186. }
  6187. };
  6188. //ANY database to do!
  6189. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6190. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6191. }
  6192. else {
  6193. if (url.indexOf("file:") !== -1) {
  6194. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6195. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6196. try {
  6197. var blobURL;
  6198. try {
  6199. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6200. }
  6201. catch (ex) {
  6202. // Chrome doesn't support oneTimeOnly parameter
  6203. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6204. }
  6205. img.src = blobURL;
  6206. }
  6207. catch (e) {
  6208. img.src = "";
  6209. }
  6210. return img;
  6211. }
  6212. }
  6213. noIndexedDB();
  6214. }
  6215. return img;
  6216. };
  6217. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6218. url = Tools.CleanUrl(url);
  6219. url = Tools.PreprocessUrl(url);
  6220. var request = null;
  6221. var noIndexedDB = function () {
  6222. request = new XMLHttpRequest();
  6223. var loadUrl = Tools.BaseUrl + url;
  6224. request.open('GET', loadUrl, true);
  6225. if (useArrayBuffer) {
  6226. request.responseType = "arraybuffer";
  6227. }
  6228. if (progressCallBack) {
  6229. request.onprogress = progressCallBack;
  6230. }
  6231. request.onreadystatechange = function () {
  6232. var req = request;
  6233. // In case of undefined state in some browsers.
  6234. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6235. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6236. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6237. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6238. }
  6239. else {
  6240. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6241. if (onError) {
  6242. onError(req, e);
  6243. }
  6244. else {
  6245. throw e;
  6246. }
  6247. }
  6248. }
  6249. };
  6250. request.send(null);
  6251. };
  6252. var loadFromIndexedDB = function () {
  6253. if (database) {
  6254. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6255. }
  6256. };
  6257. // If file and file input are set
  6258. if (url.indexOf("file:") !== -1) {
  6259. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6260. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6261. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6262. return request;
  6263. }
  6264. }
  6265. // Caching all files
  6266. if (database && database.enableSceneOffline) {
  6267. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6268. }
  6269. else {
  6270. noIndexedDB();
  6271. }
  6272. return request;
  6273. };
  6274. /**
  6275. * Load a script (identified by an url). When the url returns, the
  6276. * content of this file is added into a new script element, attached to the DOM (body element)
  6277. */
  6278. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6279. var head = document.getElementsByTagName('head')[0];
  6280. var script = document.createElement('script');
  6281. script.type = 'text/javascript';
  6282. script.src = scriptUrl;
  6283. script.onload = function () {
  6284. if (onSuccess) {
  6285. onSuccess();
  6286. }
  6287. };
  6288. script.onerror = function (e) {
  6289. if (onError) {
  6290. onError("Unable to load script", e);
  6291. }
  6292. };
  6293. head.appendChild(script);
  6294. };
  6295. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6296. var reader = new FileReader();
  6297. reader.onload = function (e) {
  6298. //target doesn't have result from ts 1.3
  6299. callback(e.target['result']);
  6300. };
  6301. reader.onprogress = progressCallback;
  6302. reader.readAsDataURL(fileToLoad);
  6303. };
  6304. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6305. var reader = new FileReader();
  6306. reader.onerror = function (e) {
  6307. Tools.Log("Error while reading file: " + fileToLoad.name);
  6308. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6309. };
  6310. reader.onload = function (e) {
  6311. //target doesn't have result from ts 1.3
  6312. callback(e.target['result']);
  6313. };
  6314. if (progressCallBack) {
  6315. reader.onprogress = progressCallBack;
  6316. }
  6317. if (!useArrayBuffer) {
  6318. // Asynchronous read
  6319. reader.readAsText(fileToLoad);
  6320. }
  6321. else {
  6322. reader.readAsArrayBuffer(fileToLoad);
  6323. }
  6324. };
  6325. //returns a downloadable url to a file content.
  6326. Tools.FileAsURL = function (content) {
  6327. var fileBlob = new Blob([content]);
  6328. var url = window.URL || window.webkitURL;
  6329. var link = url.createObjectURL(fileBlob);
  6330. return link;
  6331. };
  6332. // Misc.
  6333. Tools.Format = function (value, decimals) {
  6334. if (decimals === void 0) { decimals = 2; }
  6335. return value.toFixed(decimals);
  6336. };
  6337. Tools.CheckExtends = function (v, min, max) {
  6338. if (v.x < min.x)
  6339. min.x = v.x;
  6340. if (v.y < min.y)
  6341. min.y = v.y;
  6342. if (v.z < min.z)
  6343. min.z = v.z;
  6344. if (v.x > max.x)
  6345. max.x = v.x;
  6346. if (v.y > max.y)
  6347. max.y = v.y;
  6348. if (v.z > max.z)
  6349. max.z = v.z;
  6350. };
  6351. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6352. for (var prop in source) {
  6353. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6354. continue;
  6355. }
  6356. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6357. continue;
  6358. }
  6359. var sourceValue = source[prop];
  6360. var typeOfSourceValue = typeof sourceValue;
  6361. if (typeOfSourceValue === "function") {
  6362. continue;
  6363. }
  6364. if (typeOfSourceValue === "object") {
  6365. if (sourceValue instanceof Array) {
  6366. destination[prop] = [];
  6367. if (sourceValue.length > 0) {
  6368. if (typeof sourceValue[0] == "object") {
  6369. for (var index = 0; index < sourceValue.length; index++) {
  6370. var clonedValue = cloneValue(sourceValue[index], destination);
  6371. if (destination[prop].indexOf(clonedValue) === -1) {
  6372. destination[prop].push(clonedValue);
  6373. }
  6374. }
  6375. }
  6376. else {
  6377. destination[prop] = sourceValue.slice(0);
  6378. }
  6379. }
  6380. }
  6381. else {
  6382. destination[prop] = cloneValue(sourceValue, destination);
  6383. }
  6384. }
  6385. else {
  6386. destination[prop] = sourceValue;
  6387. }
  6388. }
  6389. };
  6390. Tools.IsEmpty = function (obj) {
  6391. for (var i in obj) {
  6392. if (obj.hasOwnProperty(i)) {
  6393. return false;
  6394. }
  6395. }
  6396. return true;
  6397. };
  6398. Tools.RegisterTopRootEvents = function (events) {
  6399. for (var index = 0; index < events.length; index++) {
  6400. var event = events[index];
  6401. window.addEventListener(event.name, event.handler, false);
  6402. try {
  6403. if (window.parent) {
  6404. window.parent.addEventListener(event.name, event.handler, false);
  6405. }
  6406. }
  6407. catch (e) {
  6408. // Silently fails...
  6409. }
  6410. }
  6411. };
  6412. Tools.UnregisterTopRootEvents = function (events) {
  6413. for (var index = 0; index < events.length; index++) {
  6414. var event = events[index];
  6415. window.removeEventListener(event.name, event.handler);
  6416. try {
  6417. if (window.parent) {
  6418. window.parent.removeEventListener(event.name, event.handler);
  6419. }
  6420. }
  6421. catch (e) {
  6422. // Silently fails...
  6423. }
  6424. }
  6425. };
  6426. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6427. if (mimeType === void 0) { mimeType = "image/png"; }
  6428. // Read the contents of the framebuffer
  6429. var numberOfChannelsByLine = width * 4;
  6430. var halfHeight = height / 2;
  6431. //Reading datas from WebGL
  6432. var data = engine.readPixels(0, 0, width, height);
  6433. //To flip image on Y axis.
  6434. for (var i = 0; i < halfHeight; i++) {
  6435. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6436. var currentCell = j + i * numberOfChannelsByLine;
  6437. var targetLine = height - i - 1;
  6438. var targetCell = j + targetLine * numberOfChannelsByLine;
  6439. var temp = data[currentCell];
  6440. data[currentCell] = data[targetCell];
  6441. data[targetCell] = temp;
  6442. }
  6443. }
  6444. // Create a 2D canvas to store the result
  6445. if (!screenshotCanvas) {
  6446. screenshotCanvas = document.createElement('canvas');
  6447. }
  6448. screenshotCanvas.width = width;
  6449. screenshotCanvas.height = height;
  6450. var context = screenshotCanvas.getContext('2d');
  6451. if (context) {
  6452. // Copy the pixels to a 2D canvas
  6453. var imageData = context.createImageData(width, height);
  6454. var castData = (imageData.data);
  6455. castData.set(data);
  6456. context.putImageData(imageData, 0, 0);
  6457. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6458. }
  6459. };
  6460. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6461. if (mimeType === void 0) { mimeType = "image/png"; }
  6462. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6463. if (successCallback) {
  6464. successCallback(base64Image);
  6465. }
  6466. else {
  6467. // We need HTMLCanvasElement.toBlob for HD screenshots
  6468. if (!screenshotCanvas.toBlob) {
  6469. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6470. screenshotCanvas.toBlob = function (callback, type, quality) {
  6471. var _this = this;
  6472. setTimeout(function () {
  6473. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6474. for (var i = 0; i < len; i++) {
  6475. arr[i] = binStr.charCodeAt(i);
  6476. }
  6477. callback(new Blob([arr], { type: type || 'image/png' }));
  6478. });
  6479. };
  6480. }
  6481. screenshotCanvas.toBlob(function (blob) {
  6482. var url = URL.createObjectURL(blob);
  6483. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6484. if (("download" in document.createElement("a"))) {
  6485. var a = window.document.createElement("a");
  6486. a.href = url;
  6487. if (fileName) {
  6488. a.setAttribute("download", fileName);
  6489. }
  6490. else {
  6491. var date = new Date();
  6492. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6493. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6494. }
  6495. window.document.body.appendChild(a);
  6496. a.addEventListener("click", function () {
  6497. if (a.parentElement) {
  6498. a.parentElement.removeChild(a);
  6499. }
  6500. });
  6501. a.click();
  6502. }
  6503. else {
  6504. var newWindow = window.open("");
  6505. if (!newWindow)
  6506. return;
  6507. var img = newWindow.document.createElement("img");
  6508. img.onload = function () {
  6509. // no longer need to read the blob so it's revoked
  6510. URL.revokeObjectURL(url);
  6511. };
  6512. img.src = url;
  6513. newWindow.document.body.appendChild(img);
  6514. }
  6515. });
  6516. }
  6517. };
  6518. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6519. if (mimeType === void 0) { mimeType = "image/png"; }
  6520. var width;
  6521. var height;
  6522. // If a precision value is specified
  6523. if (size.precision) {
  6524. width = Math.round(engine.getRenderWidth() * size.precision);
  6525. height = Math.round(width / engine.getAspectRatio(camera));
  6526. }
  6527. else if (size.width && size.height) {
  6528. width = size.width;
  6529. height = size.height;
  6530. }
  6531. else if (size.width && !size.height) {
  6532. width = size.width;
  6533. height = Math.round(width / engine.getAspectRatio(camera));
  6534. }
  6535. else if (size.height && !size.width) {
  6536. height = size.height;
  6537. width = Math.round(height * engine.getAspectRatio(camera));
  6538. }
  6539. else if (!isNaN(size)) {
  6540. height = size;
  6541. width = size;
  6542. }
  6543. else {
  6544. Tools.Error("Invalid 'size' parameter !");
  6545. return;
  6546. }
  6547. if (!screenshotCanvas) {
  6548. screenshotCanvas = document.createElement('canvas');
  6549. }
  6550. screenshotCanvas.width = width;
  6551. screenshotCanvas.height = height;
  6552. var renderContext = screenshotCanvas.getContext("2d");
  6553. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6554. var newWidth = width;
  6555. var newHeight = newWidth / ratio;
  6556. if (newHeight > height) {
  6557. newHeight = height;
  6558. newWidth = newHeight * ratio;
  6559. }
  6560. var offsetX = Math.max(0, width - newWidth) / 2;
  6561. var offsetY = Math.max(0, height - newHeight) / 2;
  6562. var renderingCanvas = engine.getRenderingCanvas();
  6563. if (renderContext && renderingCanvas) {
  6564. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6565. }
  6566. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6567. };
  6568. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6569. if (mimeType === void 0) { mimeType = "image/png"; }
  6570. if (samples === void 0) { samples = 1; }
  6571. if (antialiasing === void 0) { antialiasing = false; }
  6572. var width;
  6573. var height;
  6574. //If a precision value is specified
  6575. if (size.precision) {
  6576. width = Math.round(engine.getRenderWidth() * size.precision);
  6577. height = Math.round(width / engine.getAspectRatio(camera));
  6578. size = { width: width, height: height };
  6579. }
  6580. else if (size.width && size.height) {
  6581. width = size.width;
  6582. height = size.height;
  6583. }
  6584. else if (size.width && !size.height) {
  6585. width = size.width;
  6586. height = Math.round(width / engine.getAspectRatio(camera));
  6587. size = { width: width, height: height };
  6588. }
  6589. else if (size.height && !size.width) {
  6590. height = size.height;
  6591. width = Math.round(height * engine.getAspectRatio(camera));
  6592. size = { width: width, height: height };
  6593. }
  6594. else if (!isNaN(size)) {
  6595. height = size;
  6596. width = size;
  6597. }
  6598. else {
  6599. Tools.Error("Invalid 'size' parameter !");
  6600. return;
  6601. }
  6602. var scene = camera.getScene();
  6603. var previousCamera = null;
  6604. if (scene.activeCamera !== camera) {
  6605. previousCamera = scene.activeCamera;
  6606. scene.activeCamera = camera;
  6607. }
  6608. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6609. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6610. texture.renderList = null;
  6611. texture.samples = samples;
  6612. if (antialiasing) {
  6613. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6614. }
  6615. texture.onAfterRenderObservable.add(function () {
  6616. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6617. });
  6618. scene.incrementRenderId();
  6619. scene.resetCachedMaterial();
  6620. texture.render(true);
  6621. texture.dispose();
  6622. if (previousCamera) {
  6623. scene.activeCamera = previousCamera;
  6624. }
  6625. camera.getProjectionMatrix(true); // Force cache refresh;
  6626. };
  6627. // XHR response validator for local file scenario
  6628. Tools.ValidateXHRData = function (xhr, dataType) {
  6629. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6630. if (dataType === void 0) { dataType = 7; }
  6631. try {
  6632. if (dataType & 1) {
  6633. if (xhr.responseText && xhr.responseText.length > 0) {
  6634. return true;
  6635. }
  6636. else if (dataType === 1) {
  6637. return false;
  6638. }
  6639. }
  6640. if (dataType & 2) {
  6641. // Check header width and height since there is no "TGA" magic number
  6642. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6643. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6644. return true;
  6645. }
  6646. else if (dataType === 2) {
  6647. return false;
  6648. }
  6649. }
  6650. if (dataType & 4) {
  6651. // Check for the "DDS" magic number
  6652. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6653. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6654. return true;
  6655. }
  6656. else {
  6657. return false;
  6658. }
  6659. }
  6660. }
  6661. catch (e) {
  6662. // Global protection
  6663. }
  6664. return false;
  6665. };
  6666. /**
  6667. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6668. * Be aware Math.random() could cause collisions, but:
  6669. * "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"
  6670. */
  6671. Tools.RandomId = function () {
  6672. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6673. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6674. return v.toString(16);
  6675. });
  6676. };
  6677. Object.defineProperty(Tools, "NoneLogLevel", {
  6678. get: function () {
  6679. return Tools._NoneLogLevel;
  6680. },
  6681. enumerable: true,
  6682. configurable: true
  6683. });
  6684. Object.defineProperty(Tools, "MessageLogLevel", {
  6685. get: function () {
  6686. return Tools._MessageLogLevel;
  6687. },
  6688. enumerable: true,
  6689. configurable: true
  6690. });
  6691. Object.defineProperty(Tools, "WarningLogLevel", {
  6692. get: function () {
  6693. return Tools._WarningLogLevel;
  6694. },
  6695. enumerable: true,
  6696. configurable: true
  6697. });
  6698. Object.defineProperty(Tools, "ErrorLogLevel", {
  6699. get: function () {
  6700. return Tools._ErrorLogLevel;
  6701. },
  6702. enumerable: true,
  6703. configurable: true
  6704. });
  6705. Object.defineProperty(Tools, "AllLogLevel", {
  6706. get: function () {
  6707. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Tools._AddLogEntry = function (entry) {
  6713. Tools._LogCache = entry + Tools._LogCache;
  6714. if (Tools.OnNewCacheEntry) {
  6715. Tools.OnNewCacheEntry(entry);
  6716. }
  6717. };
  6718. Tools._FormatMessage = function (message) {
  6719. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6720. var date = new Date();
  6721. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6722. };
  6723. Tools._LogDisabled = function (message) {
  6724. // nothing to do
  6725. };
  6726. Tools._LogEnabled = function (message) {
  6727. var formattedMessage = Tools._FormatMessage(message);
  6728. console.log("BJS - " + formattedMessage);
  6729. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6730. Tools._AddLogEntry(entry);
  6731. };
  6732. Tools._WarnDisabled = function (message) {
  6733. // nothing to do
  6734. };
  6735. Tools._WarnEnabled = function (message) {
  6736. var formattedMessage = Tools._FormatMessage(message);
  6737. console.warn("BJS - " + formattedMessage);
  6738. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6739. Tools._AddLogEntry(entry);
  6740. };
  6741. Tools._ErrorDisabled = function (message) {
  6742. // nothing to do
  6743. };
  6744. Tools._ErrorEnabled = function (message) {
  6745. Tools.errorsCount++;
  6746. var formattedMessage = Tools._FormatMessage(message);
  6747. console.error("BJS - " + formattedMessage);
  6748. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6749. Tools._AddLogEntry(entry);
  6750. };
  6751. Object.defineProperty(Tools, "LogCache", {
  6752. get: function () {
  6753. return Tools._LogCache;
  6754. },
  6755. enumerable: true,
  6756. configurable: true
  6757. });
  6758. Tools.ClearLogCache = function () {
  6759. Tools._LogCache = "";
  6760. Tools.errorsCount = 0;
  6761. };
  6762. Object.defineProperty(Tools, "LogLevels", {
  6763. set: function (level) {
  6764. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6765. Tools.Log = Tools._LogEnabled;
  6766. }
  6767. else {
  6768. Tools.Log = Tools._LogDisabled;
  6769. }
  6770. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6771. Tools.Warn = Tools._WarnEnabled;
  6772. }
  6773. else {
  6774. Tools.Warn = Tools._WarnDisabled;
  6775. }
  6776. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6777. Tools.Error = Tools._ErrorEnabled;
  6778. }
  6779. else {
  6780. Tools.Error = Tools._ErrorDisabled;
  6781. }
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Tools.IsWindowObjectExist = function () {
  6787. return (typeof window) !== "undefined";
  6788. };
  6789. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6790. get: function () {
  6791. return Tools._PerformanceNoneLogLevel;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6797. get: function () {
  6798. return Tools._PerformanceUserMarkLogLevel;
  6799. },
  6800. enumerable: true,
  6801. configurable: true
  6802. });
  6803. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6804. get: function () {
  6805. return Tools._PerformanceConsoleLogLevel;
  6806. },
  6807. enumerable: true,
  6808. configurable: true
  6809. });
  6810. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6811. set: function (level) {
  6812. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6813. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6814. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6815. return;
  6816. }
  6817. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6818. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6819. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6820. return;
  6821. }
  6822. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6823. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6829. };
  6830. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6831. };
  6832. Tools._StartUserMark = function (counterName, condition) {
  6833. if (condition === void 0) { condition = true; }
  6834. if (!Tools._performance) {
  6835. if (!Tools.IsWindowObjectExist()) {
  6836. return;
  6837. }
  6838. Tools._performance = window.performance;
  6839. }
  6840. if (!condition || !Tools._performance.mark) {
  6841. return;
  6842. }
  6843. Tools._performance.mark(counterName + "-Begin");
  6844. };
  6845. Tools._EndUserMark = function (counterName, condition) {
  6846. if (condition === void 0) { condition = true; }
  6847. if (!condition || !Tools._performance.mark) {
  6848. return;
  6849. }
  6850. Tools._performance.mark(counterName + "-End");
  6851. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6852. };
  6853. Tools._StartPerformanceConsole = function (counterName, condition) {
  6854. if (condition === void 0) { condition = true; }
  6855. if (!condition) {
  6856. return;
  6857. }
  6858. Tools._StartUserMark(counterName, condition);
  6859. if (console.time) {
  6860. console.time(counterName);
  6861. }
  6862. };
  6863. Tools._EndPerformanceConsole = function (counterName, condition) {
  6864. if (condition === void 0) { condition = true; }
  6865. if (!condition) {
  6866. return;
  6867. }
  6868. Tools._EndUserMark(counterName, condition);
  6869. if (console.time) {
  6870. console.timeEnd(counterName);
  6871. }
  6872. };
  6873. Object.defineProperty(Tools, "Now", {
  6874. get: function () {
  6875. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6876. return window.performance.now();
  6877. }
  6878. return new Date().getTime();
  6879. },
  6880. enumerable: true,
  6881. configurable: true
  6882. });
  6883. /**
  6884. * This method will return the name of the class used to create the instance of the given object.
  6885. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6886. * @param object the object to get the class name from
  6887. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6888. */
  6889. Tools.GetClassName = function (object, isType) {
  6890. if (isType === void 0) { isType = false; }
  6891. var name = null;
  6892. if (!isType && object.getClassName) {
  6893. name = object.getClassName();
  6894. }
  6895. else {
  6896. if (object instanceof Object) {
  6897. var classObj = isType ? object : Object.getPrototypeOf(object);
  6898. name = classObj.constructor["__bjsclassName__"];
  6899. }
  6900. if (!name) {
  6901. name = typeof object;
  6902. }
  6903. }
  6904. return name;
  6905. };
  6906. Tools.First = function (array, predicate) {
  6907. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6908. var el = array_1[_i];
  6909. if (predicate(el)) {
  6910. return el;
  6911. }
  6912. }
  6913. return null;
  6914. };
  6915. /**
  6916. * This method will return the name of the full name of the class, including its owning module (if any).
  6917. * 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).
  6918. * @param object the object to get the class name from
  6919. * @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.
  6920. */
  6921. Tools.getFullClassName = function (object, isType) {
  6922. if (isType === void 0) { isType = false; }
  6923. var className = null;
  6924. var moduleName = null;
  6925. if (!isType && object.getClassName) {
  6926. className = object.getClassName();
  6927. }
  6928. else {
  6929. if (object instanceof Object) {
  6930. var classObj = isType ? object : Object.getPrototypeOf(object);
  6931. className = classObj.constructor["__bjsclassName__"];
  6932. moduleName = classObj.constructor["__bjsmoduleName__"];
  6933. }
  6934. if (!className) {
  6935. className = typeof object;
  6936. }
  6937. }
  6938. if (!className) {
  6939. return null;
  6940. }
  6941. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6942. };
  6943. /**
  6944. * 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.
  6945. * @param array
  6946. */
  6947. Tools.arrayOrStringFeeder = function (array) {
  6948. return function (index) {
  6949. if (index >= array.length) {
  6950. return null;
  6951. }
  6952. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6953. if (val && val.getHashCode) {
  6954. val = val.getHashCode();
  6955. }
  6956. if (typeof val === "string") {
  6957. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6958. }
  6959. return val;
  6960. };
  6961. };
  6962. /**
  6963. * Compute the hashCode of a stream of number
  6964. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6965. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6966. * @return the hash code computed
  6967. */
  6968. Tools.hashCodeFromStream = function (feeder) {
  6969. // Based from here: http://stackoverflow.com/a/7616484/802124
  6970. var hash = 0;
  6971. var index = 0;
  6972. var chr = feeder(index++);
  6973. while (chr != null) {
  6974. hash = ((hash << 5) - hash) + chr;
  6975. hash |= 0; // Convert to 32bit integer
  6976. chr = feeder(index++);
  6977. }
  6978. return hash;
  6979. };
  6980. Tools.BaseUrl = "";
  6981. Tools.CorsBehavior = "anonymous";
  6982. Tools.UseFallbackTexture = true;
  6983. /**
  6984. * Use this object to register external classes like custom textures or material
  6985. * to allow the laoders to instantiate them
  6986. */
  6987. Tools.RegisteredExternalClasses = {};
  6988. // Used in case of a texture loading problem
  6989. 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";
  6990. Tools.PreprocessUrl = function (url) {
  6991. return url;
  6992. };
  6993. // Logs
  6994. Tools._NoneLogLevel = 0;
  6995. Tools._MessageLogLevel = 1;
  6996. Tools._WarningLogLevel = 2;
  6997. Tools._ErrorLogLevel = 4;
  6998. Tools._LogCache = "";
  6999. Tools.errorsCount = 0;
  7000. Tools.Log = Tools._LogEnabled;
  7001. Tools.Warn = Tools._WarnEnabled;
  7002. Tools.Error = Tools._ErrorEnabled;
  7003. // Performances
  7004. Tools._PerformanceNoneLogLevel = 0;
  7005. Tools._PerformanceUserMarkLogLevel = 1;
  7006. Tools._PerformanceConsoleLogLevel = 2;
  7007. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7008. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7009. return Tools;
  7010. }());
  7011. BABYLON.Tools = Tools;
  7012. /**
  7013. * This class is used to track a performance counter which is number based.
  7014. * The user has access to many properties which give statistics of different nature
  7015. *
  7016. * The implementer can track two kinds of Performance Counter: time and count
  7017. * 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.
  7018. * 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.
  7019. */
  7020. var PerfCounter = /** @class */ (function () {
  7021. function PerfCounter() {
  7022. this._startMonitoringTime = 0;
  7023. this._min = 0;
  7024. this._max = 0;
  7025. this._average = 0;
  7026. this._lastSecAverage = 0;
  7027. this._current = 0;
  7028. this._totalValueCount = 0;
  7029. this._totalAccumulated = 0;
  7030. this._lastSecAccumulated = 0;
  7031. this._lastSecTime = 0;
  7032. this._lastSecValueCount = 0;
  7033. }
  7034. Object.defineProperty(PerfCounter.prototype, "min", {
  7035. /**
  7036. * Returns the smallest value ever
  7037. */
  7038. get: function () {
  7039. return this._min;
  7040. },
  7041. enumerable: true,
  7042. configurable: true
  7043. });
  7044. Object.defineProperty(PerfCounter.prototype, "max", {
  7045. /**
  7046. * Returns the biggest value ever
  7047. */
  7048. get: function () {
  7049. return this._max;
  7050. },
  7051. enumerable: true,
  7052. configurable: true
  7053. });
  7054. Object.defineProperty(PerfCounter.prototype, "average", {
  7055. /**
  7056. * Returns the average value since the performance counter is running
  7057. */
  7058. get: function () {
  7059. return this._average;
  7060. },
  7061. enumerable: true,
  7062. configurable: true
  7063. });
  7064. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7065. /**
  7066. * Returns the average value of the last second the counter was monitored
  7067. */
  7068. get: function () {
  7069. return this._lastSecAverage;
  7070. },
  7071. enumerable: true,
  7072. configurable: true
  7073. });
  7074. Object.defineProperty(PerfCounter.prototype, "current", {
  7075. /**
  7076. * Returns the current value
  7077. */
  7078. get: function () {
  7079. return this._current;
  7080. },
  7081. enumerable: true,
  7082. configurable: true
  7083. });
  7084. Object.defineProperty(PerfCounter.prototype, "total", {
  7085. get: function () {
  7086. return this._totalAccumulated;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(PerfCounter.prototype, "count", {
  7092. get: function () {
  7093. return this._totalValueCount;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. /**
  7099. * Call this method to start monitoring a new frame.
  7100. * 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.
  7101. */
  7102. PerfCounter.prototype.fetchNewFrame = function () {
  7103. this._totalValueCount++;
  7104. this._current = 0;
  7105. this._lastSecValueCount++;
  7106. };
  7107. /**
  7108. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7109. * @param newCount the count value to add to the monitored count
  7110. * @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.
  7111. */
  7112. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7113. if (!PerfCounter.Enabled) {
  7114. return;
  7115. }
  7116. this._current += newCount;
  7117. if (fetchResult) {
  7118. this._fetchResult();
  7119. }
  7120. };
  7121. /**
  7122. * Start monitoring this performance counter
  7123. */
  7124. PerfCounter.prototype.beginMonitoring = function () {
  7125. if (!PerfCounter.Enabled) {
  7126. return;
  7127. }
  7128. this._startMonitoringTime = Tools.Now;
  7129. };
  7130. /**
  7131. * Compute the time lapsed since the previous beginMonitoring() call.
  7132. * @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
  7133. */
  7134. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7135. if (newFrame === void 0) { newFrame = true; }
  7136. if (!PerfCounter.Enabled) {
  7137. return;
  7138. }
  7139. if (newFrame) {
  7140. this.fetchNewFrame();
  7141. }
  7142. var currentTime = Tools.Now;
  7143. this._current = currentTime - this._startMonitoringTime;
  7144. if (newFrame) {
  7145. this._fetchResult();
  7146. }
  7147. };
  7148. PerfCounter.prototype._fetchResult = function () {
  7149. this._totalAccumulated += this._current;
  7150. this._lastSecAccumulated += this._current;
  7151. // Min/Max update
  7152. this._min = Math.min(this._min, this._current);
  7153. this._max = Math.max(this._max, this._current);
  7154. this._average = this._totalAccumulated / this._totalValueCount;
  7155. // Reset last sec?
  7156. var now = Tools.Now;
  7157. if ((now - this._lastSecTime) > 1000) {
  7158. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7159. this._lastSecTime = now;
  7160. this._lastSecAccumulated = 0;
  7161. this._lastSecValueCount = 0;
  7162. }
  7163. };
  7164. PerfCounter.Enabled = true;
  7165. return PerfCounter;
  7166. }());
  7167. BABYLON.PerfCounter = PerfCounter;
  7168. /**
  7169. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7170. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7171. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7172. * @param name The name of the class, case should be preserved
  7173. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7174. */
  7175. function className(name, module) {
  7176. return function (target) {
  7177. target["__bjsclassName__"] = name;
  7178. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7179. };
  7180. }
  7181. BABYLON.className = className;
  7182. /**
  7183. * An implementation of a loop for asynchronous functions.
  7184. */
  7185. var AsyncLoop = /** @class */ (function () {
  7186. /**
  7187. * Constroctor.
  7188. * @param iterations the number of iterations.
  7189. * @param _fn the function to run each iteration
  7190. * @param _successCallback the callback that will be called upon succesful execution
  7191. * @param offset starting offset.
  7192. */
  7193. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7194. if (offset === void 0) { offset = 0; }
  7195. this.iterations = iterations;
  7196. this._fn = _fn;
  7197. this._successCallback = _successCallback;
  7198. this.index = offset - 1;
  7199. this._done = false;
  7200. }
  7201. /**
  7202. * Execute the next iteration. Must be called after the last iteration was finished.
  7203. */
  7204. AsyncLoop.prototype.executeNext = function () {
  7205. if (!this._done) {
  7206. if (this.index + 1 < this.iterations) {
  7207. ++this.index;
  7208. this._fn(this);
  7209. }
  7210. else {
  7211. this.breakLoop();
  7212. }
  7213. }
  7214. };
  7215. /**
  7216. * Break the loop and run the success callback.
  7217. */
  7218. AsyncLoop.prototype.breakLoop = function () {
  7219. this._done = true;
  7220. this._successCallback();
  7221. };
  7222. /**
  7223. * Helper function
  7224. */
  7225. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7226. if (offset === void 0) { offset = 0; }
  7227. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7228. loop.executeNext();
  7229. return loop;
  7230. };
  7231. /**
  7232. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7233. * @param iterations total number of iterations
  7234. * @param syncedIterations number of synchronous iterations in each async iteration.
  7235. * @param fn the function to call each iteration.
  7236. * @param callback a success call back that will be called when iterating stops.
  7237. * @param breakFunction a break condition (optional)
  7238. * @param timeout timeout settings for the setTimeout function. default - 0.
  7239. * @constructor
  7240. */
  7241. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7242. if (timeout === void 0) { timeout = 0; }
  7243. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7244. if (breakFunction && breakFunction())
  7245. loop.breakLoop();
  7246. else {
  7247. setTimeout(function () {
  7248. for (var i = 0; i < syncedIterations; ++i) {
  7249. var iteration = (loop.index * syncedIterations) + i;
  7250. if (iteration >= iterations)
  7251. break;
  7252. fn(iteration);
  7253. if (breakFunction && breakFunction()) {
  7254. loop.breakLoop();
  7255. break;
  7256. }
  7257. }
  7258. loop.executeNext();
  7259. }, timeout);
  7260. }
  7261. }, callback);
  7262. };
  7263. return AsyncLoop;
  7264. }());
  7265. BABYLON.AsyncLoop = AsyncLoop;
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.tools.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var Internals;
  7271. (function (Internals) {
  7272. var _AlphaState = /** @class */ (function () {
  7273. /**
  7274. * Initializes the state.
  7275. */
  7276. function _AlphaState() {
  7277. this._isAlphaBlendDirty = false;
  7278. this._isBlendFunctionParametersDirty = false;
  7279. this._isBlendEquationParametersDirty = false;
  7280. this._isBlendConstantsDirty = false;
  7281. this._alphaBlend = false;
  7282. this._blendFunctionParameters = new Array(4);
  7283. this._blendEquationParameters = new Array(2);
  7284. this._blendConstants = new Array(4);
  7285. this.reset();
  7286. }
  7287. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7288. get: function () {
  7289. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7290. },
  7291. enumerable: true,
  7292. configurable: true
  7293. });
  7294. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7295. get: function () {
  7296. return this._alphaBlend;
  7297. },
  7298. set: function (value) {
  7299. if (this._alphaBlend === value) {
  7300. return;
  7301. }
  7302. this._alphaBlend = value;
  7303. this._isAlphaBlendDirty = true;
  7304. },
  7305. enumerable: true,
  7306. configurable: true
  7307. });
  7308. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7309. if (this._blendConstants[0] === r &&
  7310. this._blendConstants[1] === g &&
  7311. this._blendConstants[2] === b &&
  7312. this._blendConstants[3] === a) {
  7313. return;
  7314. }
  7315. this._blendConstants[0] = r;
  7316. this._blendConstants[1] = g;
  7317. this._blendConstants[2] = b;
  7318. this._blendConstants[3] = a;
  7319. this._isBlendConstantsDirty = true;
  7320. };
  7321. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7322. if (this._blendFunctionParameters[0] === value0 &&
  7323. this._blendFunctionParameters[1] === value1 &&
  7324. this._blendFunctionParameters[2] === value2 &&
  7325. this._blendFunctionParameters[3] === value3) {
  7326. return;
  7327. }
  7328. this._blendFunctionParameters[0] = value0;
  7329. this._blendFunctionParameters[1] = value1;
  7330. this._blendFunctionParameters[2] = value2;
  7331. this._blendFunctionParameters[3] = value3;
  7332. this._isBlendFunctionParametersDirty = true;
  7333. };
  7334. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7335. if (this._blendEquationParameters[0] === rgb &&
  7336. this._blendEquationParameters[1] === alpha) {
  7337. return;
  7338. }
  7339. this._blendEquationParameters[0] = rgb;
  7340. this._blendEquationParameters[1] = alpha;
  7341. this._isBlendEquationParametersDirty = true;
  7342. };
  7343. _AlphaState.prototype.reset = function () {
  7344. this._alphaBlend = false;
  7345. this._blendFunctionParameters[0] = null;
  7346. this._blendFunctionParameters[1] = null;
  7347. this._blendFunctionParameters[2] = null;
  7348. this._blendFunctionParameters[3] = null;
  7349. this._blendEquationParameters[0] = null;
  7350. this._blendEquationParameters[1] = null;
  7351. this._blendConstants[0] = null;
  7352. this._blendConstants[1] = null;
  7353. this._blendConstants[2] = null;
  7354. this._blendConstants[3] = null;
  7355. this._isAlphaBlendDirty = true;
  7356. this._isBlendFunctionParametersDirty = false;
  7357. this._isBlendEquationParametersDirty = false;
  7358. this._isBlendConstantsDirty = false;
  7359. };
  7360. _AlphaState.prototype.apply = function (gl) {
  7361. if (!this.isDirty) {
  7362. return;
  7363. }
  7364. // Alpha blend
  7365. if (this._isAlphaBlendDirty) {
  7366. if (this._alphaBlend) {
  7367. gl.enable(gl.BLEND);
  7368. }
  7369. else {
  7370. gl.disable(gl.BLEND);
  7371. }
  7372. this._isAlphaBlendDirty = false;
  7373. }
  7374. // Alpha function
  7375. if (this._isBlendFunctionParametersDirty) {
  7376. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7377. this._isBlendFunctionParametersDirty = false;
  7378. }
  7379. // Alpha equation
  7380. if (this._isBlendEquationParametersDirty) {
  7381. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7382. this._isBlendEquationParametersDirty = false;
  7383. }
  7384. // Constants
  7385. if (this._isBlendConstantsDirty) {
  7386. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7387. this._isBlendConstantsDirty = false;
  7388. }
  7389. };
  7390. return _AlphaState;
  7391. }());
  7392. Internals._AlphaState = _AlphaState;
  7393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7394. })(BABYLON || (BABYLON = {}));
  7395. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7396. var BABYLON;
  7397. (function (BABYLON) {
  7398. var Internals;
  7399. (function (Internals) {
  7400. var _DepthCullingState = /** @class */ (function () {
  7401. /**
  7402. * Initializes the state.
  7403. */
  7404. function _DepthCullingState() {
  7405. this._isDepthTestDirty = false;
  7406. this._isDepthMaskDirty = false;
  7407. this._isDepthFuncDirty = false;
  7408. this._isCullFaceDirty = false;
  7409. this._isCullDirty = false;
  7410. this._isZOffsetDirty = false;
  7411. this.reset();
  7412. }
  7413. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7414. get: function () {
  7415. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7416. },
  7417. enumerable: true,
  7418. configurable: true
  7419. });
  7420. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7421. get: function () {
  7422. return this._zOffset;
  7423. },
  7424. set: function (value) {
  7425. if (this._zOffset === value) {
  7426. return;
  7427. }
  7428. this._zOffset = value;
  7429. this._isZOffsetDirty = true;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7435. get: function () {
  7436. return this._cullFace;
  7437. },
  7438. set: function (value) {
  7439. if (this._cullFace === value) {
  7440. return;
  7441. }
  7442. this._cullFace = value;
  7443. this._isCullFaceDirty = true;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7449. get: function () {
  7450. return this._cull;
  7451. },
  7452. set: function (value) {
  7453. if (this._cull === value) {
  7454. return;
  7455. }
  7456. this._cull = value;
  7457. this._isCullDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7463. get: function () {
  7464. return this._depthFunc;
  7465. },
  7466. set: function (value) {
  7467. if (this._depthFunc === value) {
  7468. return;
  7469. }
  7470. this._depthFunc = value;
  7471. this._isDepthFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7477. get: function () {
  7478. return this._depthMask;
  7479. },
  7480. set: function (value) {
  7481. if (this._depthMask === value) {
  7482. return;
  7483. }
  7484. this._depthMask = value;
  7485. this._isDepthMaskDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7491. get: function () {
  7492. return this._depthTest;
  7493. },
  7494. set: function (value) {
  7495. if (this._depthTest === value) {
  7496. return;
  7497. }
  7498. this._depthTest = value;
  7499. this._isDepthTestDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. _DepthCullingState.prototype.reset = function () {
  7505. this._depthMask = true;
  7506. this._depthTest = true;
  7507. this._depthFunc = null;
  7508. this._cullFace = null;
  7509. this._cull = null;
  7510. this._zOffset = 0;
  7511. this._isDepthTestDirty = true;
  7512. this._isDepthMaskDirty = true;
  7513. this._isDepthFuncDirty = false;
  7514. this._isCullFaceDirty = false;
  7515. this._isCullDirty = false;
  7516. this._isZOffsetDirty = false;
  7517. };
  7518. _DepthCullingState.prototype.apply = function (gl) {
  7519. if (!this.isDirty) {
  7520. return;
  7521. }
  7522. // Cull
  7523. if (this._isCullDirty) {
  7524. if (this.cull) {
  7525. gl.enable(gl.CULL_FACE);
  7526. }
  7527. else {
  7528. gl.disable(gl.CULL_FACE);
  7529. }
  7530. this._isCullDirty = false;
  7531. }
  7532. // Cull face
  7533. if (this._isCullFaceDirty) {
  7534. gl.cullFace(this.cullFace);
  7535. this._isCullFaceDirty = false;
  7536. }
  7537. // Depth mask
  7538. if (this._isDepthMaskDirty) {
  7539. gl.depthMask(this.depthMask);
  7540. this._isDepthMaskDirty = false;
  7541. }
  7542. // Depth test
  7543. if (this._isDepthTestDirty) {
  7544. if (this.depthTest) {
  7545. gl.enable(gl.DEPTH_TEST);
  7546. }
  7547. else {
  7548. gl.disable(gl.DEPTH_TEST);
  7549. }
  7550. this._isDepthTestDirty = false;
  7551. }
  7552. // Depth func
  7553. if (this._isDepthFuncDirty) {
  7554. gl.depthFunc(this.depthFunc);
  7555. this._isDepthFuncDirty = false;
  7556. }
  7557. // zOffset
  7558. if (this._isZOffsetDirty) {
  7559. if (this.zOffset) {
  7560. gl.enable(gl.POLYGON_OFFSET_FILL);
  7561. gl.polygonOffset(this.zOffset, 0);
  7562. }
  7563. else {
  7564. gl.disable(gl.POLYGON_OFFSET_FILL);
  7565. }
  7566. this._isZOffsetDirty = false;
  7567. }
  7568. };
  7569. return _DepthCullingState;
  7570. }());
  7571. Internals._DepthCullingState = _DepthCullingState;
  7572. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7573. })(BABYLON || (BABYLON = {}));
  7574. //# sourceMappingURL=babylon.depthCullingState.js.map
  7575. var BABYLON;
  7576. (function (BABYLON) {
  7577. var Internals;
  7578. (function (Internals) {
  7579. var _StencilState = /** @class */ (function () {
  7580. function _StencilState() {
  7581. this._isStencilTestDirty = false;
  7582. this._isStencilMaskDirty = false;
  7583. this._isStencilFuncDirty = false;
  7584. this._isStencilOpDirty = false;
  7585. this.reset();
  7586. }
  7587. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7588. get: function () {
  7589. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7595. get: function () {
  7596. return this._stencilFunc;
  7597. },
  7598. set: function (value) {
  7599. if (this._stencilFunc === value) {
  7600. return;
  7601. }
  7602. this._stencilFunc = value;
  7603. this._isStencilFuncDirty = true;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7609. get: function () {
  7610. return this._stencilFuncRef;
  7611. },
  7612. set: function (value) {
  7613. if (this._stencilFuncRef === value) {
  7614. return;
  7615. }
  7616. this._stencilFuncRef = value;
  7617. this._isStencilFuncDirty = true;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7623. get: function () {
  7624. return this._stencilFuncMask;
  7625. },
  7626. set: function (value) {
  7627. if (this._stencilFuncMask === value) {
  7628. return;
  7629. }
  7630. this._stencilFuncMask = value;
  7631. this._isStencilFuncDirty = true;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7637. get: function () {
  7638. return this._stencilOpStencilFail;
  7639. },
  7640. set: function (value) {
  7641. if (this._stencilOpStencilFail === value) {
  7642. return;
  7643. }
  7644. this._stencilOpStencilFail = value;
  7645. this._isStencilOpDirty = true;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7651. get: function () {
  7652. return this._stencilOpDepthFail;
  7653. },
  7654. set: function (value) {
  7655. if (this._stencilOpDepthFail === value) {
  7656. return;
  7657. }
  7658. this._stencilOpDepthFail = value;
  7659. this._isStencilOpDirty = true;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7665. get: function () {
  7666. return this._stencilOpStencilDepthPass;
  7667. },
  7668. set: function (value) {
  7669. if (this._stencilOpStencilDepthPass === value) {
  7670. return;
  7671. }
  7672. this._stencilOpStencilDepthPass = value;
  7673. this._isStencilOpDirty = true;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7679. get: function () {
  7680. return this._stencilMask;
  7681. },
  7682. set: function (value) {
  7683. if (this._stencilMask === value) {
  7684. return;
  7685. }
  7686. this._stencilMask = value;
  7687. this._isStencilMaskDirty = true;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7693. get: function () {
  7694. return this._stencilTest;
  7695. },
  7696. set: function (value) {
  7697. if (this._stencilTest === value) {
  7698. return;
  7699. }
  7700. this._stencilTest = value;
  7701. this._isStencilTestDirty = true;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. _StencilState.prototype.reset = function () {
  7707. this._stencilTest = false;
  7708. this._stencilMask = 0xFF;
  7709. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7710. this._stencilFuncRef = 1;
  7711. this._stencilFuncMask = 0xFF;
  7712. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7713. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7714. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7715. this._isStencilTestDirty = true;
  7716. this._isStencilMaskDirty = true;
  7717. this._isStencilFuncDirty = true;
  7718. this._isStencilOpDirty = true;
  7719. };
  7720. _StencilState.prototype.apply = function (gl) {
  7721. if (!this.isDirty) {
  7722. return;
  7723. }
  7724. // Stencil test
  7725. if (this._isStencilTestDirty) {
  7726. if (this.stencilTest) {
  7727. gl.enable(gl.STENCIL_TEST);
  7728. }
  7729. else {
  7730. gl.disable(gl.STENCIL_TEST);
  7731. }
  7732. this._isStencilTestDirty = false;
  7733. }
  7734. // Stencil mask
  7735. if (this._isStencilMaskDirty) {
  7736. gl.stencilMask(this.stencilMask);
  7737. this._isStencilMaskDirty = false;
  7738. }
  7739. // Stencil func
  7740. if (this._isStencilFuncDirty) {
  7741. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7742. this._isStencilFuncDirty = false;
  7743. }
  7744. // Stencil op
  7745. if (this._isStencilOpDirty) {
  7746. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7747. this._isStencilOpDirty = false;
  7748. }
  7749. };
  7750. return _StencilState;
  7751. }());
  7752. Internals._StencilState = _StencilState;
  7753. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7754. })(BABYLON || (BABYLON = {}));
  7755. //# sourceMappingURL=babylon.stencilState.js.map
  7756. var BABYLON;
  7757. (function (BABYLON) {
  7758. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7759. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7760. };
  7761. var compileRawShader = function (gl, source, type) {
  7762. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7763. gl.shaderSource(shader, source);
  7764. gl.compileShader(shader);
  7765. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7766. var log = gl.getShaderInfoLog(shader);
  7767. if (log) {
  7768. throw new Error(log);
  7769. }
  7770. }
  7771. if (!shader) {
  7772. throw new Error("Something went wrong while compile the shader.");
  7773. }
  7774. return shader;
  7775. };
  7776. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7777. var magFilter = gl.NEAREST;
  7778. var minFilter = gl.NEAREST;
  7779. switch (samplingMode) {
  7780. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7781. magFilter = gl.LINEAR;
  7782. if (generateMipMaps) {
  7783. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7784. }
  7785. else {
  7786. minFilter = gl.LINEAR;
  7787. }
  7788. break;
  7789. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7790. magFilter = gl.LINEAR;
  7791. if (generateMipMaps) {
  7792. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7793. }
  7794. else {
  7795. minFilter = gl.LINEAR;
  7796. }
  7797. break;
  7798. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7799. magFilter = gl.NEAREST;
  7800. if (generateMipMaps) {
  7801. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7802. }
  7803. else {
  7804. minFilter = gl.NEAREST;
  7805. }
  7806. break;
  7807. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7808. magFilter = gl.NEAREST;
  7809. if (generateMipMaps) {
  7810. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7811. }
  7812. else {
  7813. minFilter = gl.NEAREST;
  7814. }
  7815. break;
  7816. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7817. magFilter = gl.NEAREST;
  7818. if (generateMipMaps) {
  7819. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7820. }
  7821. else {
  7822. minFilter = gl.LINEAR;
  7823. }
  7824. break;
  7825. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7826. magFilter = gl.NEAREST;
  7827. if (generateMipMaps) {
  7828. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7829. }
  7830. else {
  7831. minFilter = gl.LINEAR;
  7832. }
  7833. break;
  7834. case BABYLON.Texture.NEAREST_LINEAR:
  7835. magFilter = gl.NEAREST;
  7836. minFilter = gl.LINEAR;
  7837. break;
  7838. case BABYLON.Texture.NEAREST_NEAREST:
  7839. magFilter = gl.NEAREST;
  7840. minFilter = gl.NEAREST;
  7841. break;
  7842. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7843. magFilter = gl.LINEAR;
  7844. if (generateMipMaps) {
  7845. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7846. }
  7847. else {
  7848. minFilter = gl.NEAREST;
  7849. }
  7850. break;
  7851. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7852. magFilter = gl.LINEAR;
  7853. if (generateMipMaps) {
  7854. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7855. }
  7856. else {
  7857. minFilter = gl.NEAREST;
  7858. }
  7859. break;
  7860. case BABYLON.Texture.LINEAR_LINEAR:
  7861. magFilter = gl.LINEAR;
  7862. minFilter = gl.LINEAR;
  7863. break;
  7864. case BABYLON.Texture.LINEAR_NEAREST:
  7865. magFilter = gl.LINEAR;
  7866. minFilter = gl.NEAREST;
  7867. break;
  7868. }
  7869. return {
  7870. min: minFilter,
  7871. mag: magFilter
  7872. };
  7873. };
  7874. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7875. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7876. var img;
  7877. var onload = function () {
  7878. loadedImages[index] = img;
  7879. loadedImages._internalCount++;
  7880. if (scene) {
  7881. scene._removePendingData(img);
  7882. }
  7883. if (loadedImages._internalCount === 6) {
  7884. onfinish(loadedImages);
  7885. }
  7886. };
  7887. var onerror = function (message, exception) {
  7888. if (scene) {
  7889. scene._removePendingData(img);
  7890. }
  7891. if (onErrorCallBack) {
  7892. onErrorCallBack(message, exception);
  7893. }
  7894. };
  7895. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7896. if (scene) {
  7897. scene._addPendingData(img);
  7898. }
  7899. };
  7900. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7901. if (onError === void 0) { onError = null; }
  7902. var loadedImages = [];
  7903. loadedImages._internalCount = 0;
  7904. for (var index = 0; index < 6; index++) {
  7905. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7906. }
  7907. };
  7908. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7909. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7910. var onload = function (data) {
  7911. loadedFiles[index] = data;
  7912. loadedFiles._internalCount++;
  7913. if (loadedFiles._internalCount === 6) {
  7914. onfinish(loadedFiles);
  7915. }
  7916. };
  7917. var onerror = function (request, exception) {
  7918. if (onErrorCallBack && request) {
  7919. onErrorCallBack(request.status + " " + request.statusText, exception);
  7920. }
  7921. };
  7922. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7923. };
  7924. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7925. if (onError === void 0) { onError = null; }
  7926. var loadedFiles = [];
  7927. loadedFiles._internalCount = 0;
  7928. for (var index = 0; index < 6; index++) {
  7929. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7930. }
  7931. };
  7932. var BufferPointer = /** @class */ (function () {
  7933. function BufferPointer() {
  7934. }
  7935. return BufferPointer;
  7936. }());
  7937. var InstancingAttributeInfo = /** @class */ (function () {
  7938. function InstancingAttributeInfo() {
  7939. }
  7940. return InstancingAttributeInfo;
  7941. }());
  7942. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7943. /**
  7944. * Define options used to create a render target texture
  7945. */
  7946. var RenderTargetCreationOptions = /** @class */ (function () {
  7947. function RenderTargetCreationOptions() {
  7948. }
  7949. return RenderTargetCreationOptions;
  7950. }());
  7951. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7952. /**
  7953. * Regroup several parameters relative to the browser in use
  7954. */
  7955. var EngineCapabilities = /** @class */ (function () {
  7956. function EngineCapabilities() {
  7957. }
  7958. return EngineCapabilities;
  7959. }());
  7960. BABYLON.EngineCapabilities = EngineCapabilities;
  7961. /**
  7962. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7963. */
  7964. var Engine = /** @class */ (function () {
  7965. /**
  7966. * @constructor
  7967. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7968. * @param {boolean} [antialias] - enable antialias
  7969. * @param options - further options to be sent to the getContext function
  7970. */
  7971. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7972. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7973. var _this = this;
  7974. // Public members
  7975. this.forcePOTTextures = false;
  7976. this.isFullscreen = false;
  7977. this.isPointerLock = false;
  7978. this.cullBackFaces = true;
  7979. this.renderEvenInBackground = true;
  7980. this.preventCacheWipeBetweenFrames = false;
  7981. // To enable/disable IDB support and avoid XHR on .manifest
  7982. this.enableOfflineSupport = false;
  7983. this.scenes = new Array();
  7984. this.postProcesses = new Array();
  7985. // Observables
  7986. /**
  7987. * Observable event triggered each time the rendering canvas is resized
  7988. */
  7989. this.onResizeObservable = new BABYLON.Observable();
  7990. /**
  7991. * Observable event triggered each time the canvas loses focus
  7992. */
  7993. this.onCanvasBlurObservable = new BABYLON.Observable();
  7994. /**
  7995. * Observable event triggered each time the canvas gains focus
  7996. */
  7997. this.onCanvasFocusObservable = new BABYLON.Observable();
  7998. /**
  7999. * Observable event triggered each time the canvas receives pointerout event
  8000. */
  8001. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8002. /**
  8003. * Observable event triggered before each texture is initialized
  8004. */
  8005. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8006. //WebVR
  8007. this._vrDisplay = undefined;
  8008. this._vrSupported = false;
  8009. this._vrExclusivePointerMode = false;
  8010. // Uniform buffers list
  8011. this.disableUniformBuffers = false;
  8012. this._uniformBuffers = new Array();
  8013. // Observables
  8014. /**
  8015. * Observable raised when the engine begins a new frame
  8016. */
  8017. this.onBeginFrameObservable = new BABYLON.Observable();
  8018. /**
  8019. * Observable raised when the engine ends the current frame
  8020. */
  8021. this.onEndFrameObservable = new BABYLON.Observable();
  8022. /**
  8023. * Observable raised when the engine is about to compile a shader
  8024. */
  8025. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8026. /**
  8027. * Observable raised when the engine has jsut compiled a shader
  8028. */
  8029. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8030. this._windowIsBackground = false;
  8031. this._webGLVersion = 1.0;
  8032. this._badOS = false;
  8033. this._badDesktopOS = false;
  8034. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8035. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8036. this.onVRRequestPresentStart = new BABYLON.Observable();
  8037. this._colorWrite = true;
  8038. this._drawCalls = new BABYLON.PerfCounter();
  8039. this._renderingQueueLaunched = false;
  8040. this._activeRenderLoops = new Array();
  8041. // Deterministic lockstepMaxSteps
  8042. this._deterministicLockstep = false;
  8043. this._lockstepMaxSteps = 4;
  8044. // Lost context
  8045. this.onContextLostObservable = new BABYLON.Observable();
  8046. this.onContextRestoredObservable = new BABYLON.Observable();
  8047. this._contextWasLost = false;
  8048. this._doNotHandleContextLost = false;
  8049. // FPS
  8050. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8051. this._fps = 60;
  8052. this._deltaTime = 0;
  8053. /**
  8054. * Turn this value on if you want to pause FPS computation when in background
  8055. */
  8056. this.disablePerformanceMonitorInBackground = false;
  8057. // States
  8058. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8059. this._stencilState = new BABYLON.Internals._StencilState();
  8060. this._alphaState = new BABYLON.Internals._AlphaState();
  8061. this._alphaMode = Engine.ALPHA_DISABLE;
  8062. // Cache
  8063. this._internalTexturesCache = new Array();
  8064. this._boundTexturesCache = {};
  8065. this._compiledEffects = {};
  8066. this._vertexAttribArraysEnabled = [];
  8067. this._uintIndicesCurrentlySet = false;
  8068. this._currentBoundBuffer = new Array();
  8069. this._currentBufferPointers = new Array();
  8070. this._currentInstanceLocations = new Array();
  8071. this._currentInstanceBuffers = new Array();
  8072. this._vaoRecordInProgress = false;
  8073. this._mustWipeVertexAttributes = false;
  8074. // Hardware supported Compressed Textures
  8075. this._texturesSupported = new Array();
  8076. this._onVRFullScreenTriggered = function () {
  8077. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8078. //get the old size before we change
  8079. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8080. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8081. //get the width and height, change the render size
  8082. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8083. _this.setHardwareScalingLevel(1);
  8084. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8085. }
  8086. else {
  8087. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8088. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8089. }
  8090. };
  8091. var canvas = null;
  8092. Engine.Instances.push(this);
  8093. if (!canvasOrContext) {
  8094. return;
  8095. }
  8096. options = options || {};
  8097. if (canvasOrContext.getContext) {
  8098. canvas = canvasOrContext;
  8099. this._renderingCanvas = canvas;
  8100. if (antialias != null) {
  8101. options.antialias = antialias;
  8102. }
  8103. if (options.deterministicLockstep === undefined) {
  8104. options.deterministicLockstep = false;
  8105. }
  8106. if (options.lockstepMaxSteps === undefined) {
  8107. options.lockstepMaxSteps = 4;
  8108. }
  8109. if (options.preserveDrawingBuffer === undefined) {
  8110. options.preserveDrawingBuffer = false;
  8111. }
  8112. if (options.audioEngine === undefined) {
  8113. options.audioEngine = true;
  8114. }
  8115. if (options.stencil === undefined) {
  8116. options.stencil = true;
  8117. }
  8118. this._deterministicLockstep = options.deterministicLockstep;
  8119. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8120. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8121. // GL
  8122. if (!options.disableWebGL2Support) {
  8123. try {
  8124. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8125. if (this._gl) {
  8126. this._webGLVersion = 2.0;
  8127. }
  8128. }
  8129. catch (e) {
  8130. // Do nothing
  8131. }
  8132. }
  8133. if (!this._gl) {
  8134. if (!canvas) {
  8135. throw new Error("The provided canvas is null or undefined.");
  8136. }
  8137. try {
  8138. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8139. }
  8140. catch (e) {
  8141. throw new Error("WebGL not supported");
  8142. }
  8143. }
  8144. if (!this._gl) {
  8145. throw new Error("WebGL not supported");
  8146. }
  8147. this._onCanvasFocus = function () {
  8148. _this.onCanvasFocusObservable.notifyObservers(_this);
  8149. };
  8150. this._onCanvasBlur = function () {
  8151. _this.onCanvasBlurObservable.notifyObservers(_this);
  8152. };
  8153. canvas.addEventListener("focus", this._onCanvasFocus);
  8154. canvas.addEventListener("blur", this._onCanvasBlur);
  8155. this._onBlur = function () {
  8156. if (_this.disablePerformanceMonitorInBackground) {
  8157. _this._performanceMonitor.disable();
  8158. }
  8159. _this._windowIsBackground = true;
  8160. };
  8161. this._onFocus = function () {
  8162. if (_this.disablePerformanceMonitorInBackground) {
  8163. _this._performanceMonitor.enable();
  8164. }
  8165. _this._windowIsBackground = false;
  8166. };
  8167. this._onCanvasPointerOut = function () {
  8168. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8169. };
  8170. window.addEventListener("blur", this._onBlur);
  8171. window.addEventListener("focus", this._onFocus);
  8172. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8173. // Context lost
  8174. if (!this._doNotHandleContextLost) {
  8175. this._onContextLost = function (evt) {
  8176. evt.preventDefault();
  8177. _this._contextWasLost = true;
  8178. BABYLON.Tools.Warn("WebGL context lost.");
  8179. _this.onContextLostObservable.notifyObservers(_this);
  8180. };
  8181. this._onContextRestored = function (evt) {
  8182. // Adding a timeout to avoid race condition at browser level
  8183. setTimeout(function () {
  8184. // Rebuild gl context
  8185. _this._initGLContext();
  8186. // Rebuild effects
  8187. _this._rebuildEffects();
  8188. // Rebuild textures
  8189. _this._rebuildInternalTextures();
  8190. // Rebuild buffers
  8191. _this._rebuildBuffers();
  8192. // Cache
  8193. _this.wipeCaches(true);
  8194. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8195. _this.onContextRestoredObservable.notifyObservers(_this);
  8196. _this._contextWasLost = false;
  8197. }, 0);
  8198. };
  8199. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8200. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8201. }
  8202. }
  8203. else {
  8204. this._gl = canvasOrContext;
  8205. this._renderingCanvas = this._gl.canvas;
  8206. if (this._gl.renderbufferStorageMultisample) {
  8207. this._webGLVersion = 2.0;
  8208. }
  8209. options.stencil = this._gl.getContextAttributes().stencil;
  8210. }
  8211. // Viewport
  8212. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8213. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8214. this.resize();
  8215. this._isStencilEnable = options.stencil ? true : false;
  8216. this._initGLContext();
  8217. if (canvas) {
  8218. // Fullscreen
  8219. this._onFullscreenChange = function () {
  8220. if (document.fullscreen !== undefined) {
  8221. _this.isFullscreen = document.fullscreen;
  8222. }
  8223. else if (document.mozFullScreen !== undefined) {
  8224. _this.isFullscreen = document.mozFullScreen;
  8225. }
  8226. else if (document.webkitIsFullScreen !== undefined) {
  8227. _this.isFullscreen = document.webkitIsFullScreen;
  8228. }
  8229. else if (document.msIsFullScreen !== undefined) {
  8230. _this.isFullscreen = document.msIsFullScreen;
  8231. }
  8232. // Pointer lock
  8233. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8234. canvas.requestPointerLock = canvas.requestPointerLock ||
  8235. canvas.msRequestPointerLock ||
  8236. canvas.mozRequestPointerLock ||
  8237. canvas.webkitRequestPointerLock;
  8238. if (canvas.requestPointerLock) {
  8239. canvas.requestPointerLock();
  8240. }
  8241. }
  8242. };
  8243. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8244. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8245. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8246. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8247. // Pointer lock
  8248. this._onPointerLockChange = function () {
  8249. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8250. document.webkitPointerLockElement === canvas ||
  8251. document.msPointerLockElement === canvas ||
  8252. document.pointerLockElement === canvas);
  8253. };
  8254. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8255. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8256. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8257. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8258. this._onVRDisplayPointerRestricted = function () {
  8259. if (canvas) {
  8260. canvas.requestPointerLock();
  8261. }
  8262. };
  8263. this._onVRDisplayPointerUnrestricted = function () {
  8264. document.exitPointerLock();
  8265. };
  8266. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8267. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8268. }
  8269. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8270. Engine.audioEngine = new BABYLON.AudioEngine();
  8271. }
  8272. // Prepare buffer pointers
  8273. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8274. this._currentBufferPointers[i] = new BufferPointer();
  8275. }
  8276. // Load WebVR Devices
  8277. if (options.autoEnableWebVR) {
  8278. this.initWebVR();
  8279. }
  8280. // Detect if we are running on a faulty buggy OS.
  8281. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8282. // Detect if we are running on a faulty buggy desktop OS.
  8283. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8284. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8285. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8286. }
  8287. Object.defineProperty(Engine, "LastCreatedEngine", {
  8288. get: function () {
  8289. if (Engine.Instances.length === 0) {
  8290. return null;
  8291. }
  8292. return Engine.Instances[Engine.Instances.length - 1];
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(Engine, "LastCreatedScene", {
  8298. get: function () {
  8299. var lastCreatedEngine = Engine.LastCreatedEngine;
  8300. if (!lastCreatedEngine) {
  8301. return null;
  8302. }
  8303. if (lastCreatedEngine.scenes.length === 0) {
  8304. return null;
  8305. }
  8306. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8307. },
  8308. enumerable: true,
  8309. configurable: true
  8310. });
  8311. /**
  8312. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8313. */
  8314. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8315. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8316. var engine = Engine.Instances[engineIndex];
  8317. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8318. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8319. }
  8320. }
  8321. };
  8322. Object.defineProperty(Engine, "NEVER", {
  8323. get: function () {
  8324. return Engine._NEVER;
  8325. },
  8326. enumerable: true,
  8327. configurable: true
  8328. });
  8329. Object.defineProperty(Engine, "ALWAYS", {
  8330. get: function () {
  8331. return Engine._ALWAYS;
  8332. },
  8333. enumerable: true,
  8334. configurable: true
  8335. });
  8336. Object.defineProperty(Engine, "LESS", {
  8337. get: function () {
  8338. return Engine._LESS;
  8339. },
  8340. enumerable: true,
  8341. configurable: true
  8342. });
  8343. Object.defineProperty(Engine, "EQUAL", {
  8344. get: function () {
  8345. return Engine._EQUAL;
  8346. },
  8347. enumerable: true,
  8348. configurable: true
  8349. });
  8350. Object.defineProperty(Engine, "LEQUAL", {
  8351. get: function () {
  8352. return Engine._LEQUAL;
  8353. },
  8354. enumerable: true,
  8355. configurable: true
  8356. });
  8357. Object.defineProperty(Engine, "GREATER", {
  8358. get: function () {
  8359. return Engine._GREATER;
  8360. },
  8361. enumerable: true,
  8362. configurable: true
  8363. });
  8364. Object.defineProperty(Engine, "GEQUAL", {
  8365. get: function () {
  8366. return Engine._GEQUAL;
  8367. },
  8368. enumerable: true,
  8369. configurable: true
  8370. });
  8371. Object.defineProperty(Engine, "NOTEQUAL", {
  8372. get: function () {
  8373. return Engine._NOTEQUAL;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. Object.defineProperty(Engine, "KEEP", {
  8379. get: function () {
  8380. return Engine._KEEP;
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. Object.defineProperty(Engine, "REPLACE", {
  8386. get: function () {
  8387. return Engine._REPLACE;
  8388. },
  8389. enumerable: true,
  8390. configurable: true
  8391. });
  8392. Object.defineProperty(Engine, "INCR", {
  8393. get: function () {
  8394. return Engine._INCR;
  8395. },
  8396. enumerable: true,
  8397. configurable: true
  8398. });
  8399. Object.defineProperty(Engine, "DECR", {
  8400. get: function () {
  8401. return Engine._DECR;
  8402. },
  8403. enumerable: true,
  8404. configurable: true
  8405. });
  8406. Object.defineProperty(Engine, "INVERT", {
  8407. get: function () {
  8408. return Engine._INVERT;
  8409. },
  8410. enumerable: true,
  8411. configurable: true
  8412. });
  8413. Object.defineProperty(Engine, "INCR_WRAP", {
  8414. get: function () {
  8415. return Engine._INCR_WRAP;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(Engine, "DECR_WRAP", {
  8421. get: function () {
  8422. return Engine._DECR_WRAP;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8428. get: function () {
  8429. return Engine._ALPHA_DISABLE;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8435. get: function () {
  8436. return Engine._ALPHA_ONEONE;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(Engine, "ALPHA_ADD", {
  8442. get: function () {
  8443. return Engine._ALPHA_ADD;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8449. get: function () {
  8450. return Engine._ALPHA_COMBINE;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8456. get: function () {
  8457. return Engine._ALPHA_SUBTRACT;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8463. get: function () {
  8464. return Engine._ALPHA_MULTIPLY;
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8470. get: function () {
  8471. return Engine._ALPHA_MAXIMIZED;
  8472. },
  8473. enumerable: true,
  8474. configurable: true
  8475. });
  8476. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8477. get: function () {
  8478. return Engine._ALPHA_PREMULTIPLIED;
  8479. },
  8480. enumerable: true,
  8481. configurable: true
  8482. });
  8483. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8484. get: function () {
  8485. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8491. get: function () {
  8492. return Engine._ALPHA_INTERPOLATE;
  8493. },
  8494. enumerable: true,
  8495. configurable: true
  8496. });
  8497. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8498. get: function () {
  8499. return Engine._ALPHA_SCREENMODE;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8505. get: function () {
  8506. return Engine._DELAYLOADSTATE_NONE;
  8507. },
  8508. enumerable: true,
  8509. configurable: true
  8510. });
  8511. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8512. get: function () {
  8513. return Engine._DELAYLOADSTATE_LOADED;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8519. get: function () {
  8520. return Engine._DELAYLOADSTATE_LOADING;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8526. get: function () {
  8527. return Engine._DELAYLOADSTATE_NOTLOADED;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8533. get: function () {
  8534. return Engine._TEXTUREFORMAT_ALPHA;
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8540. get: function () {
  8541. return Engine._TEXTUREFORMAT_LUMINANCE;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8547. get: function () {
  8548. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8549. },
  8550. enumerable: true,
  8551. configurable: true
  8552. });
  8553. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8554. get: function () {
  8555. return Engine._TEXTUREFORMAT_RGB;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8561. get: function () {
  8562. return Engine._TEXTUREFORMAT_RGBA;
  8563. },
  8564. enumerable: true,
  8565. configurable: true
  8566. });
  8567. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8568. get: function () {
  8569. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8575. get: function () {
  8576. return Engine._TEXTURETYPE_FLOAT;
  8577. },
  8578. enumerable: true,
  8579. configurable: true
  8580. });
  8581. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8582. get: function () {
  8583. return Engine._TEXTURETYPE_HALF_FLOAT;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8589. get: function () {
  8590. return Engine._SCALEMODE_FLOOR;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8596. get: function () {
  8597. return Engine._SCALEMODE_NEAREST;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8603. get: function () {
  8604. return Engine._SCALEMODE_CEILING;
  8605. },
  8606. enumerable: true,
  8607. configurable: true
  8608. });
  8609. Object.defineProperty(Engine, "Version", {
  8610. get: function () {
  8611. return "3.1-beta-6";
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8617. get: function () {
  8618. return this._vrExclusivePointerMode;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8624. get: function () {
  8625. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8631. get: function () {
  8632. return this._webGLVersion < 2 || this.forcePOTTextures;
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. Object.defineProperty(Engine.prototype, "badOS", {
  8638. get: function () {
  8639. return this._badOS;
  8640. },
  8641. enumerable: true,
  8642. configurable: true
  8643. });
  8644. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8645. get: function () {
  8646. return this._badDesktopOS;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8652. get: function () {
  8653. return this._performanceMonitor;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8659. get: function () {
  8660. return this._texturesSupported;
  8661. },
  8662. enumerable: true,
  8663. configurable: true
  8664. });
  8665. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8666. get: function () {
  8667. return this._textureFormatInUse;
  8668. },
  8669. enumerable: true,
  8670. configurable: true
  8671. });
  8672. Object.defineProperty(Engine.prototype, "currentViewport", {
  8673. get: function () {
  8674. return this._cachedViewport;
  8675. },
  8676. enumerable: true,
  8677. configurable: true
  8678. });
  8679. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8680. // Empty texture
  8681. get: function () {
  8682. if (!this._emptyTexture) {
  8683. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8684. }
  8685. return this._emptyTexture;
  8686. },
  8687. enumerable: true,
  8688. configurable: true
  8689. });
  8690. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8691. get: function () {
  8692. if (!this._emptyTexture3D) {
  8693. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8694. }
  8695. return this._emptyTexture3D;
  8696. },
  8697. enumerable: true,
  8698. configurable: true
  8699. });
  8700. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8701. get: function () {
  8702. if (!this._emptyCubeTexture) {
  8703. var faceData = new Uint8Array(4);
  8704. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8705. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8706. }
  8707. return this._emptyCubeTexture;
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Engine.prototype._rebuildInternalTextures = function () {
  8713. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8714. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8715. var internalTexture = currentState_1[_i];
  8716. internalTexture._rebuild();
  8717. }
  8718. };
  8719. Engine.prototype._rebuildEffects = function () {
  8720. for (var key in this._compiledEffects) {
  8721. var effect = this._compiledEffects[key];
  8722. effect._prepareEffect();
  8723. }
  8724. BABYLON.Effect.ResetCache();
  8725. };
  8726. Engine.prototype._rebuildBuffers = function () {
  8727. // Index / Vertex
  8728. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8729. var scene = _a[_i];
  8730. scene.resetCachedMaterial();
  8731. scene._rebuildGeometries();
  8732. scene._rebuildTextures();
  8733. }
  8734. // Uniforms
  8735. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8736. var uniformBuffer = _c[_b];
  8737. uniformBuffer._rebuild();
  8738. }
  8739. };
  8740. Engine.prototype._initGLContext = function () {
  8741. // Caps
  8742. this._caps = new EngineCapabilities();
  8743. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8744. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8745. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8746. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8747. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8748. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8749. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8750. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8751. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8752. // Infos
  8753. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8754. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8755. if (rendererInfo != null) {
  8756. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8757. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8758. }
  8759. if (!this._glVendor) {
  8760. this._glVendor = "Unknown vendor";
  8761. }
  8762. if (!this._glRenderer) {
  8763. this._glRenderer = "Unknown renderer";
  8764. }
  8765. // Constants
  8766. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8767. if (this._gl.RGBA16F !== 0x881A) {
  8768. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8769. }
  8770. if (this._gl.RGBA32F !== 0x8814) {
  8771. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8772. }
  8773. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8774. this._gl.DEPTH24_STENCIL8 = 35056;
  8775. }
  8776. // Extensions
  8777. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8778. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8779. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8780. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8781. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8782. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8783. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8784. 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');
  8785. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8786. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8787. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8788. this._caps.highPrecisionShaderSupported = true;
  8789. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8790. if (this._caps.timerQuery) {
  8791. if (this._webGLVersion === 1) {
  8792. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8793. }
  8794. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8795. }
  8796. // Checks if some of the format renders first to allow the use of webgl inspector.
  8797. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8798. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8799. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8800. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8801. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8802. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8803. if (this._webGLVersion > 1) {
  8804. this._gl.HALF_FLOAT_OES = 0x140B;
  8805. }
  8806. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8807. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8808. // Draw buffers
  8809. if (this._webGLVersion > 1) {
  8810. this._caps.drawBuffersExtension = true;
  8811. }
  8812. else {
  8813. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8814. if (drawBuffersExtension !== null) {
  8815. this._caps.drawBuffersExtension = true;
  8816. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8817. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8818. for (var i = 0; i < 16; i++) {
  8819. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8820. }
  8821. }
  8822. else {
  8823. this._caps.drawBuffersExtension = false;
  8824. }
  8825. }
  8826. // Depth Texture
  8827. if (this._webGLVersion > 1) {
  8828. this._caps.depthTextureExtension = true;
  8829. }
  8830. else {
  8831. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8832. if (depthTextureExtension != null) {
  8833. this._caps.depthTextureExtension = true;
  8834. }
  8835. }
  8836. // Vertex array object
  8837. if (this._webGLVersion > 1) {
  8838. this._caps.vertexArrayObject = true;
  8839. }
  8840. else {
  8841. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8842. if (vertexArrayObjectExtension != null) {
  8843. this._caps.vertexArrayObject = true;
  8844. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8845. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8846. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8847. }
  8848. else {
  8849. this._caps.vertexArrayObject = false;
  8850. }
  8851. }
  8852. // Instances count
  8853. if (this._webGLVersion > 1) {
  8854. this._caps.instancedArrays = true;
  8855. }
  8856. else {
  8857. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8858. if (instanceExtension != null) {
  8859. this._caps.instancedArrays = true;
  8860. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8861. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8862. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8863. }
  8864. else {
  8865. this._caps.instancedArrays = false;
  8866. }
  8867. }
  8868. // Intelligently add supported compressed formats in order to check for.
  8869. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8870. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8871. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8872. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8873. if (this._caps.astc)
  8874. this.texturesSupported.push('-astc.ktx');
  8875. if (this._caps.s3tc)
  8876. this.texturesSupported.push('-dxt.ktx');
  8877. if (this._caps.pvrtc)
  8878. this.texturesSupported.push('-pvrtc.ktx');
  8879. if (this._caps.etc2)
  8880. this.texturesSupported.push('-etc2.ktx');
  8881. if (this._caps.etc1)
  8882. this.texturesSupported.push('-etc1.ktx');
  8883. if (this._gl.getShaderPrecisionFormat) {
  8884. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8885. if (highp) {
  8886. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8887. }
  8888. }
  8889. // Depth buffer
  8890. this.setDepthBuffer(true);
  8891. this.setDepthFunctionToLessOrEqual();
  8892. this.setDepthWrite(true);
  8893. };
  8894. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8895. get: function () {
  8896. return this._webGLVersion;
  8897. },
  8898. enumerable: true,
  8899. configurable: true
  8900. });
  8901. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8902. /**
  8903. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8904. */
  8905. get: function () {
  8906. return this._isStencilEnable;
  8907. },
  8908. enumerable: true,
  8909. configurable: true
  8910. });
  8911. Engine.prototype._prepareWorkingCanvas = function () {
  8912. if (this._workingCanvas) {
  8913. return;
  8914. }
  8915. this._workingCanvas = document.createElement("canvas");
  8916. var context = this._workingCanvas.getContext("2d");
  8917. if (context) {
  8918. this._workingContext = context;
  8919. }
  8920. };
  8921. Engine.prototype.resetTextureCache = function () {
  8922. for (var key in this._boundTexturesCache) {
  8923. this._boundTexturesCache[key] = null;
  8924. }
  8925. };
  8926. Engine.prototype.isDeterministicLockStep = function () {
  8927. return this._deterministicLockstep;
  8928. };
  8929. Engine.prototype.getLockstepMaxSteps = function () {
  8930. return this._lockstepMaxSteps;
  8931. };
  8932. Engine.prototype.getGlInfo = function () {
  8933. return {
  8934. vendor: this._glVendor,
  8935. renderer: this._glRenderer,
  8936. version: this._glVersion
  8937. };
  8938. };
  8939. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8940. if (useScreen === void 0) { useScreen = false; }
  8941. var viewport = camera.viewport;
  8942. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8943. };
  8944. Engine.prototype.getRenderWidth = function (useScreen) {
  8945. if (useScreen === void 0) { useScreen = false; }
  8946. if (!useScreen && this._currentRenderTarget) {
  8947. return this._currentRenderTarget.width;
  8948. }
  8949. return this._gl.drawingBufferWidth;
  8950. };
  8951. Engine.prototype.getRenderHeight = function (useScreen) {
  8952. if (useScreen === void 0) { useScreen = false; }
  8953. if (!useScreen && this._currentRenderTarget) {
  8954. return this._currentRenderTarget.height;
  8955. }
  8956. return this._gl.drawingBufferHeight;
  8957. };
  8958. Engine.prototype.getRenderingCanvas = function () {
  8959. return this._renderingCanvas;
  8960. };
  8961. Engine.prototype.getRenderingCanvasClientRect = function () {
  8962. if (!this._renderingCanvas) {
  8963. return null;
  8964. }
  8965. return this._renderingCanvas.getBoundingClientRect();
  8966. };
  8967. Engine.prototype.setHardwareScalingLevel = function (level) {
  8968. this._hardwareScalingLevel = level;
  8969. this.resize();
  8970. };
  8971. Engine.prototype.getHardwareScalingLevel = function () {
  8972. return this._hardwareScalingLevel;
  8973. };
  8974. Engine.prototype.getLoadedTexturesCache = function () {
  8975. return this._internalTexturesCache;
  8976. };
  8977. Engine.prototype.getCaps = function () {
  8978. return this._caps;
  8979. };
  8980. Object.defineProperty(Engine.prototype, "drawCalls", {
  8981. /** The number of draw calls submitted last frame */
  8982. get: function () {
  8983. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8984. return 0;
  8985. },
  8986. enumerable: true,
  8987. configurable: true
  8988. });
  8989. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8990. get: function () {
  8991. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8992. return null;
  8993. },
  8994. enumerable: true,
  8995. configurable: true
  8996. });
  8997. Engine.prototype.getDepthFunction = function () {
  8998. return this._depthCullingState.depthFunc;
  8999. };
  9000. Engine.prototype.setDepthFunction = function (depthFunc) {
  9001. this._depthCullingState.depthFunc = depthFunc;
  9002. };
  9003. Engine.prototype.setDepthFunctionToGreater = function () {
  9004. this._depthCullingState.depthFunc = this._gl.GREATER;
  9005. };
  9006. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9007. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9008. };
  9009. Engine.prototype.setDepthFunctionToLess = function () {
  9010. this._depthCullingState.depthFunc = this._gl.LESS;
  9011. };
  9012. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9013. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9014. };
  9015. Engine.prototype.getStencilBuffer = function () {
  9016. return this._stencilState.stencilTest;
  9017. };
  9018. Engine.prototype.setStencilBuffer = function (enable) {
  9019. this._stencilState.stencilTest = enable;
  9020. };
  9021. Engine.prototype.getStencilMask = function () {
  9022. return this._stencilState.stencilMask;
  9023. };
  9024. Engine.prototype.setStencilMask = function (mask) {
  9025. this._stencilState.stencilMask = mask;
  9026. };
  9027. Engine.prototype.getStencilFunction = function () {
  9028. return this._stencilState.stencilFunc;
  9029. };
  9030. Engine.prototype.getStencilFunctionReference = function () {
  9031. return this._stencilState.stencilFuncRef;
  9032. };
  9033. Engine.prototype.getStencilFunctionMask = function () {
  9034. return this._stencilState.stencilFuncMask;
  9035. };
  9036. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9037. this._stencilState.stencilFunc = stencilFunc;
  9038. };
  9039. Engine.prototype.setStencilFunctionReference = function (reference) {
  9040. this._stencilState.stencilFuncRef = reference;
  9041. };
  9042. Engine.prototype.setStencilFunctionMask = function (mask) {
  9043. this._stencilState.stencilFuncMask = mask;
  9044. };
  9045. Engine.prototype.getStencilOperationFail = function () {
  9046. return this._stencilState.stencilOpStencilFail;
  9047. };
  9048. Engine.prototype.getStencilOperationDepthFail = function () {
  9049. return this._stencilState.stencilOpDepthFail;
  9050. };
  9051. Engine.prototype.getStencilOperationPass = function () {
  9052. return this._stencilState.stencilOpStencilDepthPass;
  9053. };
  9054. Engine.prototype.setStencilOperationFail = function (operation) {
  9055. this._stencilState.stencilOpStencilFail = operation;
  9056. };
  9057. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9058. this._stencilState.stencilOpDepthFail = operation;
  9059. };
  9060. Engine.prototype.setStencilOperationPass = function (operation) {
  9061. this._stencilState.stencilOpStencilDepthPass = operation;
  9062. };
  9063. Engine.prototype.setDitheringState = function (value) {
  9064. if (value) {
  9065. this._gl.enable(this._gl.DITHER);
  9066. }
  9067. else {
  9068. this._gl.disable(this._gl.DITHER);
  9069. }
  9070. };
  9071. Engine.prototype.setRasterizerState = function (value) {
  9072. if (value) {
  9073. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9074. }
  9075. else {
  9076. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9077. }
  9078. };
  9079. /**
  9080. * stop executing a render loop function and remove it from the execution array
  9081. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9082. */
  9083. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9084. if (!renderFunction) {
  9085. this._activeRenderLoops = [];
  9086. return;
  9087. }
  9088. var index = this._activeRenderLoops.indexOf(renderFunction);
  9089. if (index >= 0) {
  9090. this._activeRenderLoops.splice(index, 1);
  9091. }
  9092. };
  9093. Engine.prototype._renderLoop = function () {
  9094. if (!this._contextWasLost) {
  9095. var shouldRender = true;
  9096. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9097. shouldRender = false;
  9098. }
  9099. if (shouldRender) {
  9100. // Start new frame
  9101. this.beginFrame();
  9102. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9103. var renderFunction = this._activeRenderLoops[index];
  9104. renderFunction();
  9105. }
  9106. // Present
  9107. this.endFrame();
  9108. }
  9109. }
  9110. if (this._activeRenderLoops.length > 0) {
  9111. // Register new frame
  9112. var requester = null;
  9113. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9114. requester = this._vrDisplay;
  9115. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9116. }
  9117. else {
  9118. this._renderingQueueLaunched = false;
  9119. }
  9120. };
  9121. /**
  9122. * Register and execute a render loop. The engine can have more than one render function.
  9123. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9124. * @example
  9125. * engine.runRenderLoop(function () {
  9126. * scene.render()
  9127. * })
  9128. */
  9129. Engine.prototype.runRenderLoop = function (renderFunction) {
  9130. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9131. return;
  9132. }
  9133. this._activeRenderLoops.push(renderFunction);
  9134. if (!this._renderingQueueLaunched) {
  9135. this._renderingQueueLaunched = true;
  9136. this._bindedRenderFunction = this._renderLoop.bind(this);
  9137. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9138. }
  9139. };
  9140. /**
  9141. * Toggle full screen mode.
  9142. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9143. * @param {any} options - an options object to be sent to the requestFullscreen function
  9144. */
  9145. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9146. if (this.isFullscreen) {
  9147. BABYLON.Tools.ExitFullscreen();
  9148. }
  9149. else {
  9150. this._pointerLockRequested = requestPointerLock;
  9151. if (this._renderingCanvas) {
  9152. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9153. }
  9154. }
  9155. };
  9156. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9157. if (stencil === void 0) { stencil = false; }
  9158. this.applyStates();
  9159. var mode = 0;
  9160. if (backBuffer && color) {
  9161. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9162. mode |= this._gl.COLOR_BUFFER_BIT;
  9163. }
  9164. if (depth) {
  9165. this._gl.clearDepth(1.0);
  9166. mode |= this._gl.DEPTH_BUFFER_BIT;
  9167. }
  9168. if (stencil) {
  9169. this._gl.clearStencil(0);
  9170. mode |= this._gl.STENCIL_BUFFER_BIT;
  9171. }
  9172. this._gl.clear(mode);
  9173. };
  9174. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9175. var gl = this._gl;
  9176. // Save state
  9177. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9178. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9179. // Change state
  9180. gl.enable(gl.SCISSOR_TEST);
  9181. gl.scissor(x, y, width, height);
  9182. // Clear
  9183. this.clear(clearColor, true, true, true);
  9184. // Restore state
  9185. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9186. if (curScissor === true) {
  9187. gl.enable(gl.SCISSOR_TEST);
  9188. }
  9189. else {
  9190. gl.disable(gl.SCISSOR_TEST);
  9191. }
  9192. };
  9193. /**
  9194. * Set the WebGL's viewport
  9195. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9196. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9197. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9198. */
  9199. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9200. var width = requiredWidth || this.getRenderWidth();
  9201. var height = requiredHeight || this.getRenderHeight();
  9202. var x = viewport.x || 0;
  9203. var y = viewport.y || 0;
  9204. this._cachedViewport = viewport;
  9205. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9206. };
  9207. /**
  9208. * Directly set the WebGL Viewport
  9209. * The x, y, width & height are directly passed to the WebGL call
  9210. * @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.
  9211. */
  9212. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9213. var currentViewport = this._cachedViewport;
  9214. this._cachedViewport = null;
  9215. this._gl.viewport(x, y, width, height);
  9216. return currentViewport;
  9217. };
  9218. Engine.prototype.beginFrame = function () {
  9219. this.onBeginFrameObservable.notifyObservers(this);
  9220. this._measureFps();
  9221. };
  9222. Engine.prototype.endFrame = function () {
  9223. //force a flush in case we are using a bad OS.
  9224. if (this._badOS) {
  9225. this.flushFramebuffer();
  9226. }
  9227. //submit frame to the vr device, if enabled
  9228. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9229. // TODO: We should only submit the frame if we read frameData successfully.
  9230. this._vrDisplay.submitFrame();
  9231. }
  9232. this.onEndFrameObservable.notifyObservers(this);
  9233. };
  9234. /**
  9235. * resize the view according to the canvas' size.
  9236. * @example
  9237. * window.addEventListener("resize", function () {
  9238. * engine.resize();
  9239. * });
  9240. */
  9241. Engine.prototype.resize = function () {
  9242. // We're not resizing the size of the canvas while in VR mode & presenting
  9243. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9244. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9245. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9246. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9247. }
  9248. };
  9249. /**
  9250. * force a specific size of the canvas
  9251. * @param {number} width - the new canvas' width
  9252. * @param {number} height - the new canvas' height
  9253. */
  9254. Engine.prototype.setSize = function (width, height) {
  9255. if (!this._renderingCanvas) {
  9256. return;
  9257. }
  9258. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9259. return;
  9260. }
  9261. this._renderingCanvas.width = width;
  9262. this._renderingCanvas.height = height;
  9263. for (var index = 0; index < this.scenes.length; index++) {
  9264. var scene = this.scenes[index];
  9265. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9266. var cam = scene.cameras[camIndex];
  9267. cam._currentRenderId = 0;
  9268. }
  9269. }
  9270. if (this.onResizeObservable.hasObservers) {
  9271. this.onResizeObservable.notifyObservers(this);
  9272. }
  9273. };
  9274. // WebVR functions
  9275. Engine.prototype.isVRDevicePresent = function () {
  9276. return !!this._vrDisplay;
  9277. };
  9278. Engine.prototype.getVRDevice = function () {
  9279. return this._vrDisplay;
  9280. };
  9281. Engine.prototype.initWebVR = function () {
  9282. var _this = this;
  9283. var notifyObservers = function () {
  9284. var eventArgs = {
  9285. vrDisplay: _this._vrDisplay,
  9286. vrSupported: _this._vrSupported
  9287. };
  9288. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9289. };
  9290. if (!this._onVrDisplayConnect) {
  9291. this._onVrDisplayConnect = function (event) {
  9292. _this._vrDisplay = event.display;
  9293. notifyObservers();
  9294. };
  9295. this._onVrDisplayDisconnect = function () {
  9296. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9297. _this._vrDisplay = undefined;
  9298. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9299. notifyObservers();
  9300. };
  9301. this._onVrDisplayPresentChange = function () {
  9302. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9303. };
  9304. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9305. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9306. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9307. }
  9308. this._getVRDisplays(notifyObservers);
  9309. return this.onVRDisplayChangedObservable;
  9310. };
  9311. Engine.prototype.enableVR = function () {
  9312. var _this = this;
  9313. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9314. var onResolved = function () {
  9315. _this.onVRRequestPresentComplete.notifyObservers(true);
  9316. _this._onVRFullScreenTriggered();
  9317. };
  9318. var onRejected = function () {
  9319. _this.onVRRequestPresentComplete.notifyObservers(false);
  9320. };
  9321. this.onVRRequestPresentStart.notifyObservers(this);
  9322. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9323. }
  9324. };
  9325. Engine.prototype.disableVR = function () {
  9326. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9327. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9328. }
  9329. };
  9330. Engine.prototype._getVRDisplays = function (callback) {
  9331. var _this = this;
  9332. var getWebVRDevices = function (devices) {
  9333. _this._vrSupported = true;
  9334. // note that devices may actually be an empty array. This is fine;
  9335. // we expect this._vrDisplay to be undefined in this case.
  9336. return _this._vrDisplay = devices[0];
  9337. };
  9338. if (navigator.getVRDisplays) {
  9339. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9340. // TODO: System CANNOT support WebVR, despite API presence.
  9341. _this._vrSupported = false;
  9342. callback();
  9343. });
  9344. }
  9345. else {
  9346. // TODO: Browser does not support WebVR
  9347. this._vrDisplay = undefined;
  9348. this._vrSupported = false;
  9349. callback();
  9350. }
  9351. };
  9352. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9353. if (this._currentRenderTarget) {
  9354. this.unBindFramebuffer(this._currentRenderTarget);
  9355. }
  9356. this._currentRenderTarget = texture;
  9357. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9358. var gl = this._gl;
  9359. if (texture.isCube) {
  9360. if (faceIndex === undefined) {
  9361. faceIndex = 0;
  9362. }
  9363. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9364. }
  9365. if (this._cachedViewport && !forceFullscreenViewport) {
  9366. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9367. }
  9368. else {
  9369. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9370. }
  9371. this.wipeCaches();
  9372. };
  9373. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9374. if (this._currentFramebuffer !== framebuffer) {
  9375. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9376. this._currentFramebuffer = framebuffer;
  9377. }
  9378. };
  9379. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9380. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9381. this._currentRenderTarget = null;
  9382. // If MSAA, we need to bitblt back to main texture
  9383. var gl = this._gl;
  9384. if (texture._MSAAFramebuffer) {
  9385. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9386. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9387. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9388. }
  9389. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9390. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9391. gl.generateMipmap(gl.TEXTURE_2D);
  9392. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9393. }
  9394. if (onBeforeUnbind) {
  9395. if (texture._MSAAFramebuffer) {
  9396. // Bind the correct framebuffer
  9397. this.bindUnboundFramebuffer(texture._framebuffer);
  9398. }
  9399. onBeforeUnbind();
  9400. }
  9401. this.bindUnboundFramebuffer(null);
  9402. };
  9403. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9404. if (texture.generateMipMaps) {
  9405. var gl = this._gl;
  9406. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9407. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9408. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9409. }
  9410. };
  9411. Engine.prototype.flushFramebuffer = function () {
  9412. this._gl.flush();
  9413. };
  9414. Engine.prototype.restoreDefaultFramebuffer = function () {
  9415. if (this._currentRenderTarget) {
  9416. this.unBindFramebuffer(this._currentRenderTarget);
  9417. }
  9418. else {
  9419. this.bindUnboundFramebuffer(null);
  9420. }
  9421. if (this._cachedViewport) {
  9422. this.setViewport(this._cachedViewport);
  9423. }
  9424. this.wipeCaches();
  9425. };
  9426. // UBOs
  9427. Engine.prototype.createUniformBuffer = function (elements) {
  9428. var ubo = this._gl.createBuffer();
  9429. if (!ubo) {
  9430. throw new Error("Unable to create uniform buffer");
  9431. }
  9432. this.bindUniformBuffer(ubo);
  9433. if (elements instanceof Float32Array) {
  9434. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9435. }
  9436. else {
  9437. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9438. }
  9439. this.bindUniformBuffer(null);
  9440. ubo.references = 1;
  9441. return ubo;
  9442. };
  9443. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9444. var ubo = this._gl.createBuffer();
  9445. if (!ubo) {
  9446. throw new Error("Unable to create dynamic uniform buffer");
  9447. }
  9448. this.bindUniformBuffer(ubo);
  9449. if (elements instanceof Float32Array) {
  9450. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9451. }
  9452. else {
  9453. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9454. }
  9455. this.bindUniformBuffer(null);
  9456. ubo.references = 1;
  9457. return ubo;
  9458. };
  9459. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9460. this.bindUniformBuffer(uniformBuffer);
  9461. if (offset === undefined) {
  9462. offset = 0;
  9463. }
  9464. if (count === undefined) {
  9465. if (elements instanceof Float32Array) {
  9466. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9467. }
  9468. else {
  9469. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9470. }
  9471. }
  9472. else {
  9473. if (elements instanceof Float32Array) {
  9474. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9475. }
  9476. else {
  9477. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9478. }
  9479. }
  9480. this.bindUniformBuffer(null);
  9481. };
  9482. // VBOs
  9483. Engine.prototype._resetVertexBufferBinding = function () {
  9484. this.bindArrayBuffer(null);
  9485. this._cachedVertexBuffers = null;
  9486. };
  9487. Engine.prototype.createVertexBuffer = function (vertices) {
  9488. var vbo = this._gl.createBuffer();
  9489. if (!vbo) {
  9490. throw new Error("Unable to create vertex buffer");
  9491. }
  9492. this.bindArrayBuffer(vbo);
  9493. if (vertices instanceof Float32Array) {
  9494. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9495. }
  9496. else {
  9497. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9498. }
  9499. this._resetVertexBufferBinding();
  9500. vbo.references = 1;
  9501. return vbo;
  9502. };
  9503. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9504. var vbo = this._gl.createBuffer();
  9505. if (!vbo) {
  9506. throw new Error("Unable to create dynamic vertex buffer");
  9507. }
  9508. this.bindArrayBuffer(vbo);
  9509. if (vertices instanceof Float32Array) {
  9510. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9511. }
  9512. else {
  9513. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9514. }
  9515. this._resetVertexBufferBinding();
  9516. vbo.references = 1;
  9517. return vbo;
  9518. };
  9519. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9520. if (offset === void 0) { offset = 0; }
  9521. // Force cache update
  9522. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9523. this.bindIndexBuffer(indexBuffer);
  9524. var arrayBuffer;
  9525. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9526. arrayBuffer = indices;
  9527. }
  9528. else {
  9529. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9530. }
  9531. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9532. this._resetIndexBufferBinding();
  9533. };
  9534. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9535. this.bindArrayBuffer(vertexBuffer);
  9536. if (offset === undefined) {
  9537. offset = 0;
  9538. }
  9539. if (count === undefined) {
  9540. if (vertices instanceof Float32Array) {
  9541. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9542. }
  9543. else {
  9544. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9545. }
  9546. }
  9547. else {
  9548. if (vertices instanceof Float32Array) {
  9549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9550. }
  9551. else {
  9552. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9553. }
  9554. }
  9555. this._resetVertexBufferBinding();
  9556. };
  9557. Engine.prototype._resetIndexBufferBinding = function () {
  9558. this.bindIndexBuffer(null);
  9559. this._cachedIndexBuffer = null;
  9560. };
  9561. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9562. var vbo = this._gl.createBuffer();
  9563. if (!vbo) {
  9564. throw new Error("Unable to create index buffer");
  9565. }
  9566. this.bindIndexBuffer(vbo);
  9567. // Check for 32 bits indices
  9568. var arrayBuffer;
  9569. var need32Bits = false;
  9570. if (indices instanceof Uint16Array) {
  9571. arrayBuffer = indices;
  9572. }
  9573. else {
  9574. //check 32 bit support
  9575. if (this._caps.uintIndices) {
  9576. if (indices instanceof Uint32Array) {
  9577. arrayBuffer = indices;
  9578. need32Bits = true;
  9579. }
  9580. else {
  9581. //number[] or Int32Array, check if 32 bit is necessary
  9582. for (var index = 0; index < indices.length; index++) {
  9583. if (indices[index] > 65535) {
  9584. need32Bits = true;
  9585. break;
  9586. }
  9587. }
  9588. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9589. }
  9590. }
  9591. else {
  9592. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9593. arrayBuffer = new Uint16Array(indices);
  9594. }
  9595. }
  9596. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9597. this._resetIndexBufferBinding();
  9598. vbo.references = 1;
  9599. vbo.is32Bits = need32Bits;
  9600. return vbo;
  9601. };
  9602. Engine.prototype.bindArrayBuffer = function (buffer) {
  9603. if (!this._vaoRecordInProgress) {
  9604. this._unbindVertexArrayObject();
  9605. }
  9606. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9607. };
  9608. Engine.prototype.bindUniformBuffer = function (buffer) {
  9609. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9610. };
  9611. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9612. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9613. };
  9614. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9615. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9616. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9617. };
  9618. ;
  9619. Engine.prototype.bindIndexBuffer = function (buffer) {
  9620. if (!this._vaoRecordInProgress) {
  9621. this._unbindVertexArrayObject();
  9622. }
  9623. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9624. };
  9625. Engine.prototype.bindBuffer = function (buffer, target) {
  9626. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9627. this._gl.bindBuffer(target, buffer);
  9628. this._currentBoundBuffer[target] = buffer;
  9629. }
  9630. };
  9631. Engine.prototype.updateArrayBuffer = function (data) {
  9632. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9633. };
  9634. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9635. var pointer = this._currentBufferPointers[indx];
  9636. var changed = false;
  9637. if (!pointer.active) {
  9638. changed = true;
  9639. pointer.active = true;
  9640. pointer.index = indx;
  9641. pointer.size = size;
  9642. pointer.type = type;
  9643. pointer.normalized = normalized;
  9644. pointer.stride = stride;
  9645. pointer.offset = offset;
  9646. pointer.buffer = buffer;
  9647. }
  9648. else {
  9649. if (pointer.buffer !== buffer) {
  9650. pointer.buffer = buffer;
  9651. changed = true;
  9652. }
  9653. if (pointer.size !== size) {
  9654. pointer.size = size;
  9655. changed = true;
  9656. }
  9657. if (pointer.type !== type) {
  9658. pointer.type = type;
  9659. changed = true;
  9660. }
  9661. if (pointer.normalized !== normalized) {
  9662. pointer.normalized = normalized;
  9663. changed = true;
  9664. }
  9665. if (pointer.stride !== stride) {
  9666. pointer.stride = stride;
  9667. changed = true;
  9668. }
  9669. if (pointer.offset !== offset) {
  9670. pointer.offset = offset;
  9671. changed = true;
  9672. }
  9673. }
  9674. if (changed || this._vaoRecordInProgress) {
  9675. this.bindArrayBuffer(buffer);
  9676. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9677. }
  9678. };
  9679. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9680. if (indexBuffer == null) {
  9681. return;
  9682. }
  9683. if (this._cachedIndexBuffer !== indexBuffer) {
  9684. this._cachedIndexBuffer = indexBuffer;
  9685. this.bindIndexBuffer(indexBuffer);
  9686. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9687. }
  9688. };
  9689. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9690. var attributes = effect.getAttributesNames();
  9691. if (!this._vaoRecordInProgress) {
  9692. this._unbindVertexArrayObject();
  9693. }
  9694. this.unbindAllAttributes();
  9695. for (var index = 0; index < attributes.length; index++) {
  9696. var order = effect.getAttributeLocation(index);
  9697. if (order >= 0) {
  9698. var vertexBuffer = vertexBuffers[attributes[index]];
  9699. if (!vertexBuffer) {
  9700. continue;
  9701. }
  9702. this._gl.enableVertexAttribArray(order);
  9703. if (!this._vaoRecordInProgress) {
  9704. this._vertexAttribArraysEnabled[order] = true;
  9705. }
  9706. var buffer = vertexBuffer.getBuffer();
  9707. if (buffer) {
  9708. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9709. if (vertexBuffer.getIsInstanced()) {
  9710. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9711. if (!this._vaoRecordInProgress) {
  9712. this._currentInstanceLocations.push(order);
  9713. this._currentInstanceBuffers.push(buffer);
  9714. }
  9715. }
  9716. }
  9717. }
  9718. }
  9719. };
  9720. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9721. var vao = this._gl.createVertexArray();
  9722. this._vaoRecordInProgress = true;
  9723. this._gl.bindVertexArray(vao);
  9724. this._mustWipeVertexAttributes = true;
  9725. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9726. this.bindIndexBuffer(indexBuffer);
  9727. this._vaoRecordInProgress = false;
  9728. this._gl.bindVertexArray(null);
  9729. return vao;
  9730. };
  9731. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9732. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9733. this._cachedVertexArrayObject = vertexArrayObject;
  9734. this._gl.bindVertexArray(vertexArrayObject);
  9735. this._cachedVertexBuffers = null;
  9736. this._cachedIndexBuffer = null;
  9737. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9738. this._mustWipeVertexAttributes = true;
  9739. }
  9740. };
  9741. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9742. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9743. this._cachedVertexBuffers = vertexBuffer;
  9744. this._cachedEffectForVertexBuffers = effect;
  9745. var attributesCount = effect.getAttributesCount();
  9746. this._unbindVertexArrayObject();
  9747. this.unbindAllAttributes();
  9748. var offset = 0;
  9749. for (var index = 0; index < attributesCount; index++) {
  9750. if (index < vertexDeclaration.length) {
  9751. var order = effect.getAttributeLocation(index);
  9752. if (order >= 0) {
  9753. this._gl.enableVertexAttribArray(order);
  9754. this._vertexAttribArraysEnabled[order] = true;
  9755. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9756. }
  9757. offset += vertexDeclaration[index] * 4;
  9758. }
  9759. }
  9760. }
  9761. this._bindIndexBufferWithCache(indexBuffer);
  9762. };
  9763. Engine.prototype._unbindVertexArrayObject = function () {
  9764. if (!this._cachedVertexArrayObject) {
  9765. return;
  9766. }
  9767. this._cachedVertexArrayObject = null;
  9768. this._gl.bindVertexArray(null);
  9769. };
  9770. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9771. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9772. this._cachedVertexBuffers = vertexBuffers;
  9773. this._cachedEffectForVertexBuffers = effect;
  9774. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9775. }
  9776. this._bindIndexBufferWithCache(indexBuffer);
  9777. };
  9778. Engine.prototype.unbindInstanceAttributes = function () {
  9779. var boundBuffer;
  9780. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9781. var instancesBuffer = this._currentInstanceBuffers[i];
  9782. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9783. boundBuffer = instancesBuffer;
  9784. this.bindArrayBuffer(instancesBuffer);
  9785. }
  9786. var offsetLocation = this._currentInstanceLocations[i];
  9787. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9788. }
  9789. this._currentInstanceBuffers.length = 0;
  9790. this._currentInstanceLocations.length = 0;
  9791. };
  9792. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9793. this._gl.deleteVertexArray(vao);
  9794. };
  9795. Engine.prototype._releaseBuffer = function (buffer) {
  9796. buffer.references--;
  9797. if (buffer.references === 0) {
  9798. this._gl.deleteBuffer(buffer);
  9799. return true;
  9800. }
  9801. return false;
  9802. };
  9803. Engine.prototype.createInstancesBuffer = function (capacity) {
  9804. var buffer = this._gl.createBuffer();
  9805. if (!buffer) {
  9806. throw new Error("Unable to create instance buffer");
  9807. }
  9808. buffer.capacity = capacity;
  9809. this.bindArrayBuffer(buffer);
  9810. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9811. return buffer;
  9812. };
  9813. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9814. this._gl.deleteBuffer(buffer);
  9815. };
  9816. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9817. this.bindArrayBuffer(instancesBuffer);
  9818. if (data) {
  9819. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9820. }
  9821. if (offsetLocations[0].index !== undefined) {
  9822. var stride = 0;
  9823. for (var i = 0; i < offsetLocations.length; i++) {
  9824. var ai = offsetLocations[i];
  9825. stride += ai.attributeSize * 4;
  9826. }
  9827. for (var i = 0; i < offsetLocations.length; i++) {
  9828. var ai = offsetLocations[i];
  9829. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9830. this._gl.enableVertexAttribArray(ai.index);
  9831. this._vertexAttribArraysEnabled[ai.index] = true;
  9832. }
  9833. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9834. this._gl.vertexAttribDivisor(ai.index, 1);
  9835. this._currentInstanceLocations.push(ai.index);
  9836. this._currentInstanceBuffers.push(instancesBuffer);
  9837. }
  9838. }
  9839. else {
  9840. for (var index = 0; index < 4; index++) {
  9841. var offsetLocation = offsetLocations[index];
  9842. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9843. this._gl.enableVertexAttribArray(offsetLocation);
  9844. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9845. }
  9846. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9847. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9848. this._currentInstanceLocations.push(offsetLocation);
  9849. this._currentInstanceBuffers.push(instancesBuffer);
  9850. }
  9851. }
  9852. };
  9853. Engine.prototype.applyStates = function () {
  9854. this._depthCullingState.apply(this._gl);
  9855. this._stencilState.apply(this._gl);
  9856. this._alphaState.apply(this._gl);
  9857. };
  9858. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9859. // Apply states
  9860. this.applyStates();
  9861. this._drawCalls.addCount(1, false);
  9862. // Render
  9863. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9864. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9865. if (instancesCount) {
  9866. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9867. return;
  9868. }
  9869. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9870. };
  9871. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9872. // Apply states
  9873. this.applyStates();
  9874. this._drawCalls.addCount(1, false);
  9875. if (instancesCount) {
  9876. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9877. return;
  9878. }
  9879. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9880. };
  9881. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9882. // Apply states
  9883. this.applyStates();
  9884. this._drawCalls.addCount(1, false);
  9885. if (instancesCount) {
  9886. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9887. return;
  9888. }
  9889. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9890. };
  9891. // Shaders
  9892. Engine.prototype._releaseEffect = function (effect) {
  9893. if (this._compiledEffects[effect._key]) {
  9894. delete this._compiledEffects[effect._key];
  9895. this._deleteProgram(effect.getProgram());
  9896. }
  9897. };
  9898. Engine.prototype._deleteProgram = function (program) {
  9899. if (program) {
  9900. program.__SPECTOR_rebuildProgram = null;
  9901. if (program.transformFeedback) {
  9902. this.deleteTransformFeedback(program.transformFeedback);
  9903. program.transformFeedback = null;
  9904. }
  9905. this._gl.deleteProgram(program);
  9906. }
  9907. };
  9908. /**
  9909. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9910. * @param samplers An array of string used to represent textures
  9911. */
  9912. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9913. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9914. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9915. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9916. if (this._compiledEffects[name]) {
  9917. var compiledEffect = this._compiledEffects[name];
  9918. if (onCompiled && compiledEffect.isReady()) {
  9919. onCompiled(compiledEffect);
  9920. }
  9921. return compiledEffect;
  9922. }
  9923. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9924. effect._key = name;
  9925. this._compiledEffects[name] = effect;
  9926. return effect;
  9927. };
  9928. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9929. if (uniformsNames === void 0) { uniformsNames = []; }
  9930. if (samplers === void 0) { samplers = []; }
  9931. if (defines === void 0) { defines = ""; }
  9932. return this.createEffect({
  9933. vertex: "particles",
  9934. fragmentElement: fragmentName
  9935. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9936. };
  9937. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9938. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9939. context = context || this._gl;
  9940. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9941. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9942. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9943. };
  9944. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9945. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9946. context = context || this._gl;
  9947. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9948. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9949. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9950. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9951. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9952. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9953. return program;
  9954. };
  9955. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9956. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9957. var shaderProgram = context.createProgram();
  9958. if (!shaderProgram) {
  9959. throw new Error("Unable to create program");
  9960. }
  9961. context.attachShader(shaderProgram, vertexShader);
  9962. context.attachShader(shaderProgram, fragmentShader);
  9963. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9964. var transformFeedback = this.createTransformFeedback();
  9965. this.bindTransformFeedback(transformFeedback);
  9966. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9967. shaderProgram.transformFeedback = transformFeedback;
  9968. }
  9969. context.linkProgram(shaderProgram);
  9970. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9971. this.bindTransformFeedback(null);
  9972. }
  9973. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9974. if (!linked) {
  9975. context.validateProgram(shaderProgram);
  9976. var error = context.getProgramInfoLog(shaderProgram);
  9977. if (error) {
  9978. throw new Error(error);
  9979. }
  9980. }
  9981. context.deleteShader(vertexShader);
  9982. context.deleteShader(fragmentShader);
  9983. return shaderProgram;
  9984. };
  9985. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9986. var results = new Array();
  9987. for (var index = 0; index < uniformsNames.length; index++) {
  9988. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9989. }
  9990. return results;
  9991. };
  9992. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9993. var results = [];
  9994. for (var index = 0; index < attributesNames.length; index++) {
  9995. try {
  9996. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9997. }
  9998. catch (e) {
  9999. results.push(-1);
  10000. }
  10001. }
  10002. return results;
  10003. };
  10004. Engine.prototype.enableEffect = function (effect) {
  10005. if (!effect) {
  10006. return;
  10007. }
  10008. // Use program
  10009. this.setProgram(effect.getProgram());
  10010. this._currentEffect = effect;
  10011. if (effect.onBind) {
  10012. effect.onBind(effect);
  10013. }
  10014. effect.onBindObservable.notifyObservers(effect);
  10015. };
  10016. Engine.prototype.setIntArray = function (uniform, array) {
  10017. if (!uniform)
  10018. return;
  10019. this._gl.uniform1iv(uniform, array);
  10020. };
  10021. Engine.prototype.setIntArray2 = function (uniform, array) {
  10022. if (!uniform || array.length % 2 !== 0)
  10023. return;
  10024. this._gl.uniform2iv(uniform, array);
  10025. };
  10026. Engine.prototype.setIntArray3 = function (uniform, array) {
  10027. if (!uniform || array.length % 3 !== 0)
  10028. return;
  10029. this._gl.uniform3iv(uniform, array);
  10030. };
  10031. Engine.prototype.setIntArray4 = function (uniform, array) {
  10032. if (!uniform || array.length % 4 !== 0)
  10033. return;
  10034. this._gl.uniform4iv(uniform, array);
  10035. };
  10036. Engine.prototype.setFloatArray = function (uniform, array) {
  10037. if (!uniform)
  10038. return;
  10039. this._gl.uniform1fv(uniform, array);
  10040. };
  10041. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10042. if (!uniform || array.length % 2 !== 0)
  10043. return;
  10044. this._gl.uniform2fv(uniform, array);
  10045. };
  10046. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10047. if (!uniform || array.length % 3 !== 0)
  10048. return;
  10049. this._gl.uniform3fv(uniform, array);
  10050. };
  10051. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10052. if (!uniform || array.length % 4 !== 0)
  10053. return;
  10054. this._gl.uniform4fv(uniform, array);
  10055. };
  10056. Engine.prototype.setArray = function (uniform, array) {
  10057. if (!uniform)
  10058. return;
  10059. this._gl.uniform1fv(uniform, array);
  10060. };
  10061. Engine.prototype.setArray2 = function (uniform, array) {
  10062. if (!uniform || array.length % 2 !== 0)
  10063. return;
  10064. this._gl.uniform2fv(uniform, array);
  10065. };
  10066. Engine.prototype.setArray3 = function (uniform, array) {
  10067. if (!uniform || array.length % 3 !== 0)
  10068. return;
  10069. this._gl.uniform3fv(uniform, array);
  10070. };
  10071. Engine.prototype.setArray4 = function (uniform, array) {
  10072. if (!uniform || array.length % 4 !== 0)
  10073. return;
  10074. this._gl.uniform4fv(uniform, array);
  10075. };
  10076. Engine.prototype.setMatrices = function (uniform, matrices) {
  10077. if (!uniform)
  10078. return;
  10079. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10080. };
  10081. Engine.prototype.setMatrix = function (uniform, matrix) {
  10082. if (!uniform)
  10083. return;
  10084. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10085. };
  10086. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10087. if (!uniform)
  10088. return;
  10089. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10090. };
  10091. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10092. if (!uniform)
  10093. return;
  10094. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10095. };
  10096. Engine.prototype.setFloat = function (uniform, value) {
  10097. if (!uniform)
  10098. return;
  10099. this._gl.uniform1f(uniform, value);
  10100. };
  10101. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10102. if (!uniform)
  10103. return;
  10104. this._gl.uniform2f(uniform, x, y);
  10105. };
  10106. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10107. if (!uniform)
  10108. return;
  10109. this._gl.uniform3f(uniform, x, y, z);
  10110. };
  10111. Engine.prototype.setBool = function (uniform, bool) {
  10112. if (!uniform)
  10113. return;
  10114. this._gl.uniform1i(uniform, bool);
  10115. };
  10116. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10117. if (!uniform)
  10118. return;
  10119. this._gl.uniform4f(uniform, x, y, z, w);
  10120. };
  10121. Engine.prototype.setColor3 = function (uniform, color3) {
  10122. if (!uniform)
  10123. return;
  10124. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10125. };
  10126. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10127. if (!uniform)
  10128. return;
  10129. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10130. };
  10131. // States
  10132. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10133. if (zOffset === void 0) { zOffset = 0; }
  10134. if (reverseSide === void 0) { reverseSide = false; }
  10135. // Culling
  10136. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10137. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10138. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10139. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10140. if (culling) {
  10141. this._depthCullingState.cullFace = cullFace;
  10142. this._depthCullingState.cull = true;
  10143. }
  10144. else {
  10145. this._depthCullingState.cull = false;
  10146. }
  10147. }
  10148. // Z offset
  10149. this.setZOffset(zOffset);
  10150. };
  10151. Engine.prototype.setZOffset = function (value) {
  10152. this._depthCullingState.zOffset = value;
  10153. };
  10154. Engine.prototype.getZOffset = function () {
  10155. return this._depthCullingState.zOffset;
  10156. };
  10157. Engine.prototype.setDepthBuffer = function (enable) {
  10158. this._depthCullingState.depthTest = enable;
  10159. };
  10160. Engine.prototype.getDepthWrite = function () {
  10161. return this._depthCullingState.depthMask;
  10162. };
  10163. Engine.prototype.setDepthWrite = function (enable) {
  10164. this._depthCullingState.depthMask = enable;
  10165. };
  10166. Engine.prototype.setColorWrite = function (enable) {
  10167. this._gl.colorMask(enable, enable, enable, enable);
  10168. this._colorWrite = enable;
  10169. };
  10170. Engine.prototype.getColorWrite = function () {
  10171. return this._colorWrite;
  10172. };
  10173. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10174. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10175. };
  10176. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10177. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10178. if (this._alphaMode === mode) {
  10179. return;
  10180. }
  10181. switch (mode) {
  10182. case Engine.ALPHA_DISABLE:
  10183. this._alphaState.alphaBlend = false;
  10184. break;
  10185. case Engine.ALPHA_PREMULTIPLIED:
  10186. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10187. this._alphaState.alphaBlend = true;
  10188. break;
  10189. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10190. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10191. this._alphaState.alphaBlend = true;
  10192. break;
  10193. case Engine.ALPHA_COMBINE:
  10194. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10195. this._alphaState.alphaBlend = true;
  10196. break;
  10197. case Engine.ALPHA_ONEONE:
  10198. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10199. this._alphaState.alphaBlend = true;
  10200. break;
  10201. case Engine.ALPHA_ADD:
  10202. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10203. this._alphaState.alphaBlend = true;
  10204. break;
  10205. case Engine.ALPHA_SUBTRACT:
  10206. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10207. this._alphaState.alphaBlend = true;
  10208. break;
  10209. case Engine.ALPHA_MULTIPLY:
  10210. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10211. this._alphaState.alphaBlend = true;
  10212. break;
  10213. case Engine.ALPHA_MAXIMIZED:
  10214. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10215. this._alphaState.alphaBlend = true;
  10216. break;
  10217. case Engine.ALPHA_INTERPOLATE:
  10218. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10219. this._alphaState.alphaBlend = true;
  10220. break;
  10221. case Engine.ALPHA_SCREENMODE:
  10222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10223. this._alphaState.alphaBlend = true;
  10224. break;
  10225. }
  10226. if (!noDepthWriteChange) {
  10227. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10228. }
  10229. this._alphaMode = mode;
  10230. };
  10231. Engine.prototype.getAlphaMode = function () {
  10232. return this._alphaMode;
  10233. };
  10234. Engine.prototype.setAlphaTesting = function (enable) {
  10235. this._alphaTest = enable;
  10236. };
  10237. Engine.prototype.getAlphaTesting = function () {
  10238. return !!this._alphaTest;
  10239. };
  10240. // Textures
  10241. Engine.prototype.wipeCaches = function (bruteForce) {
  10242. if (this.preventCacheWipeBetweenFrames) {
  10243. return;
  10244. }
  10245. this.resetTextureCache();
  10246. this._currentEffect = null;
  10247. // 6/8/2017: deltakosh: Should not be required anymore.
  10248. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10249. if (bruteForce) {
  10250. this._currentProgram = null;
  10251. this._stencilState.reset();
  10252. this._depthCullingState.reset();
  10253. this.setDepthFunctionToLessOrEqual();
  10254. this._alphaState.reset();
  10255. }
  10256. this._cachedVertexBuffers = null;
  10257. this._cachedIndexBuffer = null;
  10258. this._cachedEffectForVertexBuffers = null;
  10259. this._unbindVertexArrayObject();
  10260. this.bindIndexBuffer(null);
  10261. this.bindArrayBuffer(null);
  10262. };
  10263. /**
  10264. * Set the compressed texture format to use, based on the formats you have, and the formats
  10265. * supported by the hardware / browser.
  10266. *
  10267. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10268. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10269. * to API arguments needed to compressed textures. This puts the burden on the container
  10270. * generator to house the arcane code for determining these for current & future formats.
  10271. *
  10272. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10273. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10274. *
  10275. * Note: The result of this call is not taken into account when a texture is base64.
  10276. *
  10277. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10278. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10279. *
  10280. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10281. * @returns The extension selected.
  10282. */
  10283. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10284. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10285. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10286. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10287. return this._textureFormatInUse = this._texturesSupported[i];
  10288. }
  10289. }
  10290. }
  10291. // actively set format to nothing, to allow this to be called more than once
  10292. // and possibly fail the 2nd time
  10293. this._textureFormatInUse = null;
  10294. return null;
  10295. };
  10296. Engine.prototype._createTexture = function () {
  10297. var texture = this._gl.createTexture();
  10298. if (!texture) {
  10299. throw new Error("Unable to create texture");
  10300. }
  10301. return texture;
  10302. };
  10303. /**
  10304. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10305. * @param {string} urlArg- This contains one of the following:
  10306. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10307. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10308. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10309. *
  10310. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10311. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10312. * @param {Scene} scene- Needed for loading to the correct scene.
  10313. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10314. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10315. * @param {callback} onError- Optional callback to be called upon failure.
  10316. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10317. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10318. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10319. *
  10320. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10321. */
  10322. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10323. var _this = this;
  10324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10325. if (onLoad === void 0) { onLoad = null; }
  10326. if (onError === void 0) { onError = null; }
  10327. if (buffer === void 0) { buffer = null; }
  10328. if (fallBack === void 0) { fallBack = null; }
  10329. if (format === void 0) { format = null; }
  10330. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10331. var fromData = url.substr(0, 5) === "data:";
  10332. var fromBlob = url.substr(0, 5) === "blob:";
  10333. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10334. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10335. // establish the file extension, if possible
  10336. var lastDot = url.lastIndexOf('.');
  10337. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10338. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10339. var isTGA = (extension === ".tga");
  10340. // determine if a ktx file should be substituted
  10341. var isKTX = false;
  10342. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10343. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10344. isKTX = true;
  10345. }
  10346. if (scene) {
  10347. scene._addPendingData(texture);
  10348. }
  10349. texture.url = url;
  10350. texture.generateMipMaps = !noMipmap;
  10351. texture.samplingMode = samplingMode;
  10352. texture.invertY = invertY;
  10353. if (!this._doNotHandleContextLost) {
  10354. // Keep a link to the buffer only if we plan to handle context lost
  10355. texture._buffer = buffer;
  10356. }
  10357. var onLoadObserver = null;
  10358. if (onLoad && !fallBack) {
  10359. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10360. }
  10361. if (!fallBack)
  10362. this._internalTexturesCache.push(texture);
  10363. var onerror = function (message, exception) {
  10364. if (scene) {
  10365. scene._removePendingData(texture);
  10366. }
  10367. if (onLoadObserver) {
  10368. texture.onLoadedObservable.remove(onLoadObserver);
  10369. }
  10370. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10371. if (isKTX) {
  10372. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10373. }
  10374. else if (BABYLON.Tools.UseFallbackTexture) {
  10375. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10376. }
  10377. if (onError) {
  10378. onError(message || "Unknown error", exception);
  10379. }
  10380. };
  10381. var callback = null;
  10382. // processing for non-image formats
  10383. if (isKTX || isTGA || isDDS) {
  10384. if (isKTX) {
  10385. callback = function (data) {
  10386. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10387. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10388. ktx.uploadLevels(_this._gl, !noMipmap);
  10389. return false;
  10390. }, samplingMode);
  10391. };
  10392. }
  10393. else if (isTGA) {
  10394. callback = function (arrayBuffer) {
  10395. var data = new Uint8Array(arrayBuffer);
  10396. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10397. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10398. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10399. return false;
  10400. }, samplingMode);
  10401. };
  10402. }
  10403. else if (isDDS) {
  10404. callback = function (data) {
  10405. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10406. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10407. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10408. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10409. return false;
  10410. }, samplingMode);
  10411. };
  10412. }
  10413. if (!buffer) {
  10414. BABYLON.Tools.LoadFile(url, function (data) {
  10415. if (callback) {
  10416. callback(data);
  10417. }
  10418. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10419. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10420. });
  10421. }
  10422. else {
  10423. if (callback) {
  10424. callback(buffer);
  10425. }
  10426. }
  10427. // image format processing
  10428. }
  10429. else {
  10430. var onload = function (img) {
  10431. if (fromBlob && !_this._doNotHandleContextLost) {
  10432. // We need to store the image if we need to rebuild the texture
  10433. // in case of a webgl context lost
  10434. texture._buffer = img;
  10435. }
  10436. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10437. var gl = _this._gl;
  10438. var isPot = (img.width === potWidth && img.height === potHeight);
  10439. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10440. if (isPot) {
  10441. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10442. return false;
  10443. }
  10444. // Using shaders to rescale because canvas.drawImage is lossy
  10445. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10446. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10447. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10452. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10453. _this._releaseTexture(source);
  10454. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10455. continuationCallback();
  10456. });
  10457. return true;
  10458. }, samplingMode);
  10459. };
  10460. if (!fromData || isBase64)
  10461. if (buffer instanceof HTMLImageElement) {
  10462. onload(buffer);
  10463. }
  10464. else {
  10465. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10466. }
  10467. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10468. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10469. else
  10470. onload(buffer);
  10471. }
  10472. return texture;
  10473. };
  10474. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10475. var _this = this;
  10476. var rtt = this.createRenderTargetTexture({
  10477. width: destination.width,
  10478. height: destination.height,
  10479. }, {
  10480. generateMipMaps: false,
  10481. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10482. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10483. generateDepthBuffer: false,
  10484. generateStencilBuffer: false
  10485. });
  10486. if (!this._rescalePostProcess) {
  10487. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10488. }
  10489. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10490. _this._rescalePostProcess.onApply = function (effect) {
  10491. effect._bindTexture("textureSampler", source);
  10492. };
  10493. var hostingScene = scene;
  10494. if (!hostingScene) {
  10495. hostingScene = _this.scenes[_this.scenes.length - 1];
  10496. }
  10497. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10498. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10499. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10500. _this.unBindFramebuffer(rtt);
  10501. _this._releaseTexture(rtt);
  10502. if (onComplete) {
  10503. onComplete();
  10504. }
  10505. });
  10506. };
  10507. Engine.prototype._getInternalFormat = function (format) {
  10508. var internalFormat = this._gl.RGBA;
  10509. switch (format) {
  10510. case Engine.TEXTUREFORMAT_ALPHA:
  10511. internalFormat = this._gl.ALPHA;
  10512. break;
  10513. case Engine.TEXTUREFORMAT_LUMINANCE:
  10514. internalFormat = this._gl.LUMINANCE;
  10515. break;
  10516. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10517. internalFormat = this._gl.LUMINANCE_ALPHA;
  10518. break;
  10519. case Engine.TEXTUREFORMAT_RGB:
  10520. internalFormat = this._gl.RGB;
  10521. break;
  10522. case Engine.TEXTUREFORMAT_RGBA:
  10523. internalFormat = this._gl.RGBA;
  10524. break;
  10525. }
  10526. return internalFormat;
  10527. };
  10528. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10529. if (compression === void 0) { compression = null; }
  10530. if (!texture) {
  10531. return;
  10532. }
  10533. var internalFormat = this._getInternalFormat(format);
  10534. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10535. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10536. if (!this._doNotHandleContextLost) {
  10537. texture._bufferView = data;
  10538. texture.format = format;
  10539. texture.invertY = invertY;
  10540. texture._compression = compression;
  10541. }
  10542. if (texture.width % 4 !== 0) {
  10543. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10544. }
  10545. if (compression && data) {
  10546. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10547. }
  10548. else {
  10549. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10550. }
  10551. if (texture.generateMipMaps) {
  10552. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10553. }
  10554. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10555. this.resetTextureCache();
  10556. texture.isReady = true;
  10557. };
  10558. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10559. if (compression === void 0) { compression = null; }
  10560. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10561. texture.baseWidth = width;
  10562. texture.baseHeight = height;
  10563. texture.width = width;
  10564. texture.height = height;
  10565. texture.format = format;
  10566. texture.generateMipMaps = generateMipMaps;
  10567. texture.samplingMode = samplingMode;
  10568. texture.invertY = invertY;
  10569. texture._compression = compression;
  10570. if (!this._doNotHandleContextLost) {
  10571. texture._bufferView = data;
  10572. }
  10573. this.updateRawTexture(texture, data, format, invertY, compression);
  10574. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10575. // Filters
  10576. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10577. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10578. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10579. if (generateMipMaps) {
  10580. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10581. }
  10582. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10583. this._internalTexturesCache.push(texture);
  10584. return texture;
  10585. };
  10586. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10587. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10588. texture.baseWidth = width;
  10589. texture.baseHeight = height;
  10590. if (generateMipMaps) {
  10591. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10592. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10593. }
  10594. this.resetTextureCache();
  10595. texture.width = width;
  10596. texture.height = height;
  10597. texture.isReady = false;
  10598. texture.generateMipMaps = generateMipMaps;
  10599. texture.samplingMode = samplingMode;
  10600. this.updateTextureSamplingMode(samplingMode, texture);
  10601. this._internalTexturesCache.push(texture);
  10602. return texture;
  10603. };
  10604. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10605. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10606. if (texture.isCube) {
  10607. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10608. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10609. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10610. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10611. }
  10612. else if (texture.is3D) {
  10613. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10614. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10615. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10616. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10617. }
  10618. else {
  10619. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10620. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10622. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10623. }
  10624. texture.samplingMode = samplingMode;
  10625. };
  10626. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10627. if (premulAlpha === void 0) { premulAlpha = false; }
  10628. if (!texture) {
  10629. return;
  10630. }
  10631. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10632. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10633. if (premulAlpha) {
  10634. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10635. }
  10636. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10637. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10638. if (texture.generateMipMaps) {
  10639. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10640. }
  10641. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10642. if (premulAlpha) {
  10643. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10644. }
  10645. this.resetTextureCache();
  10646. texture.isReady = true;
  10647. };
  10648. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10649. if (!texture || texture._isDisabled) {
  10650. return;
  10651. }
  10652. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10653. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10654. try {
  10655. // Testing video texture support
  10656. if (this._videoTextureSupported === undefined) {
  10657. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10658. if (this._gl.getError() !== 0) {
  10659. this._videoTextureSupported = false;
  10660. }
  10661. else {
  10662. this._videoTextureSupported = true;
  10663. }
  10664. }
  10665. // Copy video through the current working canvas if video texture is not supported
  10666. if (!this._videoTextureSupported) {
  10667. if (!texture._workingCanvas) {
  10668. texture._workingCanvas = document.createElement("canvas");
  10669. var context = texture._workingCanvas.getContext("2d");
  10670. if (!context) {
  10671. throw new Error("Unable to get 2d context");
  10672. }
  10673. texture._workingContext = context;
  10674. texture._workingCanvas.width = texture.width;
  10675. texture._workingCanvas.height = texture.height;
  10676. }
  10677. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10679. }
  10680. else {
  10681. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10682. }
  10683. if (texture.generateMipMaps) {
  10684. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10685. }
  10686. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10687. this.resetTextureCache();
  10688. texture.isReady = true;
  10689. }
  10690. catch (ex) {
  10691. // Something unexpected
  10692. // Let's disable the texture
  10693. texture._isDisabled = true;
  10694. }
  10695. };
  10696. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10697. var fullOptions = new RenderTargetCreationOptions();
  10698. if (options !== undefined && typeof options === "object") {
  10699. fullOptions.generateMipMaps = options.generateMipMaps;
  10700. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10701. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10702. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10703. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10704. }
  10705. else {
  10706. fullOptions.generateMipMaps = options;
  10707. fullOptions.generateDepthBuffer = true;
  10708. fullOptions.generateStencilBuffer = false;
  10709. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10710. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10711. }
  10712. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10713. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10714. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10715. }
  10716. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10717. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10718. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10719. }
  10720. var gl = this._gl;
  10721. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10722. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10723. var width = size.width || size;
  10724. var height = size.height || size;
  10725. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10726. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10727. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10728. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10729. }
  10730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10734. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10735. // Create the framebuffer
  10736. var framebuffer = gl.createFramebuffer();
  10737. this.bindUnboundFramebuffer(framebuffer);
  10738. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10739. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10740. if (fullOptions.generateMipMaps) {
  10741. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10742. }
  10743. // Unbind
  10744. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10746. this.bindUnboundFramebuffer(null);
  10747. texture._framebuffer = framebuffer;
  10748. texture.baseWidth = width;
  10749. texture.baseHeight = height;
  10750. texture.width = width;
  10751. texture.height = height;
  10752. texture.isReady = true;
  10753. texture.samples = 1;
  10754. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10755. texture.samplingMode = fullOptions.samplingMode;
  10756. texture.type = fullOptions.type;
  10757. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10758. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10759. this.resetTextureCache();
  10760. this._internalTexturesCache.push(texture);
  10761. return texture;
  10762. };
  10763. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10764. var generateMipMaps = false;
  10765. var generateDepthBuffer = true;
  10766. var generateStencilBuffer = false;
  10767. var generateDepthTexture = false;
  10768. var textureCount = 1;
  10769. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10770. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10771. var types = [], samplingModes = [];
  10772. if (options !== undefined) {
  10773. generateMipMaps = options.generateMipMaps;
  10774. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10775. generateStencilBuffer = options.generateStencilBuffer;
  10776. generateDepthTexture = options.generateDepthTexture;
  10777. textureCount = options.textureCount || 1;
  10778. if (options.types) {
  10779. types = options.types;
  10780. }
  10781. if (options.samplingModes) {
  10782. samplingModes = options.samplingModes;
  10783. }
  10784. }
  10785. var gl = this._gl;
  10786. // Create the framebuffer
  10787. var framebuffer = gl.createFramebuffer();
  10788. this.bindUnboundFramebuffer(framebuffer);
  10789. var width = size.width || size;
  10790. var height = size.height || size;
  10791. var textures = [];
  10792. var attachments = [];
  10793. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10794. for (var i = 0; i < textureCount; i++) {
  10795. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10796. var type = types[i] || defaultType;
  10797. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10798. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10799. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10800. }
  10801. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10802. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10803. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10804. }
  10805. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10806. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10807. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10808. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10809. }
  10810. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10811. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10812. textures.push(texture);
  10813. attachments.push(attachment);
  10814. gl.activeTexture(gl["TEXTURE" + i]);
  10815. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10820. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10821. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10822. if (generateMipMaps) {
  10823. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10824. }
  10825. // Unbind
  10826. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10827. texture._framebuffer = framebuffer;
  10828. texture._depthStencilBuffer = depthStencilBuffer;
  10829. texture.baseWidth = width;
  10830. texture.baseHeight = height;
  10831. texture.width = width;
  10832. texture.height = height;
  10833. texture.isReady = true;
  10834. texture.samples = 1;
  10835. texture.generateMipMaps = generateMipMaps;
  10836. texture.samplingMode = samplingMode;
  10837. texture.type = type;
  10838. texture._generateDepthBuffer = generateDepthBuffer;
  10839. texture._generateStencilBuffer = generateStencilBuffer;
  10840. this._internalTexturesCache.push(texture);
  10841. }
  10842. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10843. // Depth texture
  10844. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10845. gl.activeTexture(gl.TEXTURE0);
  10846. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10847. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10850. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10851. 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);
  10852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10853. depthTexture._framebuffer = framebuffer;
  10854. depthTexture.baseWidth = width;
  10855. depthTexture.baseHeight = height;
  10856. depthTexture.width = width;
  10857. depthTexture.height = height;
  10858. depthTexture.isReady = true;
  10859. depthTexture.samples = 1;
  10860. depthTexture.generateMipMaps = generateMipMaps;
  10861. depthTexture.samplingMode = gl.NEAREST;
  10862. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10863. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10864. textures.push(depthTexture);
  10865. this._internalTexturesCache.push(depthTexture);
  10866. }
  10867. gl.drawBuffers(attachments);
  10868. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10869. this.bindUnboundFramebuffer(null);
  10870. this.resetTextureCache();
  10871. return textures;
  10872. };
  10873. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10874. if (samples === void 0) { samples = 1; }
  10875. var depthStencilBuffer = null;
  10876. var gl = this._gl;
  10877. // Create the depth/stencil buffer
  10878. if (generateStencilBuffer) {
  10879. depthStencilBuffer = gl.createRenderbuffer();
  10880. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10881. if (samples > 1) {
  10882. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10883. }
  10884. else {
  10885. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10886. }
  10887. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10888. }
  10889. else if (generateDepthBuffer) {
  10890. depthStencilBuffer = gl.createRenderbuffer();
  10891. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10892. if (samples > 1) {
  10893. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10894. }
  10895. else {
  10896. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10897. }
  10898. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10899. }
  10900. return depthStencilBuffer;
  10901. };
  10902. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10903. if (this.webGLVersion < 2 || !texture) {
  10904. return 1;
  10905. }
  10906. if (texture.samples === samples) {
  10907. return samples;
  10908. }
  10909. var gl = this._gl;
  10910. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10911. // Dispose previous render buffers
  10912. if (texture._depthStencilBuffer) {
  10913. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10914. }
  10915. if (texture._MSAAFramebuffer) {
  10916. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10917. }
  10918. if (texture._MSAARenderBuffer) {
  10919. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10920. }
  10921. if (samples > 1) {
  10922. var framebuffer = gl.createFramebuffer();
  10923. if (!framebuffer) {
  10924. throw new Error("Unable to create multi sampled framebuffer");
  10925. }
  10926. texture._MSAAFramebuffer = framebuffer;
  10927. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10928. var colorRenderbuffer = gl.createRenderbuffer();
  10929. if (!colorRenderbuffer) {
  10930. throw new Error("Unable to create multi sampled framebuffer");
  10931. }
  10932. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10934. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10935. texture._MSAARenderBuffer = colorRenderbuffer;
  10936. }
  10937. else {
  10938. this.bindUnboundFramebuffer(texture._framebuffer);
  10939. }
  10940. texture.samples = samples;
  10941. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10942. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10943. this.bindUnboundFramebuffer(null);
  10944. return samples;
  10945. };
  10946. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10947. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10948. };
  10949. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10950. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10951. };
  10952. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10953. var gl = this._gl;
  10954. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10955. var generateMipMaps = true;
  10956. var generateDepthBuffer = true;
  10957. var generateStencilBuffer = false;
  10958. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10959. if (options !== undefined) {
  10960. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10961. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10962. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10963. if (options.samplingMode !== undefined) {
  10964. samplingMode = options.samplingMode;
  10965. }
  10966. }
  10967. texture.isCube = true;
  10968. texture.generateMipMaps = generateMipMaps;
  10969. texture.samples = 1;
  10970. texture.samplingMode = samplingMode;
  10971. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10972. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10973. for (var face = 0; face < 6; face++) {
  10974. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10975. }
  10976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10980. // Create the framebuffer
  10981. var framebuffer = gl.createFramebuffer();
  10982. this.bindUnboundFramebuffer(framebuffer);
  10983. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10984. // Mipmaps
  10985. if (texture.generateMipMaps) {
  10986. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10987. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10988. }
  10989. // Unbind
  10990. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10991. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10992. this.bindUnboundFramebuffer(null);
  10993. texture._framebuffer = framebuffer;
  10994. texture.width = size;
  10995. texture.height = size;
  10996. texture.isReady = true;
  10997. this.resetTextureCache();
  10998. this._internalTexturesCache.push(texture);
  10999. return texture;
  11000. };
  11001. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11002. var _this = this;
  11003. if (onLoad === void 0) { onLoad = null; }
  11004. if (onError === void 0) { onError = null; }
  11005. if (forcedExtension === void 0) { forcedExtension = null; }
  11006. var callback = function (loadData) {
  11007. if (!loadData) {
  11008. if (onLoad) {
  11009. onLoad(null);
  11010. }
  11011. return;
  11012. }
  11013. var texture = loadData.texture;
  11014. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11015. texture._lodGenerationScale = scale;
  11016. texture._lodGenerationOffset = offset;
  11017. if (_this._caps.textureLOD) {
  11018. // Do not add extra process if texture lod is supported.
  11019. if (onLoad) {
  11020. onLoad(texture);
  11021. }
  11022. return;
  11023. }
  11024. var mipSlices = 3;
  11025. var gl = _this._gl;
  11026. var width = loadData.width;
  11027. if (!width) {
  11028. return;
  11029. }
  11030. var textures = [];
  11031. for (var i = 0; i < mipSlices; i++) {
  11032. //compute LOD from even spacing in smoothness (matching shader calculation)
  11033. var smoothness = i / (mipSlices - 1);
  11034. var roughness = 1 - smoothness;
  11035. var minLODIndex = offset; // roughness = 0
  11036. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11037. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11038. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11039. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11040. glTextureFromLod.isCube = true;
  11041. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  11042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11046. if (loadData.isDDS) {
  11047. var info = loadData.info;
  11048. var data = loadData.data;
  11049. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11050. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11051. }
  11052. else {
  11053. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11054. }
  11055. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11056. // Wrap in a base texture for easy binding.
  11057. var lodTexture = new BABYLON.BaseTexture(scene);
  11058. lodTexture.isCube = true;
  11059. lodTexture._texture = glTextureFromLod;
  11060. glTextureFromLod.isReady = true;
  11061. textures.push(lodTexture);
  11062. }
  11063. texture._lodTextureHigh = textures[2];
  11064. texture._lodTextureMid = textures[1];
  11065. texture._lodTextureLow = textures[0];
  11066. if (onLoad) {
  11067. onLoad(texture);
  11068. }
  11069. };
  11070. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11071. };
  11072. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11073. var _this = this;
  11074. if (onLoad === void 0) { onLoad = null; }
  11075. if (onError === void 0) { onError = null; }
  11076. if (forcedExtension === void 0) { forcedExtension = null; }
  11077. var gl = this._gl;
  11078. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11079. texture.isCube = true;
  11080. texture.url = rootUrl;
  11081. texture.generateMipMaps = !noMipmap;
  11082. if (!this._doNotHandleContextLost) {
  11083. texture._extension = forcedExtension;
  11084. texture._files = files;
  11085. }
  11086. var isKTX = false;
  11087. var isDDS = false;
  11088. var lastDot = rootUrl.lastIndexOf('.');
  11089. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11090. if (this._textureFormatInUse) {
  11091. extension = this._textureFormatInUse;
  11092. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11093. isKTX = true;
  11094. }
  11095. else {
  11096. isDDS = (extension === ".dds");
  11097. }
  11098. var onerror = function (request, exception) {
  11099. if (onError && request) {
  11100. onError(request.status + " " + request.statusText, exception);
  11101. }
  11102. };
  11103. if (isKTX) {
  11104. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11105. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11106. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11107. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11109. ktx.uploadLevels(_this._gl, !noMipmap);
  11110. _this.setCubeMapTextureParams(gl, loadMipmap);
  11111. texture.width = ktx.pixelWidth;
  11112. texture.height = ktx.pixelHeight;
  11113. texture.isReady = true;
  11114. }, undefined, undefined, true, onerror);
  11115. }
  11116. else if (isDDS) {
  11117. if (files && files.length === 6) {
  11118. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11119. var info;
  11120. var loadMipmap = false;
  11121. var width = 0;
  11122. for (var index = 0; index < imgs.length; index++) {
  11123. var data = imgs[index];
  11124. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11125. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11126. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11127. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11128. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11129. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11130. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11131. }
  11132. texture.width = info.width;
  11133. texture.height = info.height;
  11134. texture.type = info.textureType;
  11135. width = info.width;
  11136. }
  11137. _this.setCubeMapTextureParams(gl, loadMipmap);
  11138. texture.isReady = true;
  11139. if (onLoad) {
  11140. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11141. }
  11142. }, files, onError);
  11143. }
  11144. else {
  11145. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11146. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11147. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11148. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11150. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11151. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11152. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11153. }
  11154. _this.setCubeMapTextureParams(gl, loadMipmap);
  11155. texture.width = info.width;
  11156. texture.height = info.height;
  11157. texture.isReady = true;
  11158. texture.type = info.textureType;
  11159. if (onLoad) {
  11160. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11161. }
  11162. }, undefined, undefined, true, onerror);
  11163. }
  11164. }
  11165. else {
  11166. if (!files) {
  11167. throw new Error("Cannot load cubemap because files were not defined");
  11168. }
  11169. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11170. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11171. var height = width;
  11172. _this._prepareWorkingCanvas();
  11173. if (!_this._workingCanvas || !_this._workingContext) {
  11174. return;
  11175. }
  11176. _this._workingCanvas.width = width;
  11177. _this._workingCanvas.height = height;
  11178. var faces = [
  11179. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11180. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11181. ];
  11182. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11183. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11184. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11185. for (var index = 0; index < faces.length; index++) {
  11186. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11187. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11188. }
  11189. if (!noMipmap) {
  11190. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11191. }
  11192. _this.setCubeMapTextureParams(gl, !noMipmap);
  11193. texture.width = width;
  11194. texture.height = height;
  11195. texture.isReady = true;
  11196. if (format) {
  11197. texture.format = format;
  11198. }
  11199. texture.onLoadedObservable.notifyObservers(texture);
  11200. texture.onLoadedObservable.clear();
  11201. if (onLoad) {
  11202. onLoad();
  11203. }
  11204. }, files, onError);
  11205. }
  11206. this._internalTexturesCache.push(texture);
  11207. return texture;
  11208. };
  11209. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11214. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11215. this.resetTextureCache();
  11216. };
  11217. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11218. if (compression === void 0) { compression = null; }
  11219. if (level === void 0) { level = 0; }
  11220. texture._bufferViewArray = data;
  11221. texture.format = format;
  11222. texture.type = type;
  11223. texture.invertY = invertY;
  11224. texture._compression = compression;
  11225. var gl = this._gl;
  11226. var textureType = this._getWebGLTextureType(type);
  11227. var internalFormat = this._getInternalFormat(format);
  11228. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11229. var needConversion = false;
  11230. if (internalFormat === gl.RGB) {
  11231. internalFormat = gl.RGBA;
  11232. needConversion = true;
  11233. }
  11234. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11235. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11236. if (texture.width % 4 !== 0) {
  11237. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11238. }
  11239. // Data are known to be in +X +Y +Z -X -Y -Z
  11240. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11241. var faceData = data[faceIndex];
  11242. if (compression) {
  11243. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11244. }
  11245. else {
  11246. if (needConversion) {
  11247. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11248. }
  11249. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11250. }
  11251. }
  11252. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11253. if (isPot && texture.generateMipMaps && level === 0) {
  11254. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11255. }
  11256. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11257. this.resetTextureCache();
  11258. texture.isReady = true;
  11259. };
  11260. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11261. if (compression === void 0) { compression = null; }
  11262. var gl = this._gl;
  11263. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11264. texture.isCube = true;
  11265. texture.generateMipMaps = generateMipMaps;
  11266. texture.format = format;
  11267. texture.type = type;
  11268. if (!this._doNotHandleContextLost) {
  11269. texture._bufferViewArray = data;
  11270. }
  11271. var textureType = this._getWebGLTextureType(type);
  11272. var internalFormat = this._getInternalFormat(format);
  11273. if (internalFormat === gl.RGB) {
  11274. internalFormat = gl.RGBA;
  11275. }
  11276. var width = size;
  11277. var height = width;
  11278. texture.width = width;
  11279. texture.height = height;
  11280. // Double check on POT to generate Mips.
  11281. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11282. if (!isPot) {
  11283. generateMipMaps = false;
  11284. }
  11285. // Upload data if needed. The texture won't be ready until then.
  11286. if (data) {
  11287. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11288. }
  11289. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11290. // Filters
  11291. if (data && generateMipMaps) {
  11292. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11293. }
  11294. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11297. }
  11298. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11301. }
  11302. else {
  11303. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11306. }
  11307. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11309. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11310. return texture;
  11311. };
  11312. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11313. var _this = this;
  11314. if (onLoad === void 0) { onLoad = null; }
  11315. if (onError === void 0) { onError = null; }
  11316. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11317. if (invertY === void 0) { invertY = false; }
  11318. var gl = this._gl;
  11319. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11320. scene._addPendingData(texture);
  11321. texture.url = url;
  11322. this._internalTexturesCache.push(texture);
  11323. var onerror = function (request, exception) {
  11324. scene._removePendingData(texture);
  11325. if (onError && request) {
  11326. onError(request.status + " " + request.statusText, exception);
  11327. }
  11328. };
  11329. var internalCallback = function (data) {
  11330. var width = texture.width;
  11331. var faceDataArrays = callback(data);
  11332. if (!faceDataArrays) {
  11333. return;
  11334. }
  11335. if (mipmmapGenerator) {
  11336. var textureType = _this._getWebGLTextureType(type);
  11337. var internalFormat = _this._getInternalFormat(format);
  11338. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11339. var needConversion = false;
  11340. if (internalFormat === gl.RGB) {
  11341. internalFormat = gl.RGBA;
  11342. needConversion = true;
  11343. }
  11344. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11345. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11346. var mipData = mipmmapGenerator(faceDataArrays);
  11347. for (var level = 0; level < mipData.length; level++) {
  11348. var mipSize = width >> level;
  11349. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11350. var mipFaceData = mipData[level][faceIndex];
  11351. if (needConversion) {
  11352. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11353. }
  11354. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11355. }
  11356. }
  11357. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11358. }
  11359. else {
  11360. texture.generateMipMaps = !noMipmap;
  11361. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11362. }
  11363. texture.isReady = true;
  11364. _this.resetTextureCache();
  11365. scene._removePendingData(texture);
  11366. if (onLoad) {
  11367. onLoad();
  11368. }
  11369. };
  11370. BABYLON.Tools.LoadFile(url, function (data) {
  11371. internalCallback(data);
  11372. }, undefined, scene.database, true, onerror);
  11373. return texture;
  11374. };
  11375. ;
  11376. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11377. if (compression === void 0) { compression = null; }
  11378. var internalFormat = this._getInternalFormat(format);
  11379. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11380. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11381. if (!this._doNotHandleContextLost) {
  11382. texture._bufferView = data;
  11383. texture.format = format;
  11384. texture.invertY = invertY;
  11385. texture._compression = compression;
  11386. }
  11387. if (texture.width % 4 !== 0) {
  11388. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11389. }
  11390. if (compression && data) {
  11391. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11392. }
  11393. else {
  11394. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11395. }
  11396. if (texture.generateMipMaps) {
  11397. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11398. }
  11399. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11400. this.resetTextureCache();
  11401. texture.isReady = true;
  11402. };
  11403. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11404. if (compression === void 0) { compression = null; }
  11405. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11406. texture.baseWidth = width;
  11407. texture.baseHeight = height;
  11408. texture.baseDepth = depth;
  11409. texture.width = width;
  11410. texture.height = height;
  11411. texture.depth = depth;
  11412. texture.format = format;
  11413. texture.generateMipMaps = generateMipMaps;
  11414. texture.samplingMode = samplingMode;
  11415. texture.is3D = true;
  11416. if (!this._doNotHandleContextLost) {
  11417. texture._bufferView = data;
  11418. }
  11419. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11420. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11421. // Filters
  11422. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11423. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11424. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11425. if (generateMipMaps) {
  11426. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11427. }
  11428. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11429. this._internalTexturesCache.push(texture);
  11430. return texture;
  11431. };
  11432. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11433. var gl = this._gl;
  11434. if (!gl) {
  11435. return;
  11436. }
  11437. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11440. if (!noMipmap && !isCompressed) {
  11441. gl.generateMipmap(gl.TEXTURE_2D);
  11442. }
  11443. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11444. this.resetTextureCache();
  11445. if (scene) {
  11446. scene._removePendingData(texture);
  11447. }
  11448. texture.onLoadedObservable.notifyObservers(texture);
  11449. texture.onLoadedObservable.clear();
  11450. };
  11451. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11452. var _this = this;
  11453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11454. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11455. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11456. var gl = this._gl;
  11457. if (!gl) {
  11458. return;
  11459. }
  11460. if (!texture._webGLTexture) {
  11461. this.resetTextureCache();
  11462. if (scene) {
  11463. scene._removePendingData(texture);
  11464. }
  11465. return;
  11466. }
  11467. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11468. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11469. texture.baseWidth = width;
  11470. texture.baseHeight = height;
  11471. texture.width = potWidth;
  11472. texture.height = potHeight;
  11473. texture.isReady = true;
  11474. if (processFunction(potWidth, potHeight, function () {
  11475. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11476. })) {
  11477. // Returning as texture needs extra async steps
  11478. return;
  11479. }
  11480. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11481. };
  11482. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11483. // Create new RGBA data container.
  11484. var rgbaData;
  11485. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11486. rgbaData = new Float32Array(width * height * 4);
  11487. }
  11488. else {
  11489. rgbaData = new Uint32Array(width * height * 4);
  11490. }
  11491. // Convert each pixel.
  11492. for (var x = 0; x < width; x++) {
  11493. for (var y = 0; y < height; y++) {
  11494. var index = (y * width + x) * 3;
  11495. var newIndex = (y * width + x) * 4;
  11496. // Map Old Value to new value.
  11497. rgbaData[newIndex + 0] = rgbData[index + 0];
  11498. rgbaData[newIndex + 1] = rgbData[index + 1];
  11499. rgbaData[newIndex + 2] = rgbData[index + 2];
  11500. // Add fully opaque alpha channel.
  11501. rgbaData[newIndex + 3] = 1;
  11502. }
  11503. }
  11504. return rgbaData;
  11505. };
  11506. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11507. var gl = this._gl;
  11508. if (texture._framebuffer) {
  11509. gl.deleteFramebuffer(texture._framebuffer);
  11510. texture._framebuffer = null;
  11511. }
  11512. if (texture._depthStencilBuffer) {
  11513. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11514. texture._depthStencilBuffer = null;
  11515. }
  11516. if (texture._MSAAFramebuffer) {
  11517. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11518. texture._MSAAFramebuffer = null;
  11519. }
  11520. if (texture._MSAARenderBuffer) {
  11521. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11522. texture._MSAARenderBuffer = null;
  11523. }
  11524. };
  11525. Engine.prototype._releaseTexture = function (texture) {
  11526. var gl = this._gl;
  11527. this._releaseFramebufferObjects(texture);
  11528. gl.deleteTexture(texture._webGLTexture);
  11529. // Unbind channels
  11530. this.unbindAllTextures();
  11531. var index = this._internalTexturesCache.indexOf(texture);
  11532. if (index !== -1) {
  11533. this._internalTexturesCache.splice(index, 1);
  11534. }
  11535. // Integrated fixed lod samplers.
  11536. if (texture._lodTextureHigh) {
  11537. texture._lodTextureHigh.dispose();
  11538. }
  11539. if (texture._lodTextureMid) {
  11540. texture._lodTextureMid.dispose();
  11541. }
  11542. if (texture._lodTextureLow) {
  11543. texture._lodTextureLow.dispose();
  11544. }
  11545. };
  11546. Engine.prototype.setProgram = function (program) {
  11547. if (this._currentProgram !== program) {
  11548. this._gl.useProgram(program);
  11549. this._currentProgram = program;
  11550. }
  11551. };
  11552. Engine.prototype.bindSamplers = function (effect) {
  11553. this.setProgram(effect.getProgram());
  11554. var samplers = effect.getSamplers();
  11555. for (var index = 0; index < samplers.length; index++) {
  11556. var uniform = effect.getUniform(samplers[index]);
  11557. this._gl.uniform1i(uniform, index);
  11558. }
  11559. this._currentEffect = null;
  11560. };
  11561. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11562. if (this._activeTextureChannel !== textureChannel) {
  11563. this._gl.activeTexture(textureChannel);
  11564. this._activeTextureChannel = textureChannel;
  11565. }
  11566. };
  11567. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11568. if (this._boundTexturesCache[this._activeTextureChannel] !== texture) {
  11569. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11570. this._boundTexturesCache[this._activeTextureChannel] = texture;
  11571. }
  11572. };
  11573. Engine.prototype._bindTexture = function (channel, texture) {
  11574. if (channel < 0) {
  11575. return;
  11576. }
  11577. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11578. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11579. };
  11580. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11581. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11582. };
  11583. Engine.prototype.unbindAllTextures = function () {
  11584. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11585. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11587. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11588. if (this.webGLVersion > 1) {
  11589. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11590. }
  11591. }
  11592. };
  11593. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11594. if (channel < 0) {
  11595. return;
  11596. }
  11597. if (this._setTexture(channel, texture)) {
  11598. this._gl.uniform1i(uniform, channel);
  11599. }
  11600. };
  11601. Engine.prototype._setTexture = function (channel, texture) {
  11602. // Not ready?
  11603. if (!texture) {
  11604. if (this._boundTexturesCache[channel] != null) {
  11605. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11606. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11607. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11608. if (this.webGLVersion > 1) {
  11609. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11610. }
  11611. }
  11612. return false;
  11613. }
  11614. // Video
  11615. var alreadyActivated = false;
  11616. if (texture.video) {
  11617. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11618. alreadyActivated = true;
  11619. texture.update();
  11620. }
  11621. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11622. texture.delayLoad();
  11623. return false;
  11624. }
  11625. var internalTexture;
  11626. if (texture.isReady()) {
  11627. internalTexture = texture.getInternalTexture();
  11628. }
  11629. else if (texture.isCube) {
  11630. internalTexture = this.emptyCubeTexture;
  11631. }
  11632. else if (texture.is3D) {
  11633. internalTexture = this.emptyTexture3D;
  11634. }
  11635. else {
  11636. internalTexture = this.emptyTexture;
  11637. }
  11638. if (!alreadyActivated) {
  11639. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11640. }
  11641. if (this._boundTexturesCache[this._activeTextureChannel] === internalTexture) {
  11642. return false;
  11643. }
  11644. if (internalTexture && internalTexture.is3D) {
  11645. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11646. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11647. internalTexture._cachedWrapU = texture.wrapU;
  11648. switch (texture.wrapU) {
  11649. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11650. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11651. break;
  11652. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11653. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11654. break;
  11655. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11656. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11657. break;
  11658. }
  11659. }
  11660. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11661. internalTexture._cachedWrapV = texture.wrapV;
  11662. switch (texture.wrapV) {
  11663. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11664. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11665. break;
  11666. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11667. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11668. break;
  11669. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11670. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11671. break;
  11672. }
  11673. }
  11674. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11675. internalTexture._cachedWrapR = texture.wrapR;
  11676. switch (texture.wrapV) {
  11677. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11678. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11679. break;
  11680. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11681. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11682. break;
  11683. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11684. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11685. break;
  11686. }
  11687. }
  11688. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11689. }
  11690. else if (internalTexture && internalTexture.isCube) {
  11691. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11692. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11693. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11694. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11695. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11696. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11697. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11698. }
  11699. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11700. }
  11701. else {
  11702. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11703. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11704. internalTexture._cachedWrapU = texture.wrapU;
  11705. switch (texture.wrapU) {
  11706. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11707. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11708. break;
  11709. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11711. break;
  11712. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11713. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11714. break;
  11715. }
  11716. }
  11717. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11718. internalTexture._cachedWrapV = texture.wrapV;
  11719. switch (texture.wrapV) {
  11720. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11721. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11722. break;
  11723. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11724. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11725. break;
  11726. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11727. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11728. break;
  11729. }
  11730. }
  11731. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11732. }
  11733. return true;
  11734. };
  11735. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11736. if (channel < 0 || !uniform) {
  11737. return;
  11738. }
  11739. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11740. this._textureUnits = new Int32Array(textures.length);
  11741. }
  11742. for (var i = 0; i < textures.length; i++) {
  11743. this._textureUnits[i] = channel + i;
  11744. }
  11745. this._gl.uniform1iv(uniform, this._textureUnits);
  11746. for (var index = 0; index < textures.length; index++) {
  11747. this._setTexture(channel + index, textures[index]);
  11748. }
  11749. };
  11750. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11751. var internalTexture = texture.getInternalTexture();
  11752. if (!internalTexture) {
  11753. return;
  11754. }
  11755. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11756. var value = texture.anisotropicFilteringLevel;
  11757. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11758. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11759. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11760. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11761. }
  11762. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11763. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11764. internalTexture._cachedAnisotropicFilteringLevel = value;
  11765. }
  11766. };
  11767. Engine.prototype.readPixels = function (x, y, width, height) {
  11768. var data = new Uint8Array(height * width * 4);
  11769. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11770. return data;
  11771. };
  11772. /**
  11773. * Add an externaly attached data from its key.
  11774. * This method call will fail and return false, if such key already exists.
  11775. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11776. * @param key the unique key that identifies the data
  11777. * @param data the data object to associate to the key for this Engine instance
  11778. * @return true if no such key were already present and the data was added successfully, false otherwise
  11779. */
  11780. Engine.prototype.addExternalData = function (key, data) {
  11781. if (!this._externalData) {
  11782. this._externalData = new BABYLON.StringDictionary();
  11783. }
  11784. return this._externalData.add(key, data);
  11785. };
  11786. /**
  11787. * Get an externaly attached data from its key
  11788. * @param key the unique key that identifies the data
  11789. * @return the associated data, if present (can be null), or undefined if not present
  11790. */
  11791. Engine.prototype.getExternalData = function (key) {
  11792. if (!this._externalData) {
  11793. this._externalData = new BABYLON.StringDictionary();
  11794. }
  11795. return this._externalData.get(key);
  11796. };
  11797. /**
  11798. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11799. * @param key the unique key that identifies the data
  11800. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11801. * @return the associated data, can be null if the factory returned null.
  11802. */
  11803. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11804. if (!this._externalData) {
  11805. this._externalData = new BABYLON.StringDictionary();
  11806. }
  11807. return this._externalData.getOrAddWithFactory(key, factory);
  11808. };
  11809. /**
  11810. * Remove an externaly attached data from the Engine instance
  11811. * @param key the unique key that identifies the data
  11812. * @return true if the data was successfully removed, false if it doesn't exist
  11813. */
  11814. Engine.prototype.removeExternalData = function (key) {
  11815. if (!this._externalData) {
  11816. this._externalData = new BABYLON.StringDictionary();
  11817. }
  11818. return this._externalData.remove(key);
  11819. };
  11820. Engine.prototype.unbindAllAttributes = function () {
  11821. if (this._mustWipeVertexAttributes) {
  11822. this._mustWipeVertexAttributes = false;
  11823. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11824. this._gl.disableVertexAttribArray(i);
  11825. this._vertexAttribArraysEnabled[i] = false;
  11826. this._currentBufferPointers[i].active = false;
  11827. }
  11828. return;
  11829. }
  11830. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11831. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11832. continue;
  11833. }
  11834. this._gl.disableVertexAttribArray(i);
  11835. this._vertexAttribArraysEnabled[i] = false;
  11836. this._currentBufferPointers[i].active = false;
  11837. }
  11838. };
  11839. Engine.prototype.releaseEffects = function () {
  11840. for (var name in this._compiledEffects) {
  11841. this._deleteProgram(this._compiledEffects[name]._program);
  11842. }
  11843. this._compiledEffects = {};
  11844. };
  11845. // Dispose
  11846. Engine.prototype.dispose = function () {
  11847. this.hideLoadingUI();
  11848. this.stopRenderLoop();
  11849. // Release postProcesses
  11850. while (this.postProcesses.length) {
  11851. this.postProcesses[0].dispose();
  11852. }
  11853. // Empty texture
  11854. if (this._emptyTexture) {
  11855. this._releaseTexture(this._emptyTexture);
  11856. this._emptyTexture = null;
  11857. }
  11858. if (this._emptyCubeTexture) {
  11859. this._releaseTexture(this._emptyCubeTexture);
  11860. this._emptyCubeTexture = null;
  11861. }
  11862. // Rescale PP
  11863. if (this._rescalePostProcess) {
  11864. this._rescalePostProcess.dispose();
  11865. }
  11866. // Release scenes
  11867. while (this.scenes.length) {
  11868. this.scenes[0].dispose();
  11869. }
  11870. // Release audio engine
  11871. if (Engine.audioEngine) {
  11872. Engine.audioEngine.dispose();
  11873. }
  11874. // Release effects
  11875. this.releaseEffects();
  11876. // Unbind
  11877. this.unbindAllAttributes();
  11878. if (this._dummyFramebuffer) {
  11879. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11880. }
  11881. //WebVR
  11882. this.disableVR();
  11883. // Events
  11884. if (BABYLON.Tools.IsWindowObjectExist()) {
  11885. window.removeEventListener("blur", this._onBlur);
  11886. window.removeEventListener("focus", this._onFocus);
  11887. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11888. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11889. if (this._renderingCanvas) {
  11890. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11891. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11892. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11893. if (!this._doNotHandleContextLost) {
  11894. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11895. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11896. }
  11897. }
  11898. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11899. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11900. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11901. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11902. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11903. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11904. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11905. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11906. if (this._onVrDisplayConnect) {
  11907. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11908. if (this._onVrDisplayDisconnect) {
  11909. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11910. }
  11911. if (this._onVrDisplayPresentChange) {
  11912. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11913. }
  11914. this._onVrDisplayConnect = null;
  11915. this._onVrDisplayDisconnect = null;
  11916. }
  11917. }
  11918. // Remove from Instances
  11919. var index = Engine.Instances.indexOf(this);
  11920. if (index >= 0) {
  11921. Engine.Instances.splice(index, 1);
  11922. }
  11923. this._workingCanvas = null;
  11924. this._workingContext = null;
  11925. this._currentBufferPointers = [];
  11926. this._renderingCanvas = null;
  11927. this._currentProgram = null;
  11928. this.onResizeObservable.clear();
  11929. this.onCanvasBlurObservable.clear();
  11930. this.onCanvasFocusObservable.clear();
  11931. this.onCanvasPointerOutObservable.clear();
  11932. this.onBeginFrameObservable.clear();
  11933. this.onEndFrameObservable.clear();
  11934. BABYLON.Effect.ResetCache();
  11935. };
  11936. // Loading screen
  11937. Engine.prototype.displayLoadingUI = function () {
  11938. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11939. return;
  11940. }
  11941. var loadingScreen = this.loadingScreen;
  11942. if (loadingScreen) {
  11943. loadingScreen.displayLoadingUI();
  11944. }
  11945. };
  11946. Engine.prototype.hideLoadingUI = function () {
  11947. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11948. return;
  11949. }
  11950. var loadingScreen = this.loadingScreen;
  11951. if (loadingScreen) {
  11952. loadingScreen.hideLoadingUI();
  11953. }
  11954. };
  11955. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11956. get: function () {
  11957. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11958. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11959. return this._loadingScreen;
  11960. },
  11961. set: function (loadingScreen) {
  11962. this._loadingScreen = loadingScreen;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11968. set: function (text) {
  11969. this.loadingScreen.loadingUIText = text;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11975. set: function (color) {
  11976. this.loadingScreen.loadingUIBackgroundColor = color;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Engine.prototype.attachContextLostEvent = function (callback) {
  11982. if (this._renderingCanvas) {
  11983. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11984. }
  11985. };
  11986. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11987. if (this._renderingCanvas) {
  11988. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11989. }
  11990. };
  11991. Engine.prototype.getVertexShaderSource = function (program) {
  11992. var shaders = this._gl.getAttachedShaders(program);
  11993. if (!shaders) {
  11994. return null;
  11995. }
  11996. return this._gl.getShaderSource(shaders[0]);
  11997. };
  11998. Engine.prototype.getFragmentShaderSource = function (program) {
  11999. var shaders = this._gl.getAttachedShaders(program);
  12000. if (!shaders) {
  12001. return null;
  12002. }
  12003. return this._gl.getShaderSource(shaders[1]);
  12004. };
  12005. Engine.prototype.getError = function () {
  12006. return this._gl.getError();
  12007. };
  12008. // FPS
  12009. Engine.prototype.getFps = function () {
  12010. return this._fps;
  12011. };
  12012. Engine.prototype.getDeltaTime = function () {
  12013. return this._deltaTime;
  12014. };
  12015. Engine.prototype._measureFps = function () {
  12016. this._performanceMonitor.sampleFrame();
  12017. this._fps = this._performanceMonitor.averageFPS;
  12018. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12019. };
  12020. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12021. if (faceIndex === void 0) { faceIndex = -1; }
  12022. var gl = this._gl;
  12023. if (!this._dummyFramebuffer) {
  12024. var dummy = gl.createFramebuffer();
  12025. if (!dummy) {
  12026. throw new Error("Unable to create dummy framebuffer");
  12027. }
  12028. this._dummyFramebuffer = dummy;
  12029. }
  12030. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12031. if (faceIndex > -1) {
  12032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12033. }
  12034. else {
  12035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12036. }
  12037. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12038. var buffer;
  12039. switch (readType) {
  12040. case gl.UNSIGNED_BYTE:
  12041. buffer = new Uint8Array(4 * width * height);
  12042. readType = gl.UNSIGNED_BYTE;
  12043. break;
  12044. default:
  12045. buffer = new Float32Array(4 * width * height);
  12046. readType = gl.FLOAT;
  12047. break;
  12048. }
  12049. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12050. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12051. return buffer;
  12052. };
  12053. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12054. if (this._webGLVersion > 1) {
  12055. return this._caps.colorBufferFloat;
  12056. }
  12057. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  12058. };
  12059. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12060. if (this._webGLVersion > 1) {
  12061. return this._caps.colorBufferFloat;
  12062. }
  12063. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  12064. };
  12065. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12066. Engine.prototype._canRenderToFramebuffer = function (type) {
  12067. var gl = this._gl;
  12068. //clear existing errors
  12069. while (gl.getError() !== gl.NO_ERROR) { }
  12070. var successful = true;
  12071. var texture = gl.createTexture();
  12072. gl.bindTexture(gl.TEXTURE_2D, texture);
  12073. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12076. var fb = gl.createFramebuffer();
  12077. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12079. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12080. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12081. successful = successful && (gl.getError() === gl.NO_ERROR);
  12082. //try render by clearing frame buffer's color buffer
  12083. if (successful) {
  12084. gl.clear(gl.COLOR_BUFFER_BIT);
  12085. successful = successful && (gl.getError() === gl.NO_ERROR);
  12086. }
  12087. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12088. if (successful) {
  12089. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12090. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12091. var readFormat = gl.RGBA;
  12092. var readType = gl.UNSIGNED_BYTE;
  12093. var buffer = new Uint8Array(4);
  12094. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12095. successful = successful && (gl.getError() === gl.NO_ERROR);
  12096. }
  12097. //clean up
  12098. gl.deleteTexture(texture);
  12099. gl.deleteFramebuffer(fb);
  12100. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12101. //clear accumulated errors
  12102. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12103. return successful;
  12104. };
  12105. Engine.prototype._getWebGLTextureType = function (type) {
  12106. if (type === Engine.TEXTURETYPE_FLOAT) {
  12107. return this._gl.FLOAT;
  12108. }
  12109. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12110. // Add Half Float Constant.
  12111. return this._gl.HALF_FLOAT_OES;
  12112. }
  12113. return this._gl.UNSIGNED_BYTE;
  12114. };
  12115. ;
  12116. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12117. if (this._webGLVersion === 1) {
  12118. return this._gl.RGBA;
  12119. }
  12120. if (type === Engine.TEXTURETYPE_FLOAT) {
  12121. return this._gl.RGBA32F;
  12122. }
  12123. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12124. return this._gl.RGBA16F;
  12125. }
  12126. return this._gl.RGBA;
  12127. };
  12128. ;
  12129. Engine.prototype.createQuery = function () {
  12130. return this._gl.createQuery();
  12131. };
  12132. Engine.prototype.deleteQuery = function (query) {
  12133. this._gl.deleteQuery(query);
  12134. return this;
  12135. };
  12136. Engine.prototype.isQueryResultAvailable = function (query) {
  12137. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12138. };
  12139. Engine.prototype.getQueryResult = function (query) {
  12140. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12141. };
  12142. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12143. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12144. this._gl.beginQuery(glAlgorithm, query);
  12145. return this;
  12146. };
  12147. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12148. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12149. this._gl.endQuery(glAlgorithm);
  12150. return this;
  12151. };
  12152. /* Time queries */
  12153. Engine.prototype._createTimeQuery = function () {
  12154. var timerQuery = this._caps.timerQuery;
  12155. if (timerQuery.createQueryEXT) {
  12156. return timerQuery.createQueryEXT();
  12157. }
  12158. return this.createQuery();
  12159. };
  12160. Engine.prototype._deleteTimeQuery = function (query) {
  12161. var timerQuery = this._caps.timerQuery;
  12162. if (timerQuery.deleteQueryEXT) {
  12163. timerQuery.deleteQueryEXT(query);
  12164. return;
  12165. }
  12166. this.deleteQuery(query);
  12167. };
  12168. Engine.prototype._getTimeQueryResult = function (query) {
  12169. var timerQuery = this._caps.timerQuery;
  12170. if (timerQuery.getQueryObjectEXT) {
  12171. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12172. }
  12173. return this.getQueryResult(query);
  12174. };
  12175. Engine.prototype._getTimeQueryAvailability = function (query) {
  12176. var timerQuery = this._caps.timerQuery;
  12177. if (timerQuery.getQueryObjectEXT) {
  12178. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12179. }
  12180. return this.isQueryResultAvailable(query);
  12181. };
  12182. Engine.prototype.startTimeQuery = function () {
  12183. var timerQuery = this._caps.timerQuery;
  12184. if (!timerQuery) {
  12185. return null;
  12186. }
  12187. var token = new BABYLON._TimeToken();
  12188. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12189. if (this._caps.canUseTimestampForTimerQuery) {
  12190. token._startTimeQuery = this._createTimeQuery();
  12191. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12192. }
  12193. else {
  12194. if (this._currentNonTimestampToken) {
  12195. return this._currentNonTimestampToken;
  12196. }
  12197. token._timeElapsedQuery = this._createTimeQuery();
  12198. if (timerQuery.beginQueryEXT) {
  12199. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12200. }
  12201. else {
  12202. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12203. }
  12204. this._currentNonTimestampToken = token;
  12205. }
  12206. return token;
  12207. };
  12208. Engine.prototype.endTimeQuery = function (token) {
  12209. var timerQuery = this._caps.timerQuery;
  12210. if (!timerQuery || !token) {
  12211. return -1;
  12212. }
  12213. if (this._caps.canUseTimestampForTimerQuery) {
  12214. if (!token._startTimeQuery) {
  12215. return -1;
  12216. }
  12217. if (!token._endTimeQuery) {
  12218. token._endTimeQuery = this._createTimeQuery();
  12219. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12220. }
  12221. }
  12222. else if (!token._timeElapsedQueryEnded) {
  12223. if (!token._timeElapsedQuery) {
  12224. return -1;
  12225. }
  12226. if (timerQuery.endQueryEXT) {
  12227. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12228. }
  12229. else {
  12230. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12231. }
  12232. token._timeElapsedQueryEnded = true;
  12233. }
  12234. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12235. var available = false;
  12236. if (token._endTimeQuery) {
  12237. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12238. }
  12239. else if (token._timeElapsedQuery) {
  12240. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12241. }
  12242. if (available && !disjoint) {
  12243. var result = 0;
  12244. if (this._caps.canUseTimestampForTimerQuery) {
  12245. if (!token._startTimeQuery || !token._endTimeQuery) {
  12246. return -1;
  12247. }
  12248. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12249. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12250. result = timeEnd - timeStart;
  12251. this._deleteTimeQuery(token._startTimeQuery);
  12252. this._deleteTimeQuery(token._endTimeQuery);
  12253. token._startTimeQuery = null;
  12254. token._endTimeQuery = null;
  12255. }
  12256. else {
  12257. if (!token._timeElapsedQuery) {
  12258. return -1;
  12259. }
  12260. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12261. this._deleteTimeQuery(token._timeElapsedQuery);
  12262. token._timeElapsedQuery = null;
  12263. token._timeElapsedQueryEnded = false;
  12264. this._currentNonTimestampToken = null;
  12265. }
  12266. return result;
  12267. }
  12268. return -1;
  12269. };
  12270. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12271. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12272. };
  12273. // Transform feedback
  12274. Engine.prototype.createTransformFeedback = function () {
  12275. return this._gl.createTransformFeedback();
  12276. };
  12277. Engine.prototype.deleteTransformFeedback = function (value) {
  12278. this._gl.deleteTransformFeedback(value);
  12279. };
  12280. Engine.prototype.bindTransformFeedback = function (value) {
  12281. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12282. };
  12283. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12284. if (usePoints === void 0) { usePoints = true; }
  12285. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12286. };
  12287. Engine.prototype.endTransformFeedback = function () {
  12288. this._gl.endTransformFeedback();
  12289. };
  12290. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12291. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12292. };
  12293. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12294. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12295. };
  12296. // Statics
  12297. Engine.isSupported = function () {
  12298. try {
  12299. var tempcanvas = document.createElement("canvas");
  12300. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12301. return gl != null && !!window.WebGLRenderingContext;
  12302. }
  12303. catch (e) {
  12304. return false;
  12305. }
  12306. };
  12307. Engine.Instances = new Array();
  12308. // Const statics
  12309. Engine._ALPHA_DISABLE = 0;
  12310. Engine._ALPHA_ADD = 1;
  12311. Engine._ALPHA_COMBINE = 2;
  12312. Engine._ALPHA_SUBTRACT = 3;
  12313. Engine._ALPHA_MULTIPLY = 4;
  12314. Engine._ALPHA_MAXIMIZED = 5;
  12315. Engine._ALPHA_ONEONE = 6;
  12316. Engine._ALPHA_PREMULTIPLIED = 7;
  12317. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12318. Engine._ALPHA_INTERPOLATE = 9;
  12319. Engine._ALPHA_SCREENMODE = 10;
  12320. Engine._DELAYLOADSTATE_NONE = 0;
  12321. Engine._DELAYLOADSTATE_LOADED = 1;
  12322. Engine._DELAYLOADSTATE_LOADING = 2;
  12323. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12324. Engine._TEXTUREFORMAT_ALPHA = 0;
  12325. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12326. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12327. Engine._TEXTUREFORMAT_RGB = 4;
  12328. Engine._TEXTUREFORMAT_RGBA = 5;
  12329. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12330. Engine._TEXTURETYPE_FLOAT = 1;
  12331. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12332. // Depht or Stencil test Constants.
  12333. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12334. 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.
  12335. 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.
  12336. 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.
  12337. 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.
  12338. 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.
  12339. 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.
  12340. 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.
  12341. // Stencil Actions Constants.
  12342. Engine._KEEP = 0x1E00;
  12343. Engine._REPLACE = 0x1E01;
  12344. Engine._INCR = 0x1E02;
  12345. Engine._DECR = 0x1E03;
  12346. Engine._INVERT = 0x150A;
  12347. Engine._INCR_WRAP = 0x8507;
  12348. Engine._DECR_WRAP = 0x8508;
  12349. // Texture rescaling mode
  12350. Engine._SCALEMODE_FLOOR = 1;
  12351. Engine._SCALEMODE_NEAREST = 2;
  12352. Engine._SCALEMODE_CEILING = 3;
  12353. // Updatable statics so stick with vars here
  12354. Engine.CollisionsEpsilon = 0.001;
  12355. Engine.CodeRepository = "src/";
  12356. Engine.ShadersRepository = "src/Shaders/";
  12357. return Engine;
  12358. }());
  12359. BABYLON.Engine = Engine;
  12360. })(BABYLON || (BABYLON = {}));
  12361. //# sourceMappingURL=babylon.engine.js.map
  12362. var BABYLON;
  12363. (function (BABYLON) {
  12364. /**
  12365. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12366. */
  12367. var Node = /** @class */ (function () {
  12368. /**
  12369. * @constructor
  12370. * @param {string} name - the name and id to be given to this node
  12371. * @param {BABYLON.Scene} the scene this node will be added to
  12372. */
  12373. function Node(name, scene) {
  12374. if (scene === void 0) { scene = null; }
  12375. this.state = "";
  12376. this.metadata = null;
  12377. this.doNotSerialize = false;
  12378. this.animations = new Array();
  12379. this._ranges = {};
  12380. this._isEnabled = true;
  12381. this._isReady = true;
  12382. this._currentRenderId = -1;
  12383. this._parentRenderId = -1;
  12384. /**
  12385. * An event triggered when the mesh is disposed.
  12386. * @type {BABYLON.Observable}
  12387. */
  12388. this.onDisposeObservable = new BABYLON.Observable();
  12389. // Behaviors
  12390. this._behaviors = new Array();
  12391. this.name = name;
  12392. this.id = name;
  12393. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12394. this.uniqueId = this._scene.getUniqueId();
  12395. this._initCache();
  12396. }
  12397. Object.defineProperty(Node.prototype, "parent", {
  12398. get: function () {
  12399. return this._parentNode;
  12400. },
  12401. set: function (parent) {
  12402. if (this._parentNode === parent) {
  12403. return;
  12404. }
  12405. if (this._parentNode) {
  12406. var index = this._parentNode._children.indexOf(this);
  12407. if (index !== -1) {
  12408. this._parentNode._children.splice(index, 1);
  12409. }
  12410. }
  12411. this._parentNode = parent;
  12412. if (this._parentNode) {
  12413. if (!this._parentNode._children) {
  12414. this._parentNode._children = new Array();
  12415. }
  12416. this._parentNode._children.push(this);
  12417. }
  12418. },
  12419. enumerable: true,
  12420. configurable: true
  12421. });
  12422. Node.prototype.getClassName = function () {
  12423. return "Node";
  12424. };
  12425. Object.defineProperty(Node.prototype, "onDispose", {
  12426. set: function (callback) {
  12427. if (this._onDisposeObserver) {
  12428. this.onDisposeObservable.remove(this._onDisposeObserver);
  12429. }
  12430. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Node.prototype.getScene = function () {
  12436. return this._scene;
  12437. };
  12438. Node.prototype.getEngine = function () {
  12439. return this._scene.getEngine();
  12440. };
  12441. Node.prototype.addBehavior = function (behavior) {
  12442. var _this = this;
  12443. var index = this._behaviors.indexOf(behavior);
  12444. if (index !== -1) {
  12445. return this;
  12446. }
  12447. behavior.init();
  12448. if (this._scene.isLoading) {
  12449. // We defer the attach when the scene will be loaded
  12450. var observer = this._scene.onDataLoadedObservable.add(function () {
  12451. behavior.attach(_this);
  12452. _this._scene.onDataLoadedObservable.remove(observer);
  12453. });
  12454. }
  12455. else {
  12456. behavior.attach(this);
  12457. }
  12458. this._behaviors.push(behavior);
  12459. return this;
  12460. };
  12461. Node.prototype.removeBehavior = function (behavior) {
  12462. var index = this._behaviors.indexOf(behavior);
  12463. if (index === -1) {
  12464. return this;
  12465. }
  12466. this._behaviors[index].detach();
  12467. this._behaviors.splice(index, 1);
  12468. return this;
  12469. };
  12470. Object.defineProperty(Node.prototype, "behaviors", {
  12471. get: function () {
  12472. return this._behaviors;
  12473. },
  12474. enumerable: true,
  12475. configurable: true
  12476. });
  12477. Node.prototype.getBehaviorByName = function (name) {
  12478. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12479. var behavior = _a[_i];
  12480. if (behavior.name === name) {
  12481. return behavior;
  12482. }
  12483. }
  12484. return null;
  12485. };
  12486. // override it in derived class
  12487. Node.prototype.getWorldMatrix = function () {
  12488. return BABYLON.Matrix.Identity();
  12489. };
  12490. // override it in derived class if you add new variables to the cache
  12491. // and call the parent class method
  12492. Node.prototype._initCache = function () {
  12493. this._cache = {};
  12494. this._cache.parent = undefined;
  12495. };
  12496. Node.prototype.updateCache = function (force) {
  12497. if (!force && this.isSynchronized())
  12498. return;
  12499. this._cache.parent = this.parent;
  12500. this._updateCache();
  12501. };
  12502. // override it in derived class if you add new variables to the cache
  12503. // and call the parent class method if !ignoreParentClass
  12504. Node.prototype._updateCache = function (ignoreParentClass) {
  12505. };
  12506. // override it in derived class if you add new variables to the cache
  12507. Node.prototype._isSynchronized = function () {
  12508. return true;
  12509. };
  12510. Node.prototype._markSyncedWithParent = function () {
  12511. if (this.parent) {
  12512. this._parentRenderId = this.parent._currentRenderId;
  12513. }
  12514. };
  12515. Node.prototype.isSynchronizedWithParent = function () {
  12516. if (!this.parent) {
  12517. return true;
  12518. }
  12519. if (this._parentRenderId !== this.parent._currentRenderId) {
  12520. return false;
  12521. }
  12522. return this.parent.isSynchronized();
  12523. };
  12524. Node.prototype.isSynchronized = function (updateCache) {
  12525. var check = this.hasNewParent();
  12526. check = check || !this.isSynchronizedWithParent();
  12527. check = check || !this._isSynchronized();
  12528. if (updateCache)
  12529. this.updateCache(true);
  12530. return !check;
  12531. };
  12532. Node.prototype.hasNewParent = function (update) {
  12533. if (this._cache.parent === this.parent)
  12534. return false;
  12535. if (update)
  12536. this._cache.parent = this.parent;
  12537. return true;
  12538. };
  12539. /**
  12540. * Is this node ready to be used/rendered
  12541. * @return {boolean} is it ready
  12542. */
  12543. Node.prototype.isReady = function () {
  12544. return this._isReady;
  12545. };
  12546. /**
  12547. * Is this node enabled.
  12548. * If the node has a parent and is enabled, the parent will be inspected as well.
  12549. * @return {boolean} whether this node (and its parent) is enabled.
  12550. * @see setEnabled
  12551. */
  12552. Node.prototype.isEnabled = function () {
  12553. if (!this._isEnabled) {
  12554. return false;
  12555. }
  12556. if (this.parent) {
  12557. return this.parent.isEnabled();
  12558. }
  12559. return true;
  12560. };
  12561. /**
  12562. * Set the enabled state of this node.
  12563. * @param {boolean} value - the new enabled state
  12564. * @see isEnabled
  12565. */
  12566. Node.prototype.setEnabled = function (value) {
  12567. this._isEnabled = value;
  12568. };
  12569. /**
  12570. * Is this node a descendant of the given node.
  12571. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12572. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12573. * @see parent
  12574. */
  12575. Node.prototype.isDescendantOf = function (ancestor) {
  12576. if (this.parent) {
  12577. if (this.parent === ancestor) {
  12578. return true;
  12579. }
  12580. return this.parent.isDescendantOf(ancestor);
  12581. }
  12582. return false;
  12583. };
  12584. /**
  12585. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12586. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12587. * @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.
  12588. * @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.
  12589. */
  12590. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12591. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12592. if (!this._children) {
  12593. return;
  12594. }
  12595. for (var index = 0; index < this._children.length; index++) {
  12596. var item = this._children[index];
  12597. if (!predicate || predicate(item)) {
  12598. results.push(item);
  12599. }
  12600. if (!directDescendantsOnly) {
  12601. item._getDescendants(results, false, predicate);
  12602. }
  12603. }
  12604. };
  12605. /**
  12606. * Will return all nodes that have this node as ascendant.
  12607. * @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.
  12608. * @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.
  12609. * @return {BABYLON.Node[]} all children nodes of all types.
  12610. */
  12611. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12612. var results = new Array();
  12613. this._getDescendants(results, directDescendantsOnly, predicate);
  12614. return results;
  12615. };
  12616. /**
  12617. * Get all child-meshes of this node.
  12618. */
  12619. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12620. var results = [];
  12621. this._getDescendants(results, directDescendantsOnly, function (node) {
  12622. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12623. });
  12624. return results;
  12625. };
  12626. /**
  12627. * Get all child-transformNodes of this node.
  12628. */
  12629. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12630. var results = [];
  12631. this._getDescendants(results, directDescendantsOnly, function (node) {
  12632. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12633. });
  12634. return results;
  12635. };
  12636. /**
  12637. * Get all direct children of this node.
  12638. */
  12639. Node.prototype.getChildren = function (predicate) {
  12640. return this.getDescendants(true, predicate);
  12641. };
  12642. Node.prototype._setReady = function (state) {
  12643. if (state === this._isReady) {
  12644. return;
  12645. }
  12646. if (!state) {
  12647. this._isReady = false;
  12648. return;
  12649. }
  12650. this._isReady = true;
  12651. if (this.onReady) {
  12652. this.onReady(this);
  12653. }
  12654. };
  12655. Node.prototype.getAnimationByName = function (name) {
  12656. for (var i = 0; i < this.animations.length; i++) {
  12657. var animation = this.animations[i];
  12658. if (animation.name === name) {
  12659. return animation;
  12660. }
  12661. }
  12662. return null;
  12663. };
  12664. Node.prototype.createAnimationRange = function (name, from, to) {
  12665. // check name not already in use
  12666. if (!this._ranges[name]) {
  12667. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12668. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12669. if (this.animations[i]) {
  12670. this.animations[i].createRange(name, from, to);
  12671. }
  12672. }
  12673. }
  12674. };
  12675. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12676. if (deleteFrames === void 0) { deleteFrames = true; }
  12677. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12678. if (this.animations[i]) {
  12679. this.animations[i].deleteRange(name, deleteFrames);
  12680. }
  12681. }
  12682. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12683. };
  12684. Node.prototype.getAnimationRange = function (name) {
  12685. return this._ranges[name];
  12686. };
  12687. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12688. var range = this.getAnimationRange(name);
  12689. if (!range) {
  12690. return;
  12691. }
  12692. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12693. };
  12694. Node.prototype.serializeAnimationRanges = function () {
  12695. var serializationRanges = [];
  12696. for (var name in this._ranges) {
  12697. var localRange = this._ranges[name];
  12698. if (!localRange) {
  12699. continue;
  12700. }
  12701. var range = {};
  12702. range.name = name;
  12703. range.from = localRange.from;
  12704. range.to = localRange.to;
  12705. serializationRanges.push(range);
  12706. }
  12707. return serializationRanges;
  12708. };
  12709. Node.prototype.dispose = function () {
  12710. this.parent = null;
  12711. // Callback
  12712. this.onDisposeObservable.notifyObservers(this);
  12713. this.onDisposeObservable.clear();
  12714. // Behaviors
  12715. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12716. var behavior = _a[_i];
  12717. behavior.detach();
  12718. }
  12719. this._behaviors = [];
  12720. };
  12721. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12722. if (parsedNode.ranges) {
  12723. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12724. var data = parsedNode.ranges[index];
  12725. node.createAnimationRange(data.name, data.from, data.to);
  12726. }
  12727. }
  12728. };
  12729. __decorate([
  12730. BABYLON.serialize()
  12731. ], Node.prototype, "name", void 0);
  12732. __decorate([
  12733. BABYLON.serialize()
  12734. ], Node.prototype, "id", void 0);
  12735. __decorate([
  12736. BABYLON.serialize()
  12737. ], Node.prototype, "uniqueId", void 0);
  12738. __decorate([
  12739. BABYLON.serialize()
  12740. ], Node.prototype, "state", void 0);
  12741. __decorate([
  12742. BABYLON.serialize()
  12743. ], Node.prototype, "metadata", void 0);
  12744. return Node;
  12745. }());
  12746. BABYLON.Node = Node;
  12747. })(BABYLON || (BABYLON = {}));
  12748. //# sourceMappingURL=babylon.node.js.map
  12749. var BABYLON;
  12750. (function (BABYLON) {
  12751. var BoundingSphere = /** @class */ (function () {
  12752. function BoundingSphere(minimum, maximum) {
  12753. this.minimum = minimum;
  12754. this.maximum = maximum;
  12755. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12756. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12757. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12758. this.radius = distance * 0.5;
  12759. this.centerWorld = BABYLON.Vector3.Zero();
  12760. this._update(BABYLON.Matrix.Identity());
  12761. }
  12762. // Methods
  12763. BoundingSphere.prototype._update = function (world) {
  12764. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12765. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12766. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12767. };
  12768. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12769. for (var i = 0; i < 6; i++) {
  12770. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12771. return false;
  12772. }
  12773. return true;
  12774. };
  12775. BoundingSphere.prototype.intersectsPoint = function (point) {
  12776. var x = this.centerWorld.x - point.x;
  12777. var y = this.centerWorld.y - point.y;
  12778. var z = this.centerWorld.z - point.z;
  12779. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12780. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12781. return false;
  12782. return true;
  12783. };
  12784. // Statics
  12785. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12786. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12787. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12788. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12789. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12790. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12791. return false;
  12792. return true;
  12793. };
  12794. return BoundingSphere;
  12795. }());
  12796. BABYLON.BoundingSphere = BoundingSphere;
  12797. })(BABYLON || (BABYLON = {}));
  12798. //# sourceMappingURL=babylon.boundingSphere.js.map
  12799. var BABYLON;
  12800. (function (BABYLON) {
  12801. var BoundingBox = /** @class */ (function () {
  12802. function BoundingBox(minimum, maximum) {
  12803. this.minimum = minimum;
  12804. this.maximum = maximum;
  12805. this.vectors = new Array();
  12806. this.vectorsWorld = new Array();
  12807. // Bounding vectors
  12808. this.vectors.push(this.minimum.clone());
  12809. this.vectors.push(this.maximum.clone());
  12810. this.vectors.push(this.minimum.clone());
  12811. this.vectors[2].x = this.maximum.x;
  12812. this.vectors.push(this.minimum.clone());
  12813. this.vectors[3].y = this.maximum.y;
  12814. this.vectors.push(this.minimum.clone());
  12815. this.vectors[4].z = this.maximum.z;
  12816. this.vectors.push(this.maximum.clone());
  12817. this.vectors[5].z = this.minimum.z;
  12818. this.vectors.push(this.maximum.clone());
  12819. this.vectors[6].x = this.minimum.x;
  12820. this.vectors.push(this.maximum.clone());
  12821. this.vectors[7].y = this.minimum.y;
  12822. // OBB
  12823. this.center = this.maximum.add(this.minimum).scale(0.5);
  12824. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12825. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12826. // World
  12827. for (var index = 0; index < this.vectors.length; index++) {
  12828. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12829. }
  12830. this.minimumWorld = BABYLON.Vector3.Zero();
  12831. this.maximumWorld = BABYLON.Vector3.Zero();
  12832. this.centerWorld = BABYLON.Vector3.Zero();
  12833. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12834. this._update(BABYLON.Matrix.Identity());
  12835. }
  12836. // Methods
  12837. BoundingBox.prototype.getWorldMatrix = function () {
  12838. return this._worldMatrix;
  12839. };
  12840. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12841. this._worldMatrix.copyFrom(matrix);
  12842. return this;
  12843. };
  12844. BoundingBox.prototype._update = function (world) {
  12845. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12846. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12847. for (var index = 0; index < this.vectors.length; index++) {
  12848. var v = this.vectorsWorld[index];
  12849. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12850. if (v.x < this.minimumWorld.x)
  12851. this.minimumWorld.x = v.x;
  12852. if (v.y < this.minimumWorld.y)
  12853. this.minimumWorld.y = v.y;
  12854. if (v.z < this.minimumWorld.z)
  12855. this.minimumWorld.z = v.z;
  12856. if (v.x > this.maximumWorld.x)
  12857. this.maximumWorld.x = v.x;
  12858. if (v.y > this.maximumWorld.y)
  12859. this.maximumWorld.y = v.y;
  12860. if (v.z > this.maximumWorld.z)
  12861. this.maximumWorld.z = v.z;
  12862. }
  12863. // Extend
  12864. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12865. this.extendSizeWorld.scaleInPlace(0.5);
  12866. // OBB
  12867. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12868. this.centerWorld.scaleInPlace(0.5);
  12869. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12870. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12871. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12872. this._worldMatrix = world;
  12873. };
  12874. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12875. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12876. };
  12877. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12878. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12879. };
  12880. BoundingBox.prototype.intersectsPoint = function (point) {
  12881. var delta = -BABYLON.Epsilon;
  12882. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12883. return false;
  12884. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12885. return false;
  12886. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12887. return false;
  12888. return true;
  12889. };
  12890. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12891. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12892. };
  12893. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12894. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12895. return false;
  12896. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12897. return false;
  12898. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12899. return false;
  12900. return true;
  12901. };
  12902. // Statics
  12903. BoundingBox.Intersects = function (box0, box1) {
  12904. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12905. return false;
  12906. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12907. return false;
  12908. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12909. return false;
  12910. return true;
  12911. };
  12912. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12913. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12914. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12915. return (num <= (sphereRadius * sphereRadius));
  12916. };
  12917. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12918. for (var p = 0; p < 6; p++) {
  12919. for (var i = 0; i < 8; i++) {
  12920. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12921. return false;
  12922. }
  12923. }
  12924. }
  12925. return true;
  12926. };
  12927. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12928. for (var p = 0; p < 6; p++) {
  12929. var inCount = 8;
  12930. for (var i = 0; i < 8; i++) {
  12931. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12932. --inCount;
  12933. }
  12934. else {
  12935. break;
  12936. }
  12937. }
  12938. if (inCount === 0)
  12939. return false;
  12940. }
  12941. return true;
  12942. };
  12943. return BoundingBox;
  12944. }());
  12945. BABYLON.BoundingBox = BoundingBox;
  12946. })(BABYLON || (BABYLON = {}));
  12947. //# sourceMappingURL=babylon.boundingBox.js.map
  12948. var BABYLON;
  12949. (function (BABYLON) {
  12950. var computeBoxExtents = function (axis, box) {
  12951. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12952. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12953. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12954. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12955. var r = r0 + r1 + r2;
  12956. return {
  12957. min: p - r,
  12958. max: p + r
  12959. };
  12960. };
  12961. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12962. var axisOverlap = function (axis, box0, box1) {
  12963. var result0 = computeBoxExtents(axis, box0);
  12964. var result1 = computeBoxExtents(axis, box1);
  12965. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12966. };
  12967. var BoundingInfo = /** @class */ (function () {
  12968. function BoundingInfo(minimum, maximum) {
  12969. this.minimum = minimum;
  12970. this.maximum = maximum;
  12971. this._isLocked = false;
  12972. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12973. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12974. }
  12975. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12976. get: function () {
  12977. return this._isLocked;
  12978. },
  12979. set: function (value) {
  12980. this._isLocked = value;
  12981. },
  12982. enumerable: true,
  12983. configurable: true
  12984. });
  12985. // Methods
  12986. BoundingInfo.prototype.update = function (world) {
  12987. if (this._isLocked) {
  12988. return;
  12989. }
  12990. this.boundingBox._update(world);
  12991. this.boundingSphere._update(world);
  12992. };
  12993. /**
  12994. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12995. * @param center New center of the bounding info
  12996. * @param extend New extend of the bounding info
  12997. */
  12998. BoundingInfo.prototype.centerOn = function (center, extend) {
  12999. this.minimum = center.subtract(extend);
  13000. this.maximum = center.add(extend);
  13001. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13002. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13003. return this;
  13004. };
  13005. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13006. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13007. return false;
  13008. return this.boundingBox.isInFrustum(frustumPlanes);
  13009. };
  13010. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13011. /**
  13012. * Gets the world distance between the min and max points of the bounding box
  13013. */
  13014. get: function () {
  13015. var boundingBox = this.boundingBox;
  13016. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13017. return size.length();
  13018. },
  13019. enumerable: true,
  13020. configurable: true
  13021. });
  13022. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13023. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13024. };
  13025. BoundingInfo.prototype._checkCollision = function (collider) {
  13026. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13027. };
  13028. BoundingInfo.prototype.intersectsPoint = function (point) {
  13029. if (!this.boundingSphere.centerWorld) {
  13030. return false;
  13031. }
  13032. if (!this.boundingSphere.intersectsPoint(point)) {
  13033. return false;
  13034. }
  13035. if (!this.boundingBox.intersectsPoint(point)) {
  13036. return false;
  13037. }
  13038. return true;
  13039. };
  13040. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13041. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13042. return false;
  13043. }
  13044. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13045. return false;
  13046. }
  13047. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13048. return false;
  13049. }
  13050. if (!precise) {
  13051. return true;
  13052. }
  13053. var box0 = this.boundingBox;
  13054. var box1 = boundingInfo.boundingBox;
  13055. if (!axisOverlap(box0.directions[0], box0, box1))
  13056. return false;
  13057. if (!axisOverlap(box0.directions[1], box0, box1))
  13058. return false;
  13059. if (!axisOverlap(box0.directions[2], box0, box1))
  13060. return false;
  13061. if (!axisOverlap(box1.directions[0], box0, box1))
  13062. return false;
  13063. if (!axisOverlap(box1.directions[1], box0, box1))
  13064. return false;
  13065. if (!axisOverlap(box1.directions[2], box0, box1))
  13066. return false;
  13067. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13068. return false;
  13069. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13070. return false;
  13071. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13072. return false;
  13073. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13074. return false;
  13075. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13076. return false;
  13077. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13078. return false;
  13079. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13080. return false;
  13081. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13082. return false;
  13083. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13084. return false;
  13085. return true;
  13086. };
  13087. return BoundingInfo;
  13088. }());
  13089. BABYLON.BoundingInfo = BoundingInfo;
  13090. })(BABYLON || (BABYLON = {}));
  13091. //# sourceMappingURL=babylon.boundingInfo.js.map
  13092. var BABYLON;
  13093. (function (BABYLON) {
  13094. var TransformNode = /** @class */ (function (_super) {
  13095. __extends(TransformNode, _super);
  13096. function TransformNode(name, scene, isPure) {
  13097. if (scene === void 0) { scene = null; }
  13098. if (isPure === void 0) { isPure = true; }
  13099. var _this = _super.call(this, name, scene) || this;
  13100. // Properties
  13101. _this._rotation = BABYLON.Vector3.Zero();
  13102. _this._scaling = BABYLON.Vector3.One();
  13103. _this._isDirty = false;
  13104. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13105. _this.scalingDeterminant = 1;
  13106. _this.infiniteDistance = false;
  13107. _this.position = BABYLON.Vector3.Zero();
  13108. _this._localWorld = BABYLON.Matrix.Zero();
  13109. _this._worldMatrix = BABYLON.Matrix.Zero();
  13110. _this._absolutePosition = BABYLON.Vector3.Zero();
  13111. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13112. _this._postMultiplyPivotMatrix = false;
  13113. _this._isWorldMatrixFrozen = false;
  13114. /**
  13115. * An event triggered after the world matrix is updated
  13116. * @type {BABYLON.Observable}
  13117. */
  13118. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13119. _this._nonUniformScaling = false;
  13120. if (isPure) {
  13121. _this.getScene().addTransformNode(_this);
  13122. }
  13123. return _this;
  13124. }
  13125. Object.defineProperty(TransformNode.prototype, "rotation", {
  13126. /**
  13127. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13128. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13129. * Default : (0.0, 0.0, 0.0)
  13130. */
  13131. get: function () {
  13132. return this._rotation;
  13133. },
  13134. set: function (newRotation) {
  13135. this._rotation = newRotation;
  13136. },
  13137. enumerable: true,
  13138. configurable: true
  13139. });
  13140. Object.defineProperty(TransformNode.prototype, "scaling", {
  13141. /**
  13142. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13143. * Default : (1.0, 1.0, 1.0)
  13144. */
  13145. get: function () {
  13146. return this._scaling;
  13147. },
  13148. /**
  13149. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13150. * Default : (1.0, 1.0, 1.0)
  13151. */
  13152. set: function (newScaling) {
  13153. this._scaling = newScaling;
  13154. },
  13155. enumerable: true,
  13156. configurable: true
  13157. });
  13158. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13159. /**
  13160. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13161. * It's null by default.
  13162. * 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)
  13163. */
  13164. get: function () {
  13165. return this._rotationQuaternion;
  13166. },
  13167. set: function (quaternion) {
  13168. this._rotationQuaternion = quaternion;
  13169. //reset the rotation vector.
  13170. if (quaternion && this.rotation.length()) {
  13171. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13172. }
  13173. },
  13174. enumerable: true,
  13175. configurable: true
  13176. });
  13177. /**
  13178. * Returns the latest update of the World matrix
  13179. * Returns a Matrix.
  13180. */
  13181. TransformNode.prototype.getWorldMatrix = function () {
  13182. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13183. this.computeWorldMatrix();
  13184. }
  13185. return this._worldMatrix;
  13186. };
  13187. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13188. /**
  13189. * Returns directly the latest state of the mesh World matrix.
  13190. * A Matrix is returned.
  13191. */
  13192. get: function () {
  13193. return this._worldMatrix;
  13194. },
  13195. enumerable: true,
  13196. configurable: true
  13197. });
  13198. /**
  13199. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13200. * Returns the AbstractMesh.
  13201. */
  13202. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13203. this._poseMatrix.copyFrom(matrix);
  13204. return this;
  13205. };
  13206. /**
  13207. * Returns the mesh Pose matrix.
  13208. * Returned object : Matrix
  13209. */
  13210. TransformNode.prototype.getPoseMatrix = function () {
  13211. return this._poseMatrix;
  13212. };
  13213. TransformNode.prototype._isSynchronized = function () {
  13214. if (this._isDirty) {
  13215. return false;
  13216. }
  13217. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13218. return false;
  13219. if (this._cache.pivotMatrixUpdated) {
  13220. return false;
  13221. }
  13222. if (this.infiniteDistance) {
  13223. return false;
  13224. }
  13225. if (!this._cache.position.equals(this.position))
  13226. return false;
  13227. if (this.rotationQuaternion) {
  13228. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13229. return false;
  13230. }
  13231. if (!this._cache.rotation.equals(this.rotation))
  13232. return false;
  13233. if (!this._cache.scaling.equals(this.scaling))
  13234. return false;
  13235. return true;
  13236. };
  13237. TransformNode.prototype._initCache = function () {
  13238. _super.prototype._initCache.call(this);
  13239. this._cache.localMatrixUpdated = false;
  13240. this._cache.position = BABYLON.Vector3.Zero();
  13241. this._cache.scaling = BABYLON.Vector3.Zero();
  13242. this._cache.rotation = BABYLON.Vector3.Zero();
  13243. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13244. this._cache.billboardMode = -1;
  13245. };
  13246. TransformNode.prototype.markAsDirty = function (property) {
  13247. if (property === "rotation") {
  13248. this.rotationQuaternion = null;
  13249. }
  13250. this._currentRenderId = Number.MAX_VALUE;
  13251. this._isDirty = true;
  13252. return this;
  13253. };
  13254. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13255. /**
  13256. * Returns the current mesh absolute position.
  13257. * Retuns a Vector3.
  13258. */
  13259. get: function () {
  13260. return this._absolutePosition;
  13261. },
  13262. enumerable: true,
  13263. configurable: true
  13264. });
  13265. /**
  13266. * Sets a new pivot matrix to the mesh.
  13267. * Returns the AbstractMesh.
  13268. */
  13269. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13270. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13271. this._pivotMatrix = matrix.clone();
  13272. this._cache.pivotMatrixUpdated = true;
  13273. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13274. if (this._postMultiplyPivotMatrix) {
  13275. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13276. }
  13277. return this;
  13278. };
  13279. /**
  13280. * Returns the mesh pivot matrix.
  13281. * Default : Identity.
  13282. * A Matrix is returned.
  13283. */
  13284. TransformNode.prototype.getPivotMatrix = function () {
  13285. return this._pivotMatrix;
  13286. };
  13287. /**
  13288. * Prevents the World matrix to be computed any longer.
  13289. * Returns the AbstractMesh.
  13290. */
  13291. TransformNode.prototype.freezeWorldMatrix = function () {
  13292. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13293. this.computeWorldMatrix(true);
  13294. this._isWorldMatrixFrozen = true;
  13295. return this;
  13296. };
  13297. /**
  13298. * Allows back the World matrix computation.
  13299. * Returns the AbstractMesh.
  13300. */
  13301. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13302. this._isWorldMatrixFrozen = false;
  13303. this.computeWorldMatrix(true);
  13304. return this;
  13305. };
  13306. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13307. /**
  13308. * True if the World matrix has been frozen.
  13309. * Returns a boolean.
  13310. */
  13311. get: function () {
  13312. return this._isWorldMatrixFrozen;
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. /**
  13318. * Retuns the mesh absolute position in the World.
  13319. * Returns a Vector3.
  13320. */
  13321. TransformNode.prototype.getAbsolutePosition = function () {
  13322. this.computeWorldMatrix();
  13323. return this._absolutePosition;
  13324. };
  13325. /**
  13326. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13327. * Returns the AbstractMesh.
  13328. */
  13329. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13330. if (!absolutePosition) {
  13331. return this;
  13332. }
  13333. var absolutePositionX;
  13334. var absolutePositionY;
  13335. var absolutePositionZ;
  13336. if (absolutePosition.x === undefined) {
  13337. if (arguments.length < 3) {
  13338. return this;
  13339. }
  13340. absolutePositionX = arguments[0];
  13341. absolutePositionY = arguments[1];
  13342. absolutePositionZ = arguments[2];
  13343. }
  13344. else {
  13345. absolutePositionX = absolutePosition.x;
  13346. absolutePositionY = absolutePosition.y;
  13347. absolutePositionZ = absolutePosition.z;
  13348. }
  13349. if (this.parent) {
  13350. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13351. invertParentWorldMatrix.invert();
  13352. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13353. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13354. }
  13355. else {
  13356. this.position.x = absolutePositionX;
  13357. this.position.y = absolutePositionY;
  13358. this.position.z = absolutePositionZ;
  13359. }
  13360. return this;
  13361. };
  13362. /**
  13363. * Sets the mesh position in its local space.
  13364. * Returns the AbstractMesh.
  13365. */
  13366. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13367. this.computeWorldMatrix();
  13368. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13369. return this;
  13370. };
  13371. /**
  13372. * Returns the mesh position in the local space from the current World matrix values.
  13373. * Returns a new Vector3.
  13374. */
  13375. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13376. this.computeWorldMatrix();
  13377. var invLocalWorldMatrix = this._localWorld.clone();
  13378. invLocalWorldMatrix.invert();
  13379. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13380. };
  13381. /**
  13382. * Translates the mesh along the passed Vector3 in its local space.
  13383. * Returns the AbstractMesh.
  13384. */
  13385. TransformNode.prototype.locallyTranslate = function (vector3) {
  13386. this.computeWorldMatrix(true);
  13387. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13388. return this;
  13389. };
  13390. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13391. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13392. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13393. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13394. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13395. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13396. /// <returns>Mesh oriented towards targetMesh</returns>
  13397. if (yawCor === void 0) { yawCor = 0; }
  13398. if (pitchCor === void 0) { pitchCor = 0; }
  13399. if (rollCor === void 0) { rollCor = 0; }
  13400. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13401. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13402. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13403. targetPoint.subtractToRef(pos, dv);
  13404. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13405. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13406. var pitch = Math.atan2(dv.y, len);
  13407. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13408. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13409. return this;
  13410. };
  13411. /**
  13412. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13413. * This Vector3 is expressed in the World space.
  13414. */
  13415. TransformNode.prototype.getDirection = function (localAxis) {
  13416. var result = BABYLON.Vector3.Zero();
  13417. this.getDirectionToRef(localAxis, result);
  13418. return result;
  13419. };
  13420. /**
  13421. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13422. * localAxis is expressed in the mesh local space.
  13423. * result is computed in the Wordl space from the mesh World matrix.
  13424. * Returns the AbstractMesh.
  13425. */
  13426. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13427. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13428. return this;
  13429. };
  13430. TransformNode.prototype.setPivotPoint = function (point, space) {
  13431. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13432. if (this.getScene().getRenderId() == 0) {
  13433. this.computeWorldMatrix(true);
  13434. }
  13435. var wm = this.getWorldMatrix();
  13436. if (space == BABYLON.Space.WORLD) {
  13437. var tmat = BABYLON.Tmp.Matrix[0];
  13438. wm.invertToRef(tmat);
  13439. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13440. }
  13441. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13442. this._pivotMatrix.m[12] = -point.x;
  13443. this._pivotMatrix.m[13] = -point.y;
  13444. this._pivotMatrix.m[14] = -point.z;
  13445. this._cache.pivotMatrixUpdated = true;
  13446. return this;
  13447. };
  13448. /**
  13449. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13450. */
  13451. TransformNode.prototype.getPivotPoint = function () {
  13452. var point = BABYLON.Vector3.Zero();
  13453. this.getPivotPointToRef(point);
  13454. return point;
  13455. };
  13456. /**
  13457. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13458. * Returns the AbstractMesh.
  13459. */
  13460. TransformNode.prototype.getPivotPointToRef = function (result) {
  13461. result.x = -this._pivotMatrix.m[12];
  13462. result.y = -this._pivotMatrix.m[13];
  13463. result.z = -this._pivotMatrix.m[14];
  13464. return this;
  13465. };
  13466. /**
  13467. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13468. */
  13469. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13470. var point = BABYLON.Vector3.Zero();
  13471. this.getAbsolutePivotPointToRef(point);
  13472. return point;
  13473. };
  13474. /**
  13475. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13476. * Returns the AbstractMesh.
  13477. */
  13478. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13479. result.x = this._pivotMatrix.m[12];
  13480. result.y = this._pivotMatrix.m[13];
  13481. result.z = this._pivotMatrix.m[14];
  13482. this.getPivotPointToRef(result);
  13483. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13484. return this;
  13485. };
  13486. /**
  13487. * Defines the passed node as the parent of the current node.
  13488. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13489. * Returns the TransformNode.
  13490. */
  13491. TransformNode.prototype.setParent = function (node) {
  13492. if (node == null) {
  13493. var rotation = BABYLON.Tmp.Quaternion[0];
  13494. var position = BABYLON.Tmp.Vector3[0];
  13495. var scale = BABYLON.Tmp.Vector3[1];
  13496. if (this.parent && this.parent.computeWorldMatrix) {
  13497. this.parent.computeWorldMatrix(true);
  13498. }
  13499. this.computeWorldMatrix(true);
  13500. this.getWorldMatrix().decompose(scale, rotation, position);
  13501. if (this.rotationQuaternion) {
  13502. this.rotationQuaternion.copyFrom(rotation);
  13503. }
  13504. else {
  13505. rotation.toEulerAnglesToRef(this.rotation);
  13506. }
  13507. this.scaling.x = scale.x;
  13508. this.scaling.y = scale.y;
  13509. this.scaling.z = scale.z;
  13510. this.position.x = position.x;
  13511. this.position.y = position.y;
  13512. this.position.z = position.z;
  13513. }
  13514. else {
  13515. var rotation = BABYLON.Tmp.Quaternion[0];
  13516. var position = BABYLON.Tmp.Vector3[0];
  13517. var scale = BABYLON.Tmp.Vector3[1];
  13518. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13519. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13520. this.computeWorldMatrix(true);
  13521. node.computeWorldMatrix(true);
  13522. node.getWorldMatrix().invertToRef(invParentMatrix);
  13523. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13524. diffMatrix.decompose(scale, rotation, position);
  13525. if (this.rotationQuaternion) {
  13526. this.rotationQuaternion.copyFrom(rotation);
  13527. }
  13528. else {
  13529. rotation.toEulerAnglesToRef(this.rotation);
  13530. }
  13531. this.position.x = position.x;
  13532. this.position.y = position.y;
  13533. this.position.z = position.z;
  13534. this.scaling.x = scale.x;
  13535. this.scaling.y = scale.y;
  13536. this.scaling.z = scale.z;
  13537. }
  13538. this.parent = node;
  13539. return this;
  13540. };
  13541. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13542. get: function () {
  13543. return this._nonUniformScaling;
  13544. },
  13545. enumerable: true,
  13546. configurable: true
  13547. });
  13548. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13549. if (this._nonUniformScaling === value) {
  13550. return false;
  13551. }
  13552. this._nonUniformScaling = true;
  13553. return true;
  13554. };
  13555. /**
  13556. * Attach the current TransformNode to another TransformNode associated with a bone
  13557. * @param bone Bone affecting the TransformNode
  13558. * @param affectedTransformNode TransformNode associated with the bone
  13559. */
  13560. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13561. this._transformToBoneReferal = affectedTransformNode;
  13562. this.parent = bone;
  13563. if (bone.getWorldMatrix().determinant() < 0) {
  13564. this.scalingDeterminant *= -1;
  13565. }
  13566. return this;
  13567. };
  13568. TransformNode.prototype.detachFromBone = function () {
  13569. if (!this.parent) {
  13570. return this;
  13571. }
  13572. if (this.parent.getWorldMatrix().determinant() < 0) {
  13573. this.scalingDeterminant *= -1;
  13574. }
  13575. this._transformToBoneReferal = null;
  13576. this.parent = null;
  13577. return this;
  13578. };
  13579. /**
  13580. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13581. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13582. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13583. * The passed axis is also normalized.
  13584. * Returns the AbstractMesh.
  13585. */
  13586. TransformNode.prototype.rotate = function (axis, amount, space) {
  13587. axis.normalize();
  13588. if (!this.rotationQuaternion) {
  13589. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13590. this.rotation = BABYLON.Vector3.Zero();
  13591. }
  13592. var rotationQuaternion;
  13593. if (!space || space === BABYLON.Space.LOCAL) {
  13594. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13595. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13596. }
  13597. else {
  13598. if (this.parent) {
  13599. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13600. invertParentWorldMatrix.invert();
  13601. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13602. }
  13603. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13604. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13605. }
  13606. return this;
  13607. };
  13608. /**
  13609. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13610. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13611. * The passed axis is also normalized.
  13612. * Returns the AbstractMesh.
  13613. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13614. */
  13615. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13616. axis.normalize();
  13617. if (!this.rotationQuaternion) {
  13618. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13619. this.rotation.copyFromFloats(0, 0, 0);
  13620. }
  13621. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13622. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13623. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13624. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13625. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13626. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13627. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13628. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13629. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13630. return this;
  13631. };
  13632. /**
  13633. * Translates the mesh along the axis vector for the passed distance in the given space.
  13634. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13635. * Returns the AbstractMesh.
  13636. */
  13637. TransformNode.prototype.translate = function (axis, distance, space) {
  13638. var displacementVector = axis.scale(distance);
  13639. if (!space || space === BABYLON.Space.LOCAL) {
  13640. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13641. this.setPositionWithLocalVector(tempV3);
  13642. }
  13643. else {
  13644. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13645. }
  13646. return this;
  13647. };
  13648. /**
  13649. * Adds a rotation step to the mesh current rotation.
  13650. * x, y, z are Euler angles expressed in radians.
  13651. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13652. * This means this rotation is made in the mesh local space only.
  13653. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13654. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13655. * ```javascript
  13656. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13657. * ```
  13658. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13659. * 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.
  13660. * Returns the AbstractMesh.
  13661. */
  13662. TransformNode.prototype.addRotation = function (x, y, z) {
  13663. var rotationQuaternion;
  13664. if (this.rotationQuaternion) {
  13665. rotationQuaternion = this.rotationQuaternion;
  13666. }
  13667. else {
  13668. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13669. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13670. }
  13671. var accumulation = BABYLON.Tmp.Quaternion[0];
  13672. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13673. rotationQuaternion.multiplyInPlace(accumulation);
  13674. if (!this.rotationQuaternion) {
  13675. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13676. }
  13677. return this;
  13678. };
  13679. /**
  13680. * Computes the mesh World matrix and returns it.
  13681. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13682. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13683. * If the parameter `force`is set to `true`, the actual computation is done.
  13684. * Returns the mesh World Matrix.
  13685. */
  13686. TransformNode.prototype.computeWorldMatrix = function (force) {
  13687. if (this._isWorldMatrixFrozen) {
  13688. return this._worldMatrix;
  13689. }
  13690. if (!force && this.isSynchronized(true)) {
  13691. return this._worldMatrix;
  13692. }
  13693. this._cache.position.copyFrom(this.position);
  13694. this._cache.scaling.copyFrom(this.scaling);
  13695. this._cache.pivotMatrixUpdated = false;
  13696. this._cache.billboardMode = this.billboardMode;
  13697. this._currentRenderId = this.getScene().getRenderId();
  13698. this._isDirty = false;
  13699. // Scaling
  13700. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13701. // Rotation
  13702. //rotate, if quaternion is set and rotation was used
  13703. if (this.rotationQuaternion) {
  13704. var len = this.rotation.length();
  13705. if (len) {
  13706. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13707. this.rotation.copyFromFloats(0, 0, 0);
  13708. }
  13709. }
  13710. if (this.rotationQuaternion) {
  13711. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13712. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13713. }
  13714. else {
  13715. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13716. this._cache.rotation.copyFrom(this.rotation);
  13717. }
  13718. // Translation
  13719. var camera = this.getScene().activeCamera;
  13720. if (this.infiniteDistance && !this.parent && camera) {
  13721. var cameraWorldMatrix = camera.getWorldMatrix();
  13722. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13723. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13724. }
  13725. else {
  13726. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13727. }
  13728. // Composing transformations
  13729. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13730. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13731. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13732. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13733. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13734. // Need to decompose each rotation here
  13735. var currentPosition = BABYLON.Tmp.Vector3[3];
  13736. if (this.parent && this.parent.getWorldMatrix) {
  13737. if (this._transformToBoneReferal) {
  13738. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13739. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13740. }
  13741. else {
  13742. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13743. }
  13744. }
  13745. else {
  13746. currentPosition.copyFrom(this.position);
  13747. }
  13748. currentPosition.subtractInPlace(camera.globalPosition);
  13749. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13750. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13751. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13752. }
  13753. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13754. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13755. }
  13756. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13757. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13758. }
  13759. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13760. }
  13761. else {
  13762. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13763. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13764. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13765. }
  13766. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13767. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13768. }
  13769. // Local world
  13770. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13771. // Parent
  13772. if (this.parent && this.parent.getWorldMatrix) {
  13773. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13774. if (this._transformToBoneReferal) {
  13775. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13776. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13777. }
  13778. else {
  13779. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13780. }
  13781. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13782. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13783. this._worldMatrix.copyFrom(this._localWorld);
  13784. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13785. }
  13786. else {
  13787. if (this._transformToBoneReferal) {
  13788. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13789. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13790. }
  13791. else {
  13792. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13793. }
  13794. }
  13795. this._markSyncedWithParent();
  13796. }
  13797. else {
  13798. this._worldMatrix.copyFrom(this._localWorld);
  13799. }
  13800. // Post multiply inverse of pivotMatrix
  13801. if (this._postMultiplyPivotMatrix) {
  13802. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13803. }
  13804. // Normal matrix
  13805. if (this.scaling.isNonUniform) {
  13806. this._updateNonUniformScalingState(true);
  13807. }
  13808. else if (this.parent && this.parent._nonUniformScaling) {
  13809. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13810. }
  13811. else {
  13812. this._updateNonUniformScalingState(false);
  13813. }
  13814. this._afterComputeWorldMatrix();
  13815. // Absolute position
  13816. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13817. // Callbacks
  13818. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13819. if (!this._poseMatrix) {
  13820. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13821. }
  13822. return this._worldMatrix;
  13823. };
  13824. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13825. };
  13826. /**
  13827. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13828. * @param func: callback function to add
  13829. *
  13830. * Returns the TransformNode.
  13831. */
  13832. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13833. this.onAfterWorldMatrixUpdateObservable.add(func);
  13834. return this;
  13835. };
  13836. /**
  13837. * Removes a registered callback function.
  13838. * Returns the TransformNode.
  13839. */
  13840. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13841. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13842. return this;
  13843. };
  13844. /**
  13845. * Clone the current transform node
  13846. * Returns the new transform node
  13847. * @param name Name of the new clone
  13848. * @param newParent New parent for the clone
  13849. * @param doNotCloneChildren Do not clone children hierarchy
  13850. */
  13851. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13852. var _this = this;
  13853. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13854. result.name = name;
  13855. result.id = name;
  13856. if (newParent) {
  13857. result.parent = newParent;
  13858. }
  13859. if (!doNotCloneChildren) {
  13860. // Children
  13861. var directDescendants = this.getDescendants(true);
  13862. for (var index = 0; index < directDescendants.length; index++) {
  13863. var child = directDescendants[index];
  13864. if (child.clone) {
  13865. child.clone(name + "." + child.name, result);
  13866. }
  13867. }
  13868. }
  13869. return result;
  13870. };
  13871. TransformNode.prototype.serialize = function (currentSerializationObject) {
  13872. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  13873. serializationObject.type = this.getClassName();
  13874. // Parent
  13875. if (this.parent) {
  13876. serializationObject.parentId = this.parent.id;
  13877. }
  13878. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  13879. serializationObject.tags = BABYLON.Tags.GetTags(this);
  13880. }
  13881. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  13882. serializationObject.isEnabled = this.isEnabled();
  13883. // Parent
  13884. if (this.parent) {
  13885. serializationObject.parentId = this.parent.id;
  13886. }
  13887. return serializationObject;
  13888. };
  13889. // Statics
  13890. /**
  13891. * Returns a new TransformNode object parsed from the source provided.
  13892. * The parameter `parsedMesh` is the source.
  13893. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  13894. */
  13895. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  13896. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  13897. if (BABYLON.Tags) {
  13898. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  13899. }
  13900. if (parsedTransformNode.localMatrix) {
  13901. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  13902. }
  13903. else if (parsedTransformNode.pivotMatrix) {
  13904. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  13905. }
  13906. transformNode.setEnabled(parsedTransformNode.isEnabled);
  13907. // Parent
  13908. if (parsedTransformNode.parentId) {
  13909. transformNode._waitingParentId = parsedTransformNode.parentId;
  13910. }
  13911. return transformNode;
  13912. };
  13913. /**
  13914. * Disposes the TransformNode.
  13915. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13916. * Returns nothing.
  13917. */
  13918. TransformNode.prototype.dispose = function (doNotRecurse) {
  13919. // Animations
  13920. this.getScene().stopAnimation(this);
  13921. // Remove from scene
  13922. this.getScene().removeTransformNode(this);
  13923. this._cache = null;
  13924. if (!doNotRecurse) {
  13925. // Children
  13926. var objects = this.getDescendants(true);
  13927. for (var index = 0; index < objects.length; index++) {
  13928. objects[index].dispose();
  13929. }
  13930. }
  13931. else {
  13932. var childMeshes = this.getChildMeshes(true);
  13933. for (index = 0; index < childMeshes.length; index++) {
  13934. var child = childMeshes[index];
  13935. child.parent = null;
  13936. child.computeWorldMatrix(true);
  13937. }
  13938. }
  13939. this.onAfterWorldMatrixUpdateObservable.clear();
  13940. _super.prototype.dispose.call(this);
  13941. };
  13942. // Statics
  13943. TransformNode.BILLBOARDMODE_NONE = 0;
  13944. TransformNode.BILLBOARDMODE_X = 1;
  13945. TransformNode.BILLBOARDMODE_Y = 2;
  13946. TransformNode.BILLBOARDMODE_Z = 4;
  13947. TransformNode.BILLBOARDMODE_ALL = 7;
  13948. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13949. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  13950. __decorate([
  13951. BABYLON.serializeAsVector3()
  13952. ], TransformNode.prototype, "_rotation", void 0);
  13953. __decorate([
  13954. BABYLON.serializeAsQuaternion()
  13955. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  13956. __decorate([
  13957. BABYLON.serializeAsVector3()
  13958. ], TransformNode.prototype, "_scaling", void 0);
  13959. __decorate([
  13960. BABYLON.serialize()
  13961. ], TransformNode.prototype, "billboardMode", void 0);
  13962. __decorate([
  13963. BABYLON.serialize()
  13964. ], TransformNode.prototype, "scalingDeterminant", void 0);
  13965. __decorate([
  13966. BABYLON.serialize()
  13967. ], TransformNode.prototype, "infiniteDistance", void 0);
  13968. __decorate([
  13969. BABYLON.serializeAsVector3()
  13970. ], TransformNode.prototype, "position", void 0);
  13971. return TransformNode;
  13972. }(BABYLON.Node));
  13973. BABYLON.TransformNode = TransformNode;
  13974. })(BABYLON || (BABYLON = {}));
  13975. //# sourceMappingURL=babylon.transformNode.js.map
  13976. var BABYLON;
  13977. (function (BABYLON) {
  13978. var AbstractMesh = /** @class */ (function (_super) {
  13979. __extends(AbstractMesh, _super);
  13980. // Constructor
  13981. function AbstractMesh(name, scene) {
  13982. if (scene === void 0) { scene = null; }
  13983. var _this = _super.call(this, name, scene, false) || this;
  13984. _this._facetNb = 0; // facet number
  13985. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13986. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13987. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13988. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13989. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13990. _this._subDiv = {
  13991. max: 1,
  13992. X: 1,
  13993. Y: 1,
  13994. Z: 1
  13995. };
  13996. _this._facetDepthSort = false; // is the facet depth sort to be computed
  13997. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  13998. // Events
  13999. /**
  14000. * An event triggered when this mesh collides with another one
  14001. * @type {BABYLON.Observable}
  14002. */
  14003. _this.onCollideObservable = new BABYLON.Observable();
  14004. /**
  14005. * An event triggered when the collision's position changes
  14006. * @type {BABYLON.Observable}
  14007. */
  14008. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14009. /**
  14010. * An event triggered when material is changed
  14011. * @type {BABYLON.Observable}
  14012. */
  14013. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14014. // Properties
  14015. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14016. /**
  14017. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14018. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14019. * or
  14020. * 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.
  14021. * for more info check WebGl documentations
  14022. */
  14023. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14024. /**
  14025. * 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:
  14026. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14027. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14028. * 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.
  14029. */
  14030. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14031. /**
  14032. * 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.
  14033. * The default value is -1 which means don't break the query and wait till the result.
  14034. */
  14035. _this.occlusionRetryCount = -1;
  14036. _this._occlusionInternalRetryCounter = 0;
  14037. _this._isOccluded = false;
  14038. _this._isOcclusionQueryInProgress = false;
  14039. _this.visibility = 1.0;
  14040. _this.alphaIndex = Number.MAX_VALUE;
  14041. _this.isVisible = true;
  14042. _this.isPickable = true;
  14043. _this.showBoundingBox = false;
  14044. _this.showSubMeshesBoundingBox = false;
  14045. _this.isBlocker = false;
  14046. _this.enablePointerMoveEvents = false;
  14047. _this.renderingGroupId = 0;
  14048. _this._receiveShadows = false;
  14049. _this.renderOutline = false;
  14050. _this.outlineColor = BABYLON.Color3.Red();
  14051. _this.outlineWidth = 0.02;
  14052. _this.renderOverlay = false;
  14053. _this.overlayColor = BABYLON.Color3.Red();
  14054. _this.overlayAlpha = 0.5;
  14055. _this._hasVertexAlpha = false;
  14056. _this._useVertexColors = true;
  14057. _this._computeBonesUsingShaders = true;
  14058. _this._numBoneInfluencers = 4;
  14059. _this._applyFog = true;
  14060. _this.useOctreeForRenderingSelection = true;
  14061. _this.useOctreeForPicking = true;
  14062. _this.useOctreeForCollisions = true;
  14063. _this._layerMask = 0x0FFFFFFF;
  14064. /**
  14065. * True if the mesh must be rendered in any case.
  14066. */
  14067. _this.alwaysSelectAsActiveMesh = false;
  14068. // Collisions
  14069. _this._checkCollisions = false;
  14070. _this._collisionMask = -1;
  14071. _this._collisionGroup = -1;
  14072. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14073. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14074. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14075. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14076. // Edges
  14077. _this.edgesWidth = 1;
  14078. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14079. // Cache
  14080. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14081. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14082. _this._isDisposed = false;
  14083. _this._renderId = 0;
  14084. _this._intersectionsInProgress = new Array();
  14085. _this._unIndexed = false;
  14086. _this._lightSources = new Array();
  14087. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14088. if (collidedMesh === void 0) { collidedMesh = null; }
  14089. //TODO move this to the collision coordinator!
  14090. if (_this.getScene().workerCollisions)
  14091. newPosition.multiplyInPlace(_this._collider.radius);
  14092. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14093. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14094. _this.position.addInPlace(_this._diffPositionForCollisions);
  14095. }
  14096. if (collidedMesh) {
  14097. _this.onCollideObservable.notifyObservers(collidedMesh);
  14098. }
  14099. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14100. };
  14101. _this.getScene().addMesh(_this);
  14102. _this._resyncLightSources();
  14103. return _this;
  14104. }
  14105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14106. get: function () {
  14107. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14113. get: function () {
  14114. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14115. },
  14116. enumerable: true,
  14117. configurable: true
  14118. });
  14119. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14120. get: function () {
  14121. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14127. get: function () {
  14128. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14129. },
  14130. enumerable: true,
  14131. configurable: true
  14132. });
  14133. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14134. get: function () {
  14135. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14141. /**
  14142. * Read-only : the number of facets in the mesh
  14143. */
  14144. get: function () {
  14145. return this._facetNb;
  14146. },
  14147. enumerable: true,
  14148. configurable: true
  14149. });
  14150. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14151. /**
  14152. * The number (integer) of subdivisions per axis in the partioning space
  14153. */
  14154. get: function () {
  14155. return this._partitioningSubdivisions;
  14156. },
  14157. set: function (nb) {
  14158. this._partitioningSubdivisions = nb;
  14159. },
  14160. enumerable: true,
  14161. configurable: true
  14162. });
  14163. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14164. /**
  14165. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14166. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14167. */
  14168. get: function () {
  14169. return this._partitioningBBoxRatio;
  14170. },
  14171. set: function (ratio) {
  14172. this._partitioningBBoxRatio = ratio;
  14173. },
  14174. enumerable: true,
  14175. configurable: true
  14176. });
  14177. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14178. /**
  14179. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14180. * Works only for updatable meshes.
  14181. * Doesn't work with multi-materials.
  14182. */
  14183. get: function () {
  14184. return this._facetDepthSort;
  14185. },
  14186. set: function (sort) {
  14187. this._facetDepthSort = sort;
  14188. },
  14189. enumerable: true,
  14190. configurable: true
  14191. });
  14192. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14193. /**
  14194. * The location (Vector3) where the facet depth sort must be computed from.
  14195. * By default, the active camera position.
  14196. * Used only when facet depth sort is enabled.
  14197. */
  14198. get: function () {
  14199. return this._facetDepthSortFrom;
  14200. },
  14201. set: function (location) {
  14202. this._facetDepthSortFrom = location;
  14203. },
  14204. enumerable: true,
  14205. configurable: true
  14206. });
  14207. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14208. /**
  14209. * Read-only boolean : is the feature facetData enabled ?
  14210. */
  14211. get: function () {
  14212. return this._facetDataEnabled;
  14213. },
  14214. enumerable: true,
  14215. configurable: true
  14216. });
  14217. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14218. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14219. return false;
  14220. }
  14221. this._markSubMeshesAsMiscDirty();
  14222. return true;
  14223. };
  14224. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14225. set: function (callback) {
  14226. if (this._onCollideObserver) {
  14227. this.onCollideObservable.remove(this._onCollideObserver);
  14228. }
  14229. this._onCollideObserver = this.onCollideObservable.add(callback);
  14230. },
  14231. enumerable: true,
  14232. configurable: true
  14233. });
  14234. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14235. set: function (callback) {
  14236. if (this._onCollisionPositionChangeObserver) {
  14237. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14238. }
  14239. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14240. },
  14241. enumerable: true,
  14242. configurable: true
  14243. });
  14244. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14245. /**
  14246. * 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.
  14247. */
  14248. get: function () {
  14249. return this._isOccluded;
  14250. },
  14251. set: function (value) {
  14252. this._isOccluded = value;
  14253. },
  14254. enumerable: true,
  14255. configurable: true
  14256. });
  14257. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14258. /**
  14259. * Flag to check the progress status of the query
  14260. */
  14261. get: function () {
  14262. return this._isOcclusionQueryInProgress;
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. Object.defineProperty(AbstractMesh.prototype, "material", {
  14268. get: function () {
  14269. return this._material;
  14270. },
  14271. set: function (value) {
  14272. if (this._material === value) {
  14273. return;
  14274. }
  14275. this._material = value;
  14276. if (this.onMaterialChangedObservable.hasObservers) {
  14277. this.onMaterialChangedObservable.notifyObservers(this);
  14278. }
  14279. if (!this.subMeshes) {
  14280. return;
  14281. }
  14282. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14283. var subMesh = _a[_i];
  14284. subMesh.setEffect(null);
  14285. }
  14286. },
  14287. enumerable: true,
  14288. configurable: true
  14289. });
  14290. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14291. get: function () {
  14292. return this._receiveShadows;
  14293. },
  14294. set: function (value) {
  14295. if (this._receiveShadows === value) {
  14296. return;
  14297. }
  14298. this._receiveShadows = value;
  14299. this._markSubMeshesAsLightDirty();
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14305. get: function () {
  14306. return this._hasVertexAlpha;
  14307. },
  14308. set: function (value) {
  14309. if (this._hasVertexAlpha === value) {
  14310. return;
  14311. }
  14312. this._hasVertexAlpha = value;
  14313. this._markSubMeshesAsAttributesDirty();
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14319. get: function () {
  14320. return this._useVertexColors;
  14321. },
  14322. set: function (value) {
  14323. if (this._useVertexColors === value) {
  14324. return;
  14325. }
  14326. this._useVertexColors = value;
  14327. this._markSubMeshesAsAttributesDirty();
  14328. },
  14329. enumerable: true,
  14330. configurable: true
  14331. });
  14332. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14333. get: function () {
  14334. return this._computeBonesUsingShaders;
  14335. },
  14336. set: function (value) {
  14337. if (this._computeBonesUsingShaders === value) {
  14338. return;
  14339. }
  14340. this._computeBonesUsingShaders = value;
  14341. this._markSubMeshesAsAttributesDirty();
  14342. },
  14343. enumerable: true,
  14344. configurable: true
  14345. });
  14346. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14347. get: function () {
  14348. return this._numBoneInfluencers;
  14349. },
  14350. set: function (value) {
  14351. if (this._numBoneInfluencers === value) {
  14352. return;
  14353. }
  14354. this._numBoneInfluencers = value;
  14355. this._markSubMeshesAsAttributesDirty();
  14356. },
  14357. enumerable: true,
  14358. configurable: true
  14359. });
  14360. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14361. get: function () {
  14362. return this._applyFog;
  14363. },
  14364. set: function (value) {
  14365. if (this._applyFog === value) {
  14366. return;
  14367. }
  14368. this._applyFog = value;
  14369. this._markSubMeshesAsMiscDirty();
  14370. },
  14371. enumerable: true,
  14372. configurable: true
  14373. });
  14374. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14375. get: function () {
  14376. return this._layerMask;
  14377. },
  14378. set: function (value) {
  14379. if (value === this._layerMask) {
  14380. return;
  14381. }
  14382. this._layerMask = value;
  14383. this._resyncLightSources();
  14384. },
  14385. enumerable: true,
  14386. configurable: true
  14387. });
  14388. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14389. get: function () {
  14390. return this._collisionMask;
  14391. },
  14392. set: function (mask) {
  14393. this._collisionMask = !isNaN(mask) ? mask : -1;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14399. get: function () {
  14400. return this._collisionGroup;
  14401. },
  14402. set: function (mask) {
  14403. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14409. get: function () {
  14410. return null;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14416. get: function () {
  14417. return this._skeleton;
  14418. },
  14419. set: function (value) {
  14420. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14421. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14422. }
  14423. if (value && value.needInitialSkinMatrix) {
  14424. value._registerMeshWithPoseMatrix(this);
  14425. }
  14426. this._skeleton = value;
  14427. if (!this._skeleton) {
  14428. this._bonesTransformMatrices = null;
  14429. }
  14430. this._markSubMeshesAsAttributesDirty();
  14431. },
  14432. enumerable: true,
  14433. configurable: true
  14434. });
  14435. /**
  14436. * Boolean : true if the mesh has been disposed.
  14437. */
  14438. AbstractMesh.prototype.isDisposed = function () {
  14439. return this._isDisposed;
  14440. };
  14441. /**
  14442. * Returns the string "AbstractMesh"
  14443. */
  14444. AbstractMesh.prototype.getClassName = function () {
  14445. return "AbstractMesh";
  14446. };
  14447. /**
  14448. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14449. */
  14450. AbstractMesh.prototype.toString = function (fullDetails) {
  14451. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14452. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14453. if (this._skeleton) {
  14454. ret += ", skeleton: " + this._skeleton.name;
  14455. }
  14456. if (fullDetails) {
  14457. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14458. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14459. }
  14460. return ret;
  14461. };
  14462. AbstractMesh.prototype._rebuild = function () {
  14463. if (this._occlusionQuery) {
  14464. this._occlusionQuery = null;
  14465. }
  14466. if (this._edgesRenderer) {
  14467. this._edgesRenderer._rebuild();
  14468. }
  14469. if (!this.subMeshes) {
  14470. return;
  14471. }
  14472. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14473. var subMesh = _a[_i];
  14474. subMesh._rebuild();
  14475. }
  14476. };
  14477. AbstractMesh.prototype._resyncLightSources = function () {
  14478. this._lightSources.length = 0;
  14479. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14480. var light = _a[_i];
  14481. if (!light.isEnabled()) {
  14482. continue;
  14483. }
  14484. if (light.canAffectMesh(this)) {
  14485. this._lightSources.push(light);
  14486. }
  14487. }
  14488. this._markSubMeshesAsLightDirty();
  14489. };
  14490. AbstractMesh.prototype._resyncLighSource = function (light) {
  14491. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14492. var index = this._lightSources.indexOf(light);
  14493. if (index === -1) {
  14494. if (!isIn) {
  14495. return;
  14496. }
  14497. this._lightSources.push(light);
  14498. }
  14499. else {
  14500. if (isIn) {
  14501. return;
  14502. }
  14503. this._lightSources.splice(index, 1);
  14504. }
  14505. this._markSubMeshesAsLightDirty();
  14506. };
  14507. AbstractMesh.prototype._removeLightSource = function (light) {
  14508. var index = this._lightSources.indexOf(light);
  14509. if (index === -1) {
  14510. return;
  14511. }
  14512. this._lightSources.splice(index, 1);
  14513. };
  14514. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14515. if (!this.subMeshes) {
  14516. return;
  14517. }
  14518. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14519. var subMesh = _a[_i];
  14520. if (subMesh._materialDefines) {
  14521. func(subMesh._materialDefines);
  14522. }
  14523. }
  14524. };
  14525. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14526. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14527. };
  14528. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14529. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14530. };
  14531. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14532. if (!this.subMeshes) {
  14533. return;
  14534. }
  14535. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14536. var subMesh = _a[_i];
  14537. var material = subMesh.getMaterial();
  14538. if (material) {
  14539. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14540. }
  14541. }
  14542. };
  14543. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14544. /**
  14545. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14546. * Default : (1.0, 1.0, 1.0)
  14547. */
  14548. get: function () {
  14549. return this._scaling;
  14550. },
  14551. /**
  14552. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14553. * Default : (1.0, 1.0, 1.0)
  14554. */
  14555. set: function (newScaling) {
  14556. this._scaling = newScaling;
  14557. if (this.physicsImpostor) {
  14558. this.physicsImpostor.forceUpdate();
  14559. }
  14560. },
  14561. enumerable: true,
  14562. configurable: true
  14563. });
  14564. // Methods
  14565. /**
  14566. * Disables the mesh edger rendering mode.
  14567. * Returns the AbstractMesh.
  14568. */
  14569. AbstractMesh.prototype.disableEdgesRendering = function () {
  14570. if (this._edgesRenderer) {
  14571. this._edgesRenderer.dispose();
  14572. this._edgesRenderer = null;
  14573. }
  14574. return this;
  14575. };
  14576. /**
  14577. * Enables the edge rendering mode on the mesh.
  14578. * This mode makes the mesh edges visible.
  14579. * Returns the AbstractMesh.
  14580. */
  14581. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14582. if (epsilon === void 0) { epsilon = 0.95; }
  14583. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14584. this.disableEdgesRendering();
  14585. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14586. return this;
  14587. };
  14588. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14589. /**
  14590. * Returns true if the mesh is blocked. Used by the class Mesh.
  14591. * Returns the boolean `false` by default.
  14592. */
  14593. get: function () {
  14594. return false;
  14595. },
  14596. enumerable: true,
  14597. configurable: true
  14598. });
  14599. /**
  14600. * Returns the mesh itself by default, used by the class Mesh.
  14601. * Returned type : AbstractMesh
  14602. */
  14603. AbstractMesh.prototype.getLOD = function (camera) {
  14604. return this;
  14605. };
  14606. /**
  14607. * Returns 0 by default, used by the class Mesh.
  14608. * Returns an integer.
  14609. */
  14610. AbstractMesh.prototype.getTotalVertices = function () {
  14611. return 0;
  14612. };
  14613. /**
  14614. * Returns null by default, used by the class Mesh.
  14615. * Returned type : integer array
  14616. */
  14617. AbstractMesh.prototype.getIndices = function () {
  14618. return null;
  14619. };
  14620. /**
  14621. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14622. * Returned type : float array or Float32Array
  14623. */
  14624. AbstractMesh.prototype.getVerticesData = function (kind) {
  14625. return null;
  14626. };
  14627. /**
  14628. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14629. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14630. * The `data` are either a numeric array either a Float32Array.
  14631. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14632. * 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).
  14633. * Note that a new underlying VertexBuffer object is created each call.
  14634. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14635. *
  14636. * Possible `kind` values :
  14637. * - BABYLON.VertexBuffer.PositionKind
  14638. * - BABYLON.VertexBuffer.UVKind
  14639. * - BABYLON.VertexBuffer.UV2Kind
  14640. * - BABYLON.VertexBuffer.UV3Kind
  14641. * - BABYLON.VertexBuffer.UV4Kind
  14642. * - BABYLON.VertexBuffer.UV5Kind
  14643. * - BABYLON.VertexBuffer.UV6Kind
  14644. * - BABYLON.VertexBuffer.ColorKind
  14645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14649. *
  14650. * Returns the Mesh.
  14651. */
  14652. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14653. return this;
  14654. };
  14655. /**
  14656. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14657. * If the mesh has no geometry, it is simply returned as it is.
  14658. * The `data` are either a numeric array either a Float32Array.
  14659. * No new underlying VertexBuffer object is created.
  14660. * 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.
  14661. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14662. *
  14663. * Possible `kind` values :
  14664. * - BABYLON.VertexBuffer.PositionKind
  14665. * - BABYLON.VertexBuffer.UVKind
  14666. * - BABYLON.VertexBuffer.UV2Kind
  14667. * - BABYLON.VertexBuffer.UV3Kind
  14668. * - BABYLON.VertexBuffer.UV4Kind
  14669. * - BABYLON.VertexBuffer.UV5Kind
  14670. * - BABYLON.VertexBuffer.UV6Kind
  14671. * - BABYLON.VertexBuffer.ColorKind
  14672. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14673. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14674. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14675. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14676. *
  14677. * Returns the Mesh.
  14678. */
  14679. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14680. return this;
  14681. };
  14682. /**
  14683. * Sets the mesh indices.
  14684. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14685. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14686. * This method creates a new index buffer each call.
  14687. * Returns the Mesh.
  14688. */
  14689. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14690. return this;
  14691. };
  14692. /** Returns false by default, used by the class Mesh.
  14693. * Returns a boolean
  14694. */
  14695. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14696. return false;
  14697. };
  14698. /**
  14699. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14700. * Returns a BoundingInfo
  14701. */
  14702. AbstractMesh.prototype.getBoundingInfo = function () {
  14703. if (this._masterMesh) {
  14704. return this._masterMesh.getBoundingInfo();
  14705. }
  14706. if (!this._boundingInfo) {
  14707. // this._boundingInfo is being created here
  14708. this._updateBoundingInfo();
  14709. }
  14710. // cannot be null.
  14711. return this._boundingInfo;
  14712. };
  14713. /**
  14714. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14715. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14716. */
  14717. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14718. if (includeDescendants === void 0) { includeDescendants = true; }
  14719. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14720. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14721. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14722. if (maxDimension === 0) {
  14723. return this;
  14724. }
  14725. var scale = 1 / maxDimension;
  14726. this.scaling.scaleInPlace(scale);
  14727. return this;
  14728. };
  14729. /**
  14730. * Sets a mesh new object BoundingInfo.
  14731. * Returns the AbstractMesh.
  14732. */
  14733. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14734. this._boundingInfo = boundingInfo;
  14735. return this;
  14736. };
  14737. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14738. get: function () {
  14739. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14740. },
  14741. enumerable: true,
  14742. configurable: true
  14743. });
  14744. AbstractMesh.prototype._preActivate = function () {
  14745. };
  14746. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14747. };
  14748. AbstractMesh.prototype._activate = function (renderId) {
  14749. this._renderId = renderId;
  14750. };
  14751. /**
  14752. * Returns the latest update of the World matrix
  14753. * Returns a Matrix.
  14754. */
  14755. AbstractMesh.prototype.getWorldMatrix = function () {
  14756. if (this._masterMesh) {
  14757. return this._masterMesh.getWorldMatrix();
  14758. }
  14759. return _super.prototype.getWorldMatrix.call(this);
  14760. };
  14761. // ================================== Point of View Movement =================================
  14762. /**
  14763. * Perform relative position change from the point of view of behind the front of the mesh.
  14764. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14765. * Supports definition of mesh facing forward or backward.
  14766. * @param {number} amountRight
  14767. * @param {number} amountUp
  14768. * @param {number} amountForward
  14769. *
  14770. * Returns the AbstractMesh.
  14771. */
  14772. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14773. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14774. return this;
  14775. };
  14776. /**
  14777. * Calculate relative position change from the point of view of behind the front of the mesh.
  14778. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14779. * Supports definition of mesh facing forward or backward.
  14780. * @param {number} amountRight
  14781. * @param {number} amountUp
  14782. * @param {number} amountForward
  14783. *
  14784. * Returns a new Vector3.
  14785. */
  14786. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14787. var rotMatrix = new BABYLON.Matrix();
  14788. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14789. rotQuaternion.toRotationMatrix(rotMatrix);
  14790. var translationDelta = BABYLON.Vector3.Zero();
  14791. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14792. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14793. return translationDelta;
  14794. };
  14795. // ================================== Point of View Rotation =================================
  14796. /**
  14797. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14798. * Supports definition of mesh facing forward or backward.
  14799. * @param {number} flipBack
  14800. * @param {number} twirlClockwise
  14801. * @param {number} tiltRight
  14802. *
  14803. * Returns the AbstractMesh.
  14804. */
  14805. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14806. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14807. return this;
  14808. };
  14809. /**
  14810. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14811. * Supports definition of mesh facing forward or backward.
  14812. * @param {number} flipBack
  14813. * @param {number} twirlClockwise
  14814. * @param {number} tiltRight
  14815. *
  14816. * Returns a new Vector3.
  14817. */
  14818. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14819. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14820. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14821. };
  14822. /**
  14823. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14824. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14825. */
  14826. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14827. if (includeDescendants === void 0) { includeDescendants = true; }
  14828. this.computeWorldMatrix(true);
  14829. var min;
  14830. var max;
  14831. var boundingInfo = this.getBoundingInfo();
  14832. if (!this.subMeshes) {
  14833. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14834. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14835. }
  14836. else {
  14837. min = boundingInfo.boundingBox.minimumWorld;
  14838. max = boundingInfo.boundingBox.maximumWorld;
  14839. }
  14840. if (includeDescendants) {
  14841. var descendants = this.getDescendants(false);
  14842. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14843. var descendant = descendants_1[_i];
  14844. var childMesh = descendant;
  14845. childMesh.computeWorldMatrix(true);
  14846. var childBoundingInfo = childMesh.getBoundingInfo();
  14847. if (childMesh.getTotalVertices() === 0) {
  14848. continue;
  14849. }
  14850. var boundingBox = childBoundingInfo.boundingBox;
  14851. var minBox = boundingBox.minimumWorld;
  14852. var maxBox = boundingBox.maximumWorld;
  14853. BABYLON.Tools.CheckExtends(minBox, min, max);
  14854. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14855. }
  14856. }
  14857. return {
  14858. min: min,
  14859. max: max
  14860. };
  14861. };
  14862. /**
  14863. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14864. * Returns the AbstractMesh.
  14865. */
  14866. AbstractMesh.prototype._updateBoundingInfo = function () {
  14867. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14868. this._boundingInfo.update(this.worldMatrixFromCache);
  14869. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14870. return this;
  14871. };
  14872. /**
  14873. * Update a mesh's children BoundingInfo objects only.
  14874. * Returns the AbstractMesh.
  14875. */
  14876. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14877. if (!this.subMeshes) {
  14878. return this;
  14879. }
  14880. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14881. var subMesh = this.subMeshes[subIndex];
  14882. if (!subMesh.IsGlobal) {
  14883. subMesh.updateBoundingInfo(matrix);
  14884. }
  14885. }
  14886. return this;
  14887. };
  14888. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  14889. // Bounding info
  14890. this._updateBoundingInfo();
  14891. };
  14892. /**
  14893. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14894. * A mesh is in the frustum if its bounding box intersects the frustum.
  14895. * Boolean returned.
  14896. */
  14897. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14898. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14899. };
  14900. /**
  14901. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14902. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14903. * Boolean returned.
  14904. */
  14905. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14906. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14907. ;
  14908. };
  14909. /**
  14910. * True if the mesh intersects another mesh or a SolidParticle object.
  14911. * 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)
  14912. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14913. * Returns a boolean.
  14914. */
  14915. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14916. if (precise === void 0) { precise = false; }
  14917. if (!this._boundingInfo || !mesh._boundingInfo) {
  14918. return false;
  14919. }
  14920. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14921. return true;
  14922. }
  14923. if (includeDescendants) {
  14924. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14925. var child = _a[_i];
  14926. if (child.intersectsMesh(mesh, precise, true)) {
  14927. return true;
  14928. }
  14929. }
  14930. }
  14931. return false;
  14932. };
  14933. /**
  14934. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14935. * Returns a boolean.
  14936. */
  14937. AbstractMesh.prototype.intersectsPoint = function (point) {
  14938. if (!this._boundingInfo) {
  14939. return false;
  14940. }
  14941. return this._boundingInfo.intersectsPoint(point);
  14942. };
  14943. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14944. return this.physicsImpostor;
  14945. };
  14946. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14947. if (camera === void 0) { camera = null; }
  14948. if (!camera) {
  14949. camera = this.getScene().activeCamera;
  14950. }
  14951. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14952. };
  14953. /**
  14954. * Returns the distance from the mesh to the active camera.
  14955. * Returns a float.
  14956. */
  14957. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14958. if (camera === void 0) { camera = null; }
  14959. if (!camera) {
  14960. camera = this.getScene().activeCamera;
  14961. }
  14962. return this.absolutePosition.subtract(camera.position).length();
  14963. };
  14964. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14965. if (!this.physicsImpostor) {
  14966. return this;
  14967. }
  14968. this.physicsImpostor.applyImpulse(force, contactPoint);
  14969. return this;
  14970. };
  14971. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14972. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14973. return this;
  14974. }
  14975. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14976. mainPivot: pivot1,
  14977. connectedPivot: pivot2,
  14978. nativeParams: options
  14979. });
  14980. return this;
  14981. };
  14982. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14983. // Collisions
  14984. /**
  14985. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14986. * Default `false`.
  14987. */
  14988. get: function () {
  14989. return this._checkCollisions;
  14990. },
  14991. set: function (collisionEnabled) {
  14992. this._checkCollisions = collisionEnabled;
  14993. if (this.getScene().workerCollisions) {
  14994. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14995. }
  14996. },
  14997. enumerable: true,
  14998. configurable: true
  14999. });
  15000. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15001. var globalPosition = this.getAbsolutePosition();
  15002. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  15003. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  15004. if (!this._collider) {
  15005. this._collider = new BABYLON.Collider();
  15006. }
  15007. this._collider.radius = this.ellipsoid;
  15008. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15009. return this;
  15010. };
  15011. // Submeshes octree
  15012. /**
  15013. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15014. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15015. * Returns an Octree of submeshes.
  15016. */
  15017. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15018. if (maxCapacity === void 0) { maxCapacity = 64; }
  15019. if (maxDepth === void 0) { maxDepth = 2; }
  15020. if (!this._submeshesOctree) {
  15021. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15022. }
  15023. this.computeWorldMatrix(true);
  15024. var boundingInfo = this.getBoundingInfo();
  15025. // Update octree
  15026. var bbox = boundingInfo.boundingBox;
  15027. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15028. return this._submeshesOctree;
  15029. };
  15030. // Collisions
  15031. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15032. this._generatePointsArray();
  15033. if (!this._positions) {
  15034. return this;
  15035. }
  15036. // Transformation
  15037. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15038. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15039. subMesh._lastColliderWorldVertices = [];
  15040. subMesh._trianglePlanes = [];
  15041. var start = subMesh.verticesStart;
  15042. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15043. for (var i = start; i < end; i++) {
  15044. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15045. }
  15046. }
  15047. // Collide
  15048. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15049. if (collider.collisionFound) {
  15050. collider.collidedMesh = this;
  15051. }
  15052. return this;
  15053. };
  15054. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15055. var subMeshes;
  15056. var len;
  15057. // Octrees
  15058. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15059. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  15060. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  15061. len = intersections.length;
  15062. subMeshes = intersections.data;
  15063. }
  15064. else {
  15065. subMeshes = this.subMeshes;
  15066. len = subMeshes.length;
  15067. }
  15068. for (var index = 0; index < len; index++) {
  15069. var subMesh = subMeshes[index];
  15070. // Bounding test
  15071. if (len > 1 && !subMesh._checkCollision(collider))
  15072. continue;
  15073. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15074. }
  15075. return this;
  15076. };
  15077. AbstractMesh.prototype._checkCollision = function (collider) {
  15078. // Bounding box test
  15079. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15080. return this;
  15081. // Transformation matrix
  15082. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  15083. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15084. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15085. return this;
  15086. };
  15087. // Picking
  15088. AbstractMesh.prototype._generatePointsArray = function () {
  15089. return false;
  15090. };
  15091. /**
  15092. * Checks if the passed Ray intersects with the mesh.
  15093. * Returns an object PickingInfo.
  15094. */
  15095. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15096. var pickingInfo = new BABYLON.PickingInfo();
  15097. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15098. return pickingInfo;
  15099. }
  15100. if (!this._generatePointsArray()) {
  15101. return pickingInfo;
  15102. }
  15103. var intersectInfo = null;
  15104. // Octrees
  15105. var subMeshes;
  15106. var len;
  15107. if (this._submeshesOctree && this.useOctreeForPicking) {
  15108. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15109. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15110. len = intersections.length;
  15111. subMeshes = intersections.data;
  15112. }
  15113. else {
  15114. subMeshes = this.subMeshes;
  15115. len = subMeshes.length;
  15116. }
  15117. for (var index = 0; index < len; index++) {
  15118. var subMesh = subMeshes[index];
  15119. // Bounding test
  15120. if (len > 1 && !subMesh.canIntersects(ray))
  15121. continue;
  15122. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15123. if (currentIntersectInfo) {
  15124. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15125. intersectInfo = currentIntersectInfo;
  15126. intersectInfo.subMeshId = index;
  15127. if (fastCheck) {
  15128. break;
  15129. }
  15130. }
  15131. }
  15132. }
  15133. if (intersectInfo) {
  15134. // Get picked point
  15135. var world = this.getWorldMatrix();
  15136. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15137. var direction = ray.direction.clone();
  15138. direction = direction.scale(intersectInfo.distance);
  15139. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15140. var pickedPoint = worldOrigin.add(worldDirection);
  15141. // Return result
  15142. pickingInfo.hit = true;
  15143. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15144. pickingInfo.pickedPoint = pickedPoint;
  15145. pickingInfo.pickedMesh = this;
  15146. pickingInfo.bu = intersectInfo.bu || 0;
  15147. pickingInfo.bv = intersectInfo.bv || 0;
  15148. pickingInfo.faceId = intersectInfo.faceId;
  15149. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15150. return pickingInfo;
  15151. }
  15152. return pickingInfo;
  15153. };
  15154. /**
  15155. * Clones the mesh, used by the class Mesh.
  15156. * Just returns `null` for an AbstractMesh.
  15157. */
  15158. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15159. return null;
  15160. };
  15161. /**
  15162. * Disposes all the mesh submeshes.
  15163. * Returns the AbstractMesh.
  15164. */
  15165. AbstractMesh.prototype.releaseSubMeshes = function () {
  15166. if (this.subMeshes) {
  15167. while (this.subMeshes.length) {
  15168. this.subMeshes[0].dispose();
  15169. }
  15170. }
  15171. else {
  15172. this.subMeshes = new Array();
  15173. }
  15174. return this;
  15175. };
  15176. /**
  15177. * Disposes the AbstractMesh.
  15178. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15179. * Returns nothing.
  15180. */
  15181. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15182. var _this = this;
  15183. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15184. var index;
  15185. // Action manager
  15186. if (this.actionManager) {
  15187. this.actionManager.dispose();
  15188. this.actionManager = null;
  15189. }
  15190. // Skeleton
  15191. this.skeleton = null;
  15192. // Physics
  15193. if (this.physicsImpostor) {
  15194. this.physicsImpostor.dispose();
  15195. }
  15196. // Intersections in progress
  15197. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15198. var other = this._intersectionsInProgress[index];
  15199. var pos = other._intersectionsInProgress.indexOf(this);
  15200. other._intersectionsInProgress.splice(pos, 1);
  15201. }
  15202. this._intersectionsInProgress = [];
  15203. // Lights
  15204. var lights = this.getScene().lights;
  15205. lights.forEach(function (light) {
  15206. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15207. if (meshIndex !== -1) {
  15208. light.includedOnlyMeshes.splice(meshIndex, 1);
  15209. }
  15210. meshIndex = light.excludedMeshes.indexOf(_this);
  15211. if (meshIndex !== -1) {
  15212. light.excludedMeshes.splice(meshIndex, 1);
  15213. }
  15214. // Shadow generators
  15215. var generator = light.getShadowGenerator();
  15216. if (generator) {
  15217. var shadowMap = generator.getShadowMap();
  15218. if (shadowMap && shadowMap.renderList) {
  15219. meshIndex = shadowMap.renderList.indexOf(_this);
  15220. if (meshIndex !== -1) {
  15221. shadowMap.renderList.splice(meshIndex, 1);
  15222. }
  15223. }
  15224. }
  15225. });
  15226. // Edges
  15227. if (this._edgesRenderer) {
  15228. this._edgesRenderer.dispose();
  15229. this._edgesRenderer = null;
  15230. }
  15231. // SubMeshes
  15232. if (this.getClassName() !== "InstancedMesh") {
  15233. this.releaseSubMeshes();
  15234. }
  15235. // Octree
  15236. var sceneOctree = this.getScene().selectionOctree;
  15237. if (sceneOctree) {
  15238. var index = sceneOctree.dynamicContent.indexOf(this);
  15239. if (index !== -1) {
  15240. sceneOctree.dynamicContent.splice(index, 1);
  15241. }
  15242. }
  15243. // Query
  15244. var engine = this.getScene().getEngine();
  15245. if (this._occlusionQuery) {
  15246. this._isOcclusionQueryInProgress = false;
  15247. engine.deleteQuery(this._occlusionQuery);
  15248. this._occlusionQuery = null;
  15249. }
  15250. // Engine
  15251. engine.wipeCaches();
  15252. // Remove from scene
  15253. this.getScene().removeMesh(this);
  15254. if (disposeMaterialAndTextures) {
  15255. if (this.material) {
  15256. this.material.dispose(false, true);
  15257. }
  15258. }
  15259. if (!doNotRecurse) {
  15260. // Particles
  15261. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15262. if (this.getScene().particleSystems[index].emitter === this) {
  15263. this.getScene().particleSystems[index].dispose();
  15264. index--;
  15265. }
  15266. }
  15267. }
  15268. // facet data
  15269. if (this._facetDataEnabled) {
  15270. this.disableFacetData();
  15271. }
  15272. this.onAfterWorldMatrixUpdateObservable.clear();
  15273. this.onCollideObservable.clear();
  15274. this.onCollisionPositionChangeObservable.clear();
  15275. this._isDisposed = true;
  15276. _super.prototype.dispose.call(this, doNotRecurse);
  15277. };
  15278. /**
  15279. * Adds the passed mesh as a child to the current mesh.
  15280. * Returns the AbstractMesh.
  15281. */
  15282. AbstractMesh.prototype.addChild = function (mesh) {
  15283. mesh.setParent(this);
  15284. return this;
  15285. };
  15286. /**
  15287. * Removes the passed mesh from the current mesh children list.
  15288. * Returns the AbstractMesh.
  15289. */
  15290. AbstractMesh.prototype.removeChild = function (mesh) {
  15291. mesh.setParent(null);
  15292. return this;
  15293. };
  15294. // Facet data
  15295. /**
  15296. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15297. * Returns the AbstractMesh.
  15298. */
  15299. AbstractMesh.prototype._initFacetData = function () {
  15300. if (!this._facetNormals) {
  15301. this._facetNormals = new Array();
  15302. }
  15303. if (!this._facetPositions) {
  15304. this._facetPositions = new Array();
  15305. }
  15306. if (!this._facetPartitioning) {
  15307. this._facetPartitioning = new Array();
  15308. }
  15309. this._facetNb = (this.getIndices().length / 3) | 0;
  15310. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15311. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15312. for (var f = 0; f < this._facetNb; f++) {
  15313. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15314. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15315. }
  15316. this._facetDataEnabled = true;
  15317. return this;
  15318. };
  15319. /**
  15320. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15321. * This method can be called within the render loop.
  15322. * 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.
  15323. * Returns the AbstractMesh.
  15324. */
  15325. AbstractMesh.prototype.updateFacetData = function () {
  15326. if (!this._facetDataEnabled) {
  15327. this._initFacetData();
  15328. }
  15329. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15330. var indices = this.getIndices();
  15331. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15332. var bInfo = this.getBoundingInfo();
  15333. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15334. // init arrays, matrix and sort function on first call
  15335. this._facetDepthSortEnabled = true;
  15336. if (indices instanceof Uint16Array) {
  15337. this._depthSortedIndices = new Uint16Array(indices);
  15338. }
  15339. else if (indices instanceof Uint32Array) {
  15340. this._depthSortedIndices = new Uint32Array(indices);
  15341. }
  15342. else {
  15343. var needs32bits = false;
  15344. for (var i = 0; i < indices.length; i++) {
  15345. if (indices[i] > 65535) {
  15346. needs32bits = true;
  15347. break;
  15348. }
  15349. }
  15350. if (needs32bits) {
  15351. this._depthSortedIndices = new Uint32Array(indices);
  15352. }
  15353. else {
  15354. this._depthSortedIndices = new Uint16Array(indices);
  15355. }
  15356. }
  15357. this._facetDepthSortFunction = function (f1, f2) {
  15358. return (f2.sqDistance - f1.sqDistance);
  15359. };
  15360. if (!this._facetDepthSortFrom) {
  15361. var camera = this.getScene().activeCamera;
  15362. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15363. }
  15364. this._depthSortedFacets = [];
  15365. for (var f = 0; f < this._facetNb; f++) {
  15366. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15367. this._depthSortedFacets.push(depthSortedFacet);
  15368. }
  15369. this._invertedMatrix = BABYLON.Matrix.Identity();
  15370. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15371. }
  15372. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15373. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15374. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15375. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15376. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15377. this._subDiv.max = this._partitioningSubdivisions;
  15378. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15379. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15380. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15381. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15382. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15383. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15384. // set the parameters for ComputeNormals()
  15385. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15386. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15387. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15388. this._facetParameters.bInfo = bInfo;
  15389. this._facetParameters.bbSize = this._bbSize;
  15390. this._facetParameters.subDiv = this._subDiv;
  15391. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15392. this._facetParameters.depthSort = this._facetDepthSort;
  15393. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15394. this.computeWorldMatrix(true);
  15395. this._worldMatrix.invertToRef(this._invertedMatrix);
  15396. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15397. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15398. }
  15399. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15400. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15401. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15402. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15403. var l = (this._depthSortedIndices.length / 3) | 0;
  15404. for (var f = 0; f < l; f++) {
  15405. var sind = this._depthSortedFacets[f].ind;
  15406. this._depthSortedIndices[f * 3] = indices[sind];
  15407. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15408. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15409. }
  15410. this.updateIndices(this._depthSortedIndices);
  15411. }
  15412. return this;
  15413. };
  15414. /**
  15415. * Returns the facetLocalNormals array.
  15416. * The normals are expressed in the mesh local space.
  15417. */
  15418. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15419. if (!this._facetNormals) {
  15420. this.updateFacetData();
  15421. }
  15422. return this._facetNormals;
  15423. };
  15424. /**
  15425. * Returns the facetLocalPositions array.
  15426. * The facet positions are expressed in the mesh local space.
  15427. */
  15428. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15429. if (!this._facetPositions) {
  15430. this.updateFacetData();
  15431. }
  15432. return this._facetPositions;
  15433. };
  15434. /**
  15435. * Returns the facetLocalPartioning array.
  15436. */
  15437. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15438. if (!this._facetPartitioning) {
  15439. this.updateFacetData();
  15440. }
  15441. return this._facetPartitioning;
  15442. };
  15443. /**
  15444. * Returns the i-th facet position in the world system.
  15445. * This method allocates a new Vector3 per call.
  15446. */
  15447. AbstractMesh.prototype.getFacetPosition = function (i) {
  15448. var pos = BABYLON.Vector3.Zero();
  15449. this.getFacetPositionToRef(i, pos);
  15450. return pos;
  15451. };
  15452. /**
  15453. * Sets the reference Vector3 with the i-th facet position in the world system.
  15454. * Returns the AbstractMesh.
  15455. */
  15456. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15457. var localPos = (this.getFacetLocalPositions())[i];
  15458. var world = this.getWorldMatrix();
  15459. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15460. return this;
  15461. };
  15462. /**
  15463. * Returns the i-th facet normal in the world system.
  15464. * This method allocates a new Vector3 per call.
  15465. */
  15466. AbstractMesh.prototype.getFacetNormal = function (i) {
  15467. var norm = BABYLON.Vector3.Zero();
  15468. this.getFacetNormalToRef(i, norm);
  15469. return norm;
  15470. };
  15471. /**
  15472. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15473. * Returns the AbstractMesh.
  15474. */
  15475. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15476. var localNorm = (this.getFacetLocalNormals())[i];
  15477. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15478. return this;
  15479. };
  15480. /**
  15481. * 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).
  15482. */
  15483. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15484. var bInfo = this.getBoundingInfo();
  15485. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15486. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15487. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15488. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15489. return null;
  15490. }
  15491. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15492. };
  15493. /**
  15494. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15495. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15496. * 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.
  15497. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15498. * 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.
  15499. */
  15500. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15501. if (checkFace === void 0) { checkFace = false; }
  15502. if (facing === void 0) { facing = true; }
  15503. var world = this.getWorldMatrix();
  15504. var invMat = BABYLON.Tmp.Matrix[5];
  15505. world.invertToRef(invMat);
  15506. var invVect = BABYLON.Tmp.Vector3[8];
  15507. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15508. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15509. if (projected) {
  15510. // tranform the local computed projected vector to world coordinates
  15511. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15512. }
  15513. return closest;
  15514. };
  15515. /**
  15516. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15517. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15518. * 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.
  15519. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15520. * 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.
  15521. */
  15522. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15523. if (checkFace === void 0) { checkFace = false; }
  15524. if (facing === void 0) { facing = true; }
  15525. var closest = null;
  15526. var tmpx = 0.0;
  15527. var tmpy = 0.0;
  15528. var tmpz = 0.0;
  15529. var d = 0.0; // tmp dot facet normal * facet position
  15530. var t0 = 0.0;
  15531. var projx = 0.0;
  15532. var projy = 0.0;
  15533. var projz = 0.0;
  15534. // Get all the facets in the same partitioning block than (x, y, z)
  15535. var facetPositions = this.getFacetLocalPositions();
  15536. var facetNormals = this.getFacetLocalNormals();
  15537. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15538. if (!facetsInBlock) {
  15539. return null;
  15540. }
  15541. // Get the closest facet to (x, y, z)
  15542. var shortest = Number.MAX_VALUE; // init distance vars
  15543. var tmpDistance = shortest;
  15544. var fib; // current facet in the block
  15545. var norm; // current facet normal
  15546. var p0; // current facet barycenter position
  15547. // loop on all the facets in the current partitioning block
  15548. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15549. fib = facetsInBlock[idx];
  15550. norm = facetNormals[fib];
  15551. p0 = facetPositions[fib];
  15552. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15553. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15554. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15555. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15556. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15557. projx = x + norm.x * t0;
  15558. projy = y + norm.y * t0;
  15559. projz = z + norm.z * t0;
  15560. tmpx = projx - x;
  15561. tmpy = projy - y;
  15562. tmpz = projz - z;
  15563. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15564. if (tmpDistance < shortest) {
  15565. shortest = tmpDistance;
  15566. closest = fib;
  15567. if (projected) {
  15568. projected.x = projx;
  15569. projected.y = projy;
  15570. projected.z = projz;
  15571. }
  15572. }
  15573. }
  15574. }
  15575. return closest;
  15576. };
  15577. /**
  15578. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15579. */
  15580. AbstractMesh.prototype.getFacetDataParameters = function () {
  15581. return this._facetParameters;
  15582. };
  15583. /**
  15584. * Disables the feature FacetData and frees the related memory.
  15585. * Returns the AbstractMesh.
  15586. */
  15587. AbstractMesh.prototype.disableFacetData = function () {
  15588. if (this._facetDataEnabled) {
  15589. this._facetDataEnabled = false;
  15590. this._facetPositions = new Array();
  15591. this._facetNormals = new Array();
  15592. this._facetPartitioning = new Array();
  15593. this._facetParameters = null;
  15594. this._depthSortedIndices = new Uint32Array(0);
  15595. }
  15596. return this;
  15597. };
  15598. /**
  15599. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15600. * Returns the mesh.
  15601. */
  15602. AbstractMesh.prototype.updateIndices = function (indices) {
  15603. return this;
  15604. };
  15605. /**
  15606. * The mesh Geometry. Actually used by the Mesh object.
  15607. * Returns a blank geometry object.
  15608. */
  15609. /**
  15610. * Creates new normals data for the mesh.
  15611. * @param updatable.
  15612. */
  15613. AbstractMesh.prototype.createNormals = function (updatable) {
  15614. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15615. var indices = this.getIndices();
  15616. var normals;
  15617. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15618. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15619. }
  15620. else {
  15621. normals = [];
  15622. }
  15623. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15624. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15625. };
  15626. /**
  15627. * Align the mesh with a normal.
  15628. * Returns the mesh.
  15629. */
  15630. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15631. if (!upDirection) {
  15632. upDirection = BABYLON.Axis.Y;
  15633. }
  15634. var axisX = BABYLON.Tmp.Vector3[0];
  15635. var axisZ = BABYLON.Tmp.Vector3[1];
  15636. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15637. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15638. if (this.rotationQuaternion) {
  15639. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15640. }
  15641. else {
  15642. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15643. }
  15644. return this;
  15645. };
  15646. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15647. var engine = this.getEngine();
  15648. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15649. this._isOccluded = false;
  15650. return;
  15651. }
  15652. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15653. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15654. if (isOcclusionQueryAvailable) {
  15655. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15656. this._isOcclusionQueryInProgress = false;
  15657. this._occlusionInternalRetryCounter = 0;
  15658. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15659. }
  15660. else {
  15661. this._occlusionInternalRetryCounter++;
  15662. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15663. this._isOcclusionQueryInProgress = false;
  15664. this._occlusionInternalRetryCounter = 0;
  15665. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15666. // if strict continue the last state of the object.
  15667. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15668. }
  15669. else {
  15670. return;
  15671. }
  15672. }
  15673. }
  15674. var scene = this.getScene();
  15675. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15676. if (!this._occlusionQuery) {
  15677. this._occlusionQuery = engine.createQuery();
  15678. }
  15679. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15680. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15681. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15682. this._isOcclusionQueryInProgress = true;
  15683. };
  15684. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15685. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15686. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15687. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15688. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15689. return AbstractMesh;
  15690. }(BABYLON.TransformNode));
  15691. BABYLON.AbstractMesh = AbstractMesh;
  15692. })(BABYLON || (BABYLON = {}));
  15693. //# sourceMappingURL=babylon.abstractMesh.js.map
  15694. var BABYLON;
  15695. (function (BABYLON) {
  15696. var Light = /** @class */ (function (_super) {
  15697. __extends(Light, _super);
  15698. /**
  15699. * Creates a Light object in the scene.
  15700. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15701. */
  15702. function Light(name, scene) {
  15703. var _this = _super.call(this, name, scene) || this;
  15704. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15705. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15706. _this.intensity = 1.0;
  15707. _this.range = Number.MAX_VALUE;
  15708. /**
  15709. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15710. * of light.
  15711. */
  15712. _this._photometricScale = 1.0;
  15713. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15714. _this._radius = 0.00001;
  15715. _this.renderPriority = 0;
  15716. /**
  15717. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15718. * the current shadow generator.
  15719. */
  15720. _this.shadowEnabled = true;
  15721. _this._excludeWithLayerMask = 0;
  15722. _this._includeOnlyWithLayerMask = 0;
  15723. _this._lightmapMode = 0;
  15724. _this._excludedMeshesIds = new Array();
  15725. _this._includedOnlyMeshesIds = new Array();
  15726. _this.getScene().addLight(_this);
  15727. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15728. _this._buildUniformLayout();
  15729. _this.includedOnlyMeshes = new Array();
  15730. _this.excludedMeshes = new Array();
  15731. _this._resyncMeshes();
  15732. return _this;
  15733. }
  15734. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15735. /**
  15736. * If every light affecting the material is in this lightmapMode,
  15737. * material.lightmapTexture adds or multiplies
  15738. * (depends on material.useLightmapAsShadowmap)
  15739. * after every other light calculations.
  15740. */
  15741. get: function () {
  15742. return Light._LIGHTMAP_DEFAULT;
  15743. },
  15744. enumerable: true,
  15745. configurable: true
  15746. });
  15747. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15748. /**
  15749. * material.lightmapTexture as only diffuse lighting from this light
  15750. * adds pnly specular lighting from this light
  15751. * adds dynamic shadows
  15752. */
  15753. get: function () {
  15754. return Light._LIGHTMAP_SPECULAR;
  15755. },
  15756. enumerable: true,
  15757. configurable: true
  15758. });
  15759. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15760. /**
  15761. * material.lightmapTexture as only lighting
  15762. * no light calculation from this light
  15763. * only adds dynamic shadows from this light
  15764. */
  15765. get: function () {
  15766. return Light._LIGHTMAP_SHADOWSONLY;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15772. /**
  15773. * Each light type uses the default quantity according to its type:
  15774. * point/spot lights use luminous intensity
  15775. * directional lights use illuminance
  15776. */
  15777. get: function () {
  15778. return Light._INTENSITYMODE_AUTOMATIC;
  15779. },
  15780. enumerable: true,
  15781. configurable: true
  15782. });
  15783. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15784. /**
  15785. * lumen (lm)
  15786. */
  15787. get: function () {
  15788. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15789. },
  15790. enumerable: true,
  15791. configurable: true
  15792. });
  15793. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15794. /**
  15795. * candela (lm/sr)
  15796. */
  15797. get: function () {
  15798. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15799. },
  15800. enumerable: true,
  15801. configurable: true
  15802. });
  15803. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15804. /**
  15805. * lux (lm/m^2)
  15806. */
  15807. get: function () {
  15808. return Light._INTENSITYMODE_ILLUMINANCE;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15814. /**
  15815. * nit (cd/m^2)
  15816. */
  15817. get: function () {
  15818. return Light._INTENSITYMODE_LUMINANCE;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15824. /**
  15825. * Light type const id of the point light.
  15826. */
  15827. get: function () {
  15828. return Light._LIGHTTYPEID_POINTLIGHT;
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15834. /**
  15835. * Light type const id of the directional light.
  15836. */
  15837. get: function () {
  15838. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15844. /**
  15845. * Light type const id of the spot light.
  15846. */
  15847. get: function () {
  15848. return Light._LIGHTTYPEID_SPOTLIGHT;
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15854. /**
  15855. * Light type const id of the hemispheric light.
  15856. */
  15857. get: function () {
  15858. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15859. },
  15860. enumerable: true,
  15861. configurable: true
  15862. });
  15863. Object.defineProperty(Light.prototype, "intensityMode", {
  15864. /**
  15865. * Gets the photometric scale used to interpret the intensity.
  15866. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15867. */
  15868. get: function () {
  15869. return this._intensityMode;
  15870. },
  15871. /**
  15872. * Sets the photometric scale used to interpret the intensity.
  15873. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15874. */
  15875. set: function (value) {
  15876. this._intensityMode = value;
  15877. this._computePhotometricScale();
  15878. },
  15879. enumerable: true,
  15880. configurable: true
  15881. });
  15882. ;
  15883. ;
  15884. Object.defineProperty(Light.prototype, "radius", {
  15885. /**
  15886. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15887. */
  15888. get: function () {
  15889. return this._radius;
  15890. },
  15891. /**
  15892. * sets the light radius used by PBR Materials to simulate soft area lights.
  15893. */
  15894. set: function (value) {
  15895. this._radius = value;
  15896. this._computePhotometricScale();
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. ;
  15902. ;
  15903. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15904. get: function () {
  15905. return this._includedOnlyMeshes;
  15906. },
  15907. set: function (value) {
  15908. this._includedOnlyMeshes = value;
  15909. this._hookArrayForIncludedOnly(value);
  15910. },
  15911. enumerable: true,
  15912. configurable: true
  15913. });
  15914. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15915. get: function () {
  15916. return this._excludedMeshes;
  15917. },
  15918. set: function (value) {
  15919. this._excludedMeshes = value;
  15920. this._hookArrayForExcluded(value);
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15926. get: function () {
  15927. return this._excludeWithLayerMask;
  15928. },
  15929. set: function (value) {
  15930. this._excludeWithLayerMask = value;
  15931. this._resyncMeshes();
  15932. },
  15933. enumerable: true,
  15934. configurable: true
  15935. });
  15936. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15937. get: function () {
  15938. return this._includeOnlyWithLayerMask;
  15939. },
  15940. set: function (value) {
  15941. this._includeOnlyWithLayerMask = value;
  15942. this._resyncMeshes();
  15943. },
  15944. enumerable: true,
  15945. configurable: true
  15946. });
  15947. Object.defineProperty(Light.prototype, "lightmapMode", {
  15948. get: function () {
  15949. return this._lightmapMode;
  15950. },
  15951. set: function (value) {
  15952. if (this._lightmapMode === value) {
  15953. return;
  15954. }
  15955. this._lightmapMode = value;
  15956. this._markMeshesAsLightDirty();
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Light.prototype._buildUniformLayout = function () {
  15962. // Overridden
  15963. };
  15964. /**
  15965. * Returns the string "Light".
  15966. */
  15967. Light.prototype.getClassName = function () {
  15968. return "Light";
  15969. };
  15970. /**
  15971. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15972. */
  15973. Light.prototype.toString = function (fullDetails) {
  15974. var ret = "Name: " + this.name;
  15975. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15976. if (this.animations) {
  15977. for (var i = 0; i < this.animations.length; i++) {
  15978. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15979. }
  15980. }
  15981. if (fullDetails) {
  15982. }
  15983. return ret;
  15984. };
  15985. /**
  15986. * Set the enabled state of this node.
  15987. * @param {boolean} value - the new enabled state
  15988. * @see isEnabled
  15989. */
  15990. Light.prototype.setEnabled = function (value) {
  15991. _super.prototype.setEnabled.call(this, value);
  15992. this._resyncMeshes();
  15993. };
  15994. /**
  15995. * Returns the Light associated shadow generator.
  15996. */
  15997. Light.prototype.getShadowGenerator = function () {
  15998. return this._shadowGenerator;
  15999. };
  16000. /**
  16001. * Returns a Vector3, the absolute light position in the World.
  16002. */
  16003. Light.prototype.getAbsolutePosition = function () {
  16004. return BABYLON.Vector3.Zero();
  16005. };
  16006. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16007. };
  16008. Light.prototype._getWorldMatrix = function () {
  16009. return BABYLON.Matrix.Identity();
  16010. };
  16011. /**
  16012. * Boolean : True if the light will affect the passed mesh.
  16013. */
  16014. Light.prototype.canAffectMesh = function (mesh) {
  16015. if (!mesh) {
  16016. return true;
  16017. }
  16018. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16019. return false;
  16020. }
  16021. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16022. return false;
  16023. }
  16024. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16025. return false;
  16026. }
  16027. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16028. return false;
  16029. }
  16030. return true;
  16031. };
  16032. /**
  16033. * Returns the light World matrix.
  16034. */
  16035. Light.prototype.getWorldMatrix = function () {
  16036. this._currentRenderId = this.getScene().getRenderId();
  16037. var worldMatrix = this._getWorldMatrix();
  16038. if (this.parent && this.parent.getWorldMatrix) {
  16039. if (!this._parentedWorldMatrix) {
  16040. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16041. }
  16042. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16043. this._markSyncedWithParent();
  16044. return this._parentedWorldMatrix;
  16045. }
  16046. return worldMatrix;
  16047. };
  16048. /**
  16049. * Sort function to order lights for rendering.
  16050. * @param a First Light object to compare to second.
  16051. * @param b Second Light object to compare first.
  16052. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16053. */
  16054. Light.compareLightsPriority = function (a, b) {
  16055. //shadow-casting lights have priority over non-shadow-casting lights
  16056. //the renderPrioirty is a secondary sort criterion
  16057. if (a.shadowEnabled !== b.shadowEnabled) {
  16058. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16059. }
  16060. return b.renderPriority - a.renderPriority;
  16061. };
  16062. /**
  16063. * Disposes the light.
  16064. */
  16065. Light.prototype.dispose = function () {
  16066. if (this._shadowGenerator) {
  16067. this._shadowGenerator.dispose();
  16068. this._shadowGenerator = null;
  16069. }
  16070. // Animations
  16071. this.getScene().stopAnimation(this);
  16072. // Remove from meshes
  16073. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16074. var mesh = _a[_i];
  16075. mesh._removeLightSource(this);
  16076. }
  16077. this._uniformBuffer.dispose();
  16078. // Remove from scene
  16079. this.getScene().removeLight(this);
  16080. _super.prototype.dispose.call(this);
  16081. };
  16082. /**
  16083. * Returns the light type ID (integer).
  16084. */
  16085. Light.prototype.getTypeID = function () {
  16086. return 0;
  16087. };
  16088. /**
  16089. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16090. */
  16091. Light.prototype.getScaledIntensity = function () {
  16092. return this._photometricScale * this.intensity;
  16093. };
  16094. /**
  16095. * Returns a new Light object, named "name", from the current one.
  16096. */
  16097. Light.prototype.clone = function (name) {
  16098. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16099. if (!constructor) {
  16100. return null;
  16101. }
  16102. return BABYLON.SerializationHelper.Clone(constructor, this);
  16103. };
  16104. /**
  16105. * Serializes the current light into a Serialization object.
  16106. * Returns the serialized object.
  16107. */
  16108. Light.prototype.serialize = function () {
  16109. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16110. // Type
  16111. serializationObject.type = this.getTypeID();
  16112. // Parent
  16113. if (this.parent) {
  16114. serializationObject.parentId = this.parent.id;
  16115. }
  16116. // Inclusion / exclusions
  16117. if (this.excludedMeshes.length > 0) {
  16118. serializationObject.excludedMeshesIds = [];
  16119. this.excludedMeshes.forEach(function (mesh) {
  16120. serializationObject.excludedMeshesIds.push(mesh.id);
  16121. });
  16122. }
  16123. if (this.includedOnlyMeshes.length > 0) {
  16124. serializationObject.includedOnlyMeshesIds = [];
  16125. this.includedOnlyMeshes.forEach(function (mesh) {
  16126. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16127. });
  16128. }
  16129. // Animations
  16130. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16131. serializationObject.ranges = this.serializeAnimationRanges();
  16132. return serializationObject;
  16133. };
  16134. /**
  16135. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16136. * This new light is named "name" and added to the passed scene.
  16137. */
  16138. Light.GetConstructorFromName = function (type, name, scene) {
  16139. switch (type) {
  16140. case 0:
  16141. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16142. case 1:
  16143. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16144. case 2:
  16145. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16146. case 3:
  16147. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16148. }
  16149. return null;
  16150. };
  16151. /**
  16152. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16153. */
  16154. Light.Parse = function (parsedLight, scene) {
  16155. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16156. if (!constructor) {
  16157. return null;
  16158. }
  16159. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16160. // Inclusion / exclusions
  16161. if (parsedLight.excludedMeshesIds) {
  16162. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16163. }
  16164. if (parsedLight.includedOnlyMeshesIds) {
  16165. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16166. }
  16167. // Parent
  16168. if (parsedLight.parentId) {
  16169. light._waitingParentId = parsedLight.parentId;
  16170. }
  16171. // Animations
  16172. if (parsedLight.animations) {
  16173. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16174. var parsedAnimation = parsedLight.animations[animationIndex];
  16175. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16176. }
  16177. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16178. }
  16179. if (parsedLight.autoAnimate) {
  16180. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16181. }
  16182. return light;
  16183. };
  16184. Light.prototype._hookArrayForExcluded = function (array) {
  16185. var _this = this;
  16186. var oldPush = array.push;
  16187. array.push = function () {
  16188. var items = [];
  16189. for (var _i = 0; _i < arguments.length; _i++) {
  16190. items[_i] = arguments[_i];
  16191. }
  16192. var result = oldPush.apply(array, items);
  16193. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16194. var item = items_1[_a];
  16195. item._resyncLighSource(_this);
  16196. }
  16197. return result;
  16198. };
  16199. var oldSplice = array.splice;
  16200. array.splice = function (index, deleteCount) {
  16201. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16202. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16203. var item = deleted_1[_i];
  16204. item._resyncLighSource(_this);
  16205. }
  16206. return deleted;
  16207. };
  16208. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16209. var item = array_1[_i];
  16210. item._resyncLighSource(this);
  16211. }
  16212. };
  16213. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16214. var _this = this;
  16215. var oldPush = array.push;
  16216. array.push = function () {
  16217. var items = [];
  16218. for (var _i = 0; _i < arguments.length; _i++) {
  16219. items[_i] = arguments[_i];
  16220. }
  16221. var result = oldPush.apply(array, items);
  16222. _this._resyncMeshes();
  16223. return result;
  16224. };
  16225. var oldSplice = array.splice;
  16226. array.splice = function (index, deleteCount) {
  16227. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16228. _this._resyncMeshes();
  16229. return deleted;
  16230. };
  16231. this._resyncMeshes();
  16232. };
  16233. Light.prototype._resyncMeshes = function () {
  16234. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16235. var mesh = _a[_i];
  16236. mesh._resyncLighSource(this);
  16237. }
  16238. };
  16239. Light.prototype._markMeshesAsLightDirty = function () {
  16240. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16241. var mesh = _a[_i];
  16242. if (mesh._lightSources.indexOf(this) !== -1) {
  16243. mesh._markSubMeshesAsLightDirty();
  16244. }
  16245. }
  16246. };
  16247. /**
  16248. * Recomputes the cached photometric scale if needed.
  16249. */
  16250. Light.prototype._computePhotometricScale = function () {
  16251. this._photometricScale = this._getPhotometricScale();
  16252. this.getScene().resetCachedMaterial();
  16253. };
  16254. /**
  16255. * Returns the Photometric Scale according to the light type and intensity mode.
  16256. */
  16257. Light.prototype._getPhotometricScale = function () {
  16258. var photometricScale = 0.0;
  16259. var lightTypeID = this.getTypeID();
  16260. //get photometric mode
  16261. var photometricMode = this.intensityMode;
  16262. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16263. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16264. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16265. }
  16266. else {
  16267. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16268. }
  16269. }
  16270. //compute photometric scale
  16271. switch (lightTypeID) {
  16272. case Light.LIGHTTYPEID_POINTLIGHT:
  16273. case Light.LIGHTTYPEID_SPOTLIGHT:
  16274. switch (photometricMode) {
  16275. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16276. photometricScale = 1.0 / (4.0 * Math.PI);
  16277. break;
  16278. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16279. photometricScale = 1.0;
  16280. break;
  16281. case Light.INTENSITYMODE_LUMINANCE:
  16282. photometricScale = this.radius * this.radius;
  16283. break;
  16284. }
  16285. break;
  16286. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16287. switch (photometricMode) {
  16288. case Light.INTENSITYMODE_ILLUMINANCE:
  16289. photometricScale = 1.0;
  16290. break;
  16291. case Light.INTENSITYMODE_LUMINANCE:
  16292. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16293. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16294. var apexAngleRadians = this.radius;
  16295. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16296. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16297. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16298. photometricScale = solidAngle;
  16299. break;
  16300. }
  16301. break;
  16302. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16303. // No fall off in hemisperic light.
  16304. photometricScale = 1.0;
  16305. break;
  16306. }
  16307. return photometricScale;
  16308. };
  16309. Light.prototype._reorderLightsInScene = function () {
  16310. var scene = this.getScene();
  16311. if (this._renderPriority != 0) {
  16312. scene.requireLightSorting = true;
  16313. }
  16314. this.getScene().sortLightsByPriority();
  16315. };
  16316. //lightmapMode Consts
  16317. Light._LIGHTMAP_DEFAULT = 0;
  16318. Light._LIGHTMAP_SPECULAR = 1;
  16319. Light._LIGHTMAP_SHADOWSONLY = 2;
  16320. // Intensity Mode Consts
  16321. Light._INTENSITYMODE_AUTOMATIC = 0;
  16322. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16323. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16324. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16325. Light._INTENSITYMODE_LUMINANCE = 4;
  16326. // Light types ids const.
  16327. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16328. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16329. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16330. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16331. __decorate([
  16332. BABYLON.serializeAsColor3()
  16333. ], Light.prototype, "diffuse", void 0);
  16334. __decorate([
  16335. BABYLON.serializeAsColor3()
  16336. ], Light.prototype, "specular", void 0);
  16337. __decorate([
  16338. BABYLON.serialize()
  16339. ], Light.prototype, "intensity", void 0);
  16340. __decorate([
  16341. BABYLON.serialize()
  16342. ], Light.prototype, "range", void 0);
  16343. __decorate([
  16344. BABYLON.serialize()
  16345. ], Light.prototype, "intensityMode", null);
  16346. __decorate([
  16347. BABYLON.serialize()
  16348. ], Light.prototype, "radius", null);
  16349. __decorate([
  16350. BABYLON.serialize()
  16351. ], Light.prototype, "_renderPriority", void 0);
  16352. __decorate([
  16353. BABYLON.expandToProperty("_reorderLightsInScene")
  16354. ], Light.prototype, "renderPriority", void 0);
  16355. __decorate([
  16356. BABYLON.serialize()
  16357. ], Light.prototype, "shadowEnabled", void 0);
  16358. __decorate([
  16359. BABYLON.serialize("excludeWithLayerMask")
  16360. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16361. __decorate([
  16362. BABYLON.serialize("includeOnlyWithLayerMask")
  16363. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16364. __decorate([
  16365. BABYLON.serialize("lightmapMode")
  16366. ], Light.prototype, "_lightmapMode", void 0);
  16367. return Light;
  16368. }(BABYLON.Node));
  16369. BABYLON.Light = Light;
  16370. })(BABYLON || (BABYLON = {}));
  16371. //# sourceMappingURL=babylon.light.js.map
  16372. var BABYLON;
  16373. (function (BABYLON) {
  16374. var Camera = /** @class */ (function (_super) {
  16375. __extends(Camera, _super);
  16376. function Camera(name, position, scene) {
  16377. var _this = _super.call(this, name, scene) || this;
  16378. _this.upVector = BABYLON.Vector3.Up();
  16379. _this.orthoLeft = null;
  16380. _this.orthoRight = null;
  16381. _this.orthoBottom = null;
  16382. _this.orthoTop = null;
  16383. _this.fov = 0.8;
  16384. _this.minZ = 1;
  16385. _this.maxZ = 10000.0;
  16386. _this.inertia = 0.9;
  16387. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16388. _this.isIntermediate = false;
  16389. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16390. _this.layerMask = 0x0FFFFFFF;
  16391. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16392. // Camera rig members
  16393. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16394. _this._rigCameras = new Array();
  16395. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16396. _this._skipRendering = false;
  16397. _this.customRenderTargets = new Array();
  16398. // Observables
  16399. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16400. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16401. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16402. _this.onRestoreStateObservable = new BABYLON.Observable();
  16403. // Cache
  16404. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16405. _this._projectionMatrix = new BABYLON.Matrix();
  16406. _this._doNotComputeProjectionMatrix = false;
  16407. _this._postProcesses = new Array();
  16408. _this._transformMatrix = BABYLON.Matrix.Zero();
  16409. _this._activeMeshes = new BABYLON.SmartArray(256);
  16410. _this._globalPosition = BABYLON.Vector3.Zero();
  16411. _this._refreshFrustumPlanes = true;
  16412. _this.getScene().addCamera(_this);
  16413. if (!_this.getScene().activeCamera) {
  16414. _this.getScene().activeCamera = _this;
  16415. }
  16416. _this.position = position;
  16417. return _this;
  16418. }
  16419. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16420. get: function () {
  16421. return Camera._PERSPECTIVE_CAMERA;
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16427. get: function () {
  16428. return Camera._ORTHOGRAPHIC_CAMERA;
  16429. },
  16430. enumerable: true,
  16431. configurable: true
  16432. });
  16433. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16434. get: function () {
  16435. return Camera._FOVMODE_VERTICAL_FIXED;
  16436. },
  16437. enumerable: true,
  16438. configurable: true
  16439. });
  16440. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16441. get: function () {
  16442. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16448. get: function () {
  16449. return Camera._RIG_MODE_NONE;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16455. get: function () {
  16456. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16462. get: function () {
  16463. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16469. get: function () {
  16470. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16471. },
  16472. enumerable: true,
  16473. configurable: true
  16474. });
  16475. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16476. get: function () {
  16477. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16478. },
  16479. enumerable: true,
  16480. configurable: true
  16481. });
  16482. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16483. get: function () {
  16484. return Camera._RIG_MODE_VR;
  16485. },
  16486. enumerable: true,
  16487. configurable: true
  16488. });
  16489. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16490. get: function () {
  16491. return Camera._RIG_MODE_WEBVR;
  16492. },
  16493. enumerable: true,
  16494. configurable: true
  16495. });
  16496. /**
  16497. * Store current camera state (fov, position, etc..)
  16498. */
  16499. Camera.prototype.storeState = function () {
  16500. this._stateStored = true;
  16501. this._storedFov = this.fov;
  16502. return this;
  16503. };
  16504. /**
  16505. * Restores the camera state values if it has been stored. You must call storeState() first
  16506. */
  16507. Camera.prototype._restoreStateValues = function () {
  16508. if (!this._stateStored) {
  16509. return false;
  16510. }
  16511. this.fov = this._storedFov;
  16512. return true;
  16513. };
  16514. /**
  16515. * Restored camera state. You must call storeState() first
  16516. */
  16517. Camera.prototype.restoreState = function () {
  16518. if (this._restoreStateValues()) {
  16519. this.onRestoreStateObservable.notifyObservers(this);
  16520. return true;
  16521. }
  16522. return false;
  16523. };
  16524. Camera.prototype.getClassName = function () {
  16525. return "Camera";
  16526. };
  16527. /**
  16528. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16529. */
  16530. Camera.prototype.toString = function (fullDetails) {
  16531. var ret = "Name: " + this.name;
  16532. ret += ", type: " + this.getClassName();
  16533. if (this.animations) {
  16534. for (var i = 0; i < this.animations.length; i++) {
  16535. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16536. }
  16537. }
  16538. if (fullDetails) {
  16539. }
  16540. return ret;
  16541. };
  16542. Object.defineProperty(Camera.prototype, "globalPosition", {
  16543. get: function () {
  16544. return this._globalPosition;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Camera.prototype.getActiveMeshes = function () {
  16550. return this._activeMeshes;
  16551. };
  16552. Camera.prototype.isActiveMesh = function (mesh) {
  16553. return (this._activeMeshes.indexOf(mesh) !== -1);
  16554. };
  16555. //Cache
  16556. Camera.prototype._initCache = function () {
  16557. _super.prototype._initCache.call(this);
  16558. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16559. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16560. this._cache.mode = undefined;
  16561. this._cache.minZ = undefined;
  16562. this._cache.maxZ = undefined;
  16563. this._cache.fov = undefined;
  16564. this._cache.fovMode = undefined;
  16565. this._cache.aspectRatio = undefined;
  16566. this._cache.orthoLeft = undefined;
  16567. this._cache.orthoRight = undefined;
  16568. this._cache.orthoBottom = undefined;
  16569. this._cache.orthoTop = undefined;
  16570. this._cache.renderWidth = undefined;
  16571. this._cache.renderHeight = undefined;
  16572. };
  16573. Camera.prototype._updateCache = function (ignoreParentClass) {
  16574. if (!ignoreParentClass) {
  16575. _super.prototype._updateCache.call(this);
  16576. }
  16577. this._cache.position.copyFrom(this.position);
  16578. this._cache.upVector.copyFrom(this.upVector);
  16579. };
  16580. // Synchronized
  16581. Camera.prototype._isSynchronized = function () {
  16582. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16583. };
  16584. Camera.prototype._isSynchronizedViewMatrix = function () {
  16585. if (!_super.prototype._isSynchronized.call(this))
  16586. return false;
  16587. return this._cache.position.equals(this.position)
  16588. && this._cache.upVector.equals(this.upVector)
  16589. && this.isSynchronizedWithParent();
  16590. };
  16591. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16592. var check = this._cache.mode === this.mode
  16593. && this._cache.minZ === this.minZ
  16594. && this._cache.maxZ === this.maxZ;
  16595. if (!check) {
  16596. return false;
  16597. }
  16598. var engine = this.getEngine();
  16599. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16600. check = this._cache.fov === this.fov
  16601. && this._cache.fovMode === this.fovMode
  16602. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16603. }
  16604. else {
  16605. check = this._cache.orthoLeft === this.orthoLeft
  16606. && this._cache.orthoRight === this.orthoRight
  16607. && this._cache.orthoBottom === this.orthoBottom
  16608. && this._cache.orthoTop === this.orthoTop
  16609. && this._cache.renderWidth === engine.getRenderWidth()
  16610. && this._cache.renderHeight === engine.getRenderHeight();
  16611. }
  16612. return check;
  16613. };
  16614. // Controls
  16615. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16616. };
  16617. Camera.prototype.detachControl = function (element) {
  16618. };
  16619. Camera.prototype.update = function () {
  16620. this._checkInputs();
  16621. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16622. this._updateRigCameras();
  16623. }
  16624. };
  16625. Camera.prototype._checkInputs = function () {
  16626. this.onAfterCheckInputsObservable.notifyObservers(this);
  16627. };
  16628. Object.defineProperty(Camera.prototype, "rigCameras", {
  16629. get: function () {
  16630. return this._rigCameras;
  16631. },
  16632. enumerable: true,
  16633. configurable: true
  16634. });
  16635. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16636. get: function () {
  16637. return this._rigPostProcess;
  16638. },
  16639. enumerable: true,
  16640. configurable: true
  16641. });
  16642. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16643. // invalidate framebuffer
  16644. if (this._postProcesses.length > 0) {
  16645. this._postProcesses[0].markTextureDirty();
  16646. }
  16647. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16648. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16649. var cam = this._rigCameras[i];
  16650. var rigPostProcess = cam._rigPostProcess;
  16651. // for VR rig, there does not have to be a post process
  16652. if (rigPostProcess) {
  16653. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16654. if (isPass) {
  16655. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16656. cam.isIntermediate = this._postProcesses.length === 0;
  16657. }
  16658. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16659. rigPostProcess.markTextureDirty();
  16660. }
  16661. else {
  16662. cam._postProcesses = this._postProcesses.slice(0);
  16663. }
  16664. }
  16665. };
  16666. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16667. if (insertAt === void 0) { insertAt = null; }
  16668. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16669. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16670. return 0;
  16671. }
  16672. if (insertAt == null || insertAt < 0) {
  16673. this._postProcesses.push(postProcess);
  16674. }
  16675. else {
  16676. this._postProcesses.splice(insertAt, 0, postProcess);
  16677. }
  16678. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16679. return this._postProcesses.indexOf(postProcess);
  16680. };
  16681. Camera.prototype.detachPostProcess = function (postProcess) {
  16682. var idx = this._postProcesses.indexOf(postProcess);
  16683. if (idx !== -1) {
  16684. this._postProcesses.splice(idx, 1);
  16685. }
  16686. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16687. };
  16688. Camera.prototype.getWorldMatrix = function () {
  16689. if (!this._worldMatrix) {
  16690. this._worldMatrix = BABYLON.Matrix.Identity();
  16691. }
  16692. var viewMatrix = this.getViewMatrix();
  16693. viewMatrix.invertToRef(this._worldMatrix);
  16694. return this._worldMatrix;
  16695. };
  16696. Camera.prototype._getViewMatrix = function () {
  16697. return BABYLON.Matrix.Identity();
  16698. };
  16699. Camera.prototype.getViewMatrix = function (force) {
  16700. if (!force && this._isSynchronizedViewMatrix()) {
  16701. return this._computedViewMatrix;
  16702. }
  16703. this.updateCache();
  16704. this._computedViewMatrix = this._getViewMatrix();
  16705. this._currentRenderId = this.getScene().getRenderId();
  16706. this._refreshFrustumPlanes = true;
  16707. if (!this.parent || !this.parent.getWorldMatrix) {
  16708. this._globalPosition.copyFrom(this.position);
  16709. }
  16710. else {
  16711. if (!this._worldMatrix) {
  16712. this._worldMatrix = BABYLON.Matrix.Identity();
  16713. }
  16714. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16715. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16716. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16717. this._computedViewMatrix.invert();
  16718. this._markSyncedWithParent();
  16719. }
  16720. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16721. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16722. }
  16723. this.onViewMatrixChangedObservable.notifyObservers(this);
  16724. return this._computedViewMatrix;
  16725. };
  16726. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16727. this._doNotComputeProjectionMatrix = true;
  16728. if (projection !== undefined) {
  16729. this._projectionMatrix = projection;
  16730. }
  16731. };
  16732. ;
  16733. Camera.prototype.unfreezeProjectionMatrix = function () {
  16734. this._doNotComputeProjectionMatrix = false;
  16735. };
  16736. ;
  16737. Camera.prototype.getProjectionMatrix = function (force) {
  16738. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16739. return this._projectionMatrix;
  16740. }
  16741. // Cache
  16742. this._cache.mode = this.mode;
  16743. this._cache.minZ = this.minZ;
  16744. this._cache.maxZ = this.maxZ;
  16745. // Matrix
  16746. this._refreshFrustumPlanes = true;
  16747. var engine = this.getEngine();
  16748. var scene = this.getScene();
  16749. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16750. this._cache.fov = this.fov;
  16751. this._cache.fovMode = this.fovMode;
  16752. this._cache.aspectRatio = engine.getAspectRatio(this);
  16753. if (this.minZ <= 0) {
  16754. this.minZ = 0.1;
  16755. }
  16756. if (scene.useRightHandedSystem) {
  16757. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16758. }
  16759. else {
  16760. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16761. }
  16762. }
  16763. else {
  16764. var halfWidth = engine.getRenderWidth() / 2.0;
  16765. var halfHeight = engine.getRenderHeight() / 2.0;
  16766. if (scene.useRightHandedSystem) {
  16767. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16768. }
  16769. else {
  16770. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16771. }
  16772. this._cache.orthoLeft = this.orthoLeft;
  16773. this._cache.orthoRight = this.orthoRight;
  16774. this._cache.orthoBottom = this.orthoBottom;
  16775. this._cache.orthoTop = this.orthoTop;
  16776. this._cache.renderWidth = engine.getRenderWidth();
  16777. this._cache.renderHeight = engine.getRenderHeight();
  16778. }
  16779. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16780. return this._projectionMatrix;
  16781. };
  16782. Camera.prototype.getTranformationMatrix = function () {
  16783. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16784. return this._transformMatrix;
  16785. };
  16786. Camera.prototype.updateFrustumPlanes = function () {
  16787. if (!this._refreshFrustumPlanes) {
  16788. return;
  16789. }
  16790. this.getTranformationMatrix();
  16791. if (!this._frustumPlanes) {
  16792. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16793. }
  16794. else {
  16795. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16796. }
  16797. this._refreshFrustumPlanes = false;
  16798. };
  16799. Camera.prototype.isInFrustum = function (target) {
  16800. this.updateFrustumPlanes();
  16801. return target.isInFrustum(this._frustumPlanes);
  16802. };
  16803. Camera.prototype.isCompletelyInFrustum = function (target) {
  16804. this.updateFrustumPlanes();
  16805. return target.isCompletelyInFrustum(this._frustumPlanes);
  16806. };
  16807. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16808. if (length === void 0) { length = 100; }
  16809. if (!transform) {
  16810. transform = this.getWorldMatrix();
  16811. }
  16812. if (!origin) {
  16813. origin = this.position;
  16814. }
  16815. var forward = new BABYLON.Vector3(0, 0, 1);
  16816. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16817. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16818. return new BABYLON.Ray(origin, direction, length);
  16819. };
  16820. Camera.prototype.dispose = function () {
  16821. // Observables
  16822. this.onViewMatrixChangedObservable.clear();
  16823. this.onProjectionMatrixChangedObservable.clear();
  16824. this.onAfterCheckInputsObservable.clear();
  16825. this.onRestoreStateObservable.clear();
  16826. // Inputs
  16827. if (this.inputs) {
  16828. this.inputs.clear();
  16829. }
  16830. // Animations
  16831. this.getScene().stopAnimation(this);
  16832. // Remove from scene
  16833. this.getScene().removeCamera(this);
  16834. while (this._rigCameras.length > 0) {
  16835. var camera = this._rigCameras.pop();
  16836. if (camera) {
  16837. camera.dispose();
  16838. }
  16839. }
  16840. // Postprocesses
  16841. if (this._rigPostProcess) {
  16842. this._rigPostProcess.dispose(this);
  16843. this._rigPostProcess = null;
  16844. this._postProcesses = [];
  16845. }
  16846. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16847. this._rigPostProcess = null;
  16848. this._postProcesses = [];
  16849. }
  16850. else {
  16851. var i = this._postProcesses.length;
  16852. while (--i >= 0) {
  16853. this._postProcesses[i].dispose(this);
  16854. }
  16855. }
  16856. // Render targets
  16857. var i = this.customRenderTargets.length;
  16858. while (--i >= 0) {
  16859. this.customRenderTargets[i].dispose();
  16860. }
  16861. this.customRenderTargets = [];
  16862. // Active Meshes
  16863. this._activeMeshes.dispose();
  16864. _super.prototype.dispose.call(this);
  16865. };
  16866. Object.defineProperty(Camera.prototype, "leftCamera", {
  16867. // ---- Camera rigs section ----
  16868. get: function () {
  16869. if (this._rigCameras.length < 1) {
  16870. return null;
  16871. }
  16872. return this._rigCameras[0];
  16873. },
  16874. enumerable: true,
  16875. configurable: true
  16876. });
  16877. Object.defineProperty(Camera.prototype, "rightCamera", {
  16878. get: function () {
  16879. if (this._rigCameras.length < 2) {
  16880. return null;
  16881. }
  16882. return this._rigCameras[1];
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. Camera.prototype.getLeftTarget = function () {
  16888. if (this._rigCameras.length < 1) {
  16889. return null;
  16890. }
  16891. return this._rigCameras[0].getTarget();
  16892. };
  16893. Camera.prototype.getRightTarget = function () {
  16894. if (this._rigCameras.length < 2) {
  16895. return null;
  16896. }
  16897. return this._rigCameras[1].getTarget();
  16898. };
  16899. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16900. if (this.cameraRigMode === mode) {
  16901. return;
  16902. }
  16903. while (this._rigCameras.length > 0) {
  16904. var camera = this._rigCameras.pop();
  16905. if (camera) {
  16906. camera.dispose();
  16907. }
  16908. }
  16909. this.cameraRigMode = mode;
  16910. this._cameraRigParams = {};
  16911. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16912. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16913. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16914. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16915. // create the rig cameras, unless none
  16916. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16917. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16918. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16919. if (leftCamera && rightCamera) {
  16920. this._rigCameras.push(leftCamera);
  16921. this._rigCameras.push(rightCamera);
  16922. }
  16923. }
  16924. switch (this.cameraRigMode) {
  16925. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16926. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16927. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16928. break;
  16929. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16930. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16931. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16932. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16933. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16934. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16935. break;
  16936. case Camera.RIG_MODE_VR:
  16937. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16938. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16939. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16940. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16941. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16942. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16943. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16944. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16945. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16946. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16947. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16948. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16949. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16950. if (metrics.compensateDistortion) {
  16951. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16952. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16953. }
  16954. break;
  16955. case Camera.RIG_MODE_WEBVR:
  16956. if (rigParams.vrDisplay) {
  16957. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16958. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16959. //Left eye
  16960. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16961. this._rigCameras[0].setCameraRigParameter("left", true);
  16962. //leaving this for future reference
  16963. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16964. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16965. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16966. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16967. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16968. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16969. this._rigCameras[0].parent = this;
  16970. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16971. //Right eye
  16972. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16973. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16974. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16975. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16976. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16977. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16978. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16979. this._rigCameras[1].parent = this;
  16980. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16981. if (Camera.UseAlternateWebVRRendering) {
  16982. this._rigCameras[1]._skipRendering = true;
  16983. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16984. }
  16985. }
  16986. break;
  16987. }
  16988. this._cascadePostProcessesToRigCams();
  16989. this.update();
  16990. };
  16991. Camera.prototype._getVRProjectionMatrix = function () {
  16992. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16993. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16994. return this._projectionMatrix;
  16995. };
  16996. Camera.prototype._updateCameraRotationMatrix = function () {
  16997. //Here for WebVR
  16998. };
  16999. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17000. //Here for WebVR
  17001. };
  17002. /**
  17003. * This function MUST be overwritten by the different WebVR cameras available.
  17004. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17005. */
  17006. Camera.prototype._getWebVRProjectionMatrix = function () {
  17007. return BABYLON.Matrix.Identity();
  17008. };
  17009. /**
  17010. * This function MUST be overwritten by the different WebVR cameras available.
  17011. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17012. */
  17013. Camera.prototype._getWebVRViewMatrix = function () {
  17014. return BABYLON.Matrix.Identity();
  17015. };
  17016. Camera.prototype.setCameraRigParameter = function (name, value) {
  17017. if (!this._cameraRigParams) {
  17018. this._cameraRigParams = {};
  17019. }
  17020. this._cameraRigParams[name] = value;
  17021. //provisionnally:
  17022. if (name === "interaxialDistance") {
  17023. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17024. }
  17025. };
  17026. /**
  17027. * needs to be overridden by children so sub has required properties to be copied
  17028. */
  17029. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17030. return null;
  17031. };
  17032. /**
  17033. * May need to be overridden by children
  17034. */
  17035. Camera.prototype._updateRigCameras = function () {
  17036. for (var i = 0; i < this._rigCameras.length; i++) {
  17037. this._rigCameras[i].minZ = this.minZ;
  17038. this._rigCameras[i].maxZ = this.maxZ;
  17039. this._rigCameras[i].fov = this.fov;
  17040. }
  17041. // only update viewport when ANAGLYPH
  17042. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17043. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17044. }
  17045. };
  17046. Camera.prototype._setupInputs = function () {
  17047. };
  17048. Camera.prototype.serialize = function () {
  17049. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17050. // Type
  17051. serializationObject.type = this.getClassName();
  17052. // Parent
  17053. if (this.parent) {
  17054. serializationObject.parentId = this.parent.id;
  17055. }
  17056. if (this.inputs) {
  17057. this.inputs.serialize(serializationObject);
  17058. }
  17059. // Animations
  17060. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17061. serializationObject.ranges = this.serializeAnimationRanges();
  17062. return serializationObject;
  17063. };
  17064. Camera.prototype.clone = function (name) {
  17065. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17066. };
  17067. Camera.prototype.getDirection = function (localAxis) {
  17068. var result = BABYLON.Vector3.Zero();
  17069. this.getDirectionToRef(localAxis, result);
  17070. return result;
  17071. };
  17072. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17073. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17074. };
  17075. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17076. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17077. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17078. switch (type) {
  17079. case "ArcRotateCamera":
  17080. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17081. case "DeviceOrientationCamera":
  17082. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17083. case "FollowCamera":
  17084. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17085. case "ArcFollowCamera":
  17086. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17087. case "GamepadCamera":
  17088. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17089. case "TouchCamera":
  17090. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17091. case "VirtualJoysticksCamera":
  17092. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17093. case "WebVRFreeCamera":
  17094. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17095. case "WebVRGamepadCamera":
  17096. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17097. case "VRDeviceOrientationFreeCamera":
  17098. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17099. case "VRDeviceOrientationGamepadCamera":
  17100. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17101. case "AnaglyphArcRotateCamera":
  17102. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17103. case "AnaglyphFreeCamera":
  17104. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17105. case "AnaglyphGamepadCamera":
  17106. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17107. case "AnaglyphUniversalCamera":
  17108. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17109. case "StereoscopicArcRotateCamera":
  17110. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17111. case "StereoscopicFreeCamera":
  17112. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17113. case "StereoscopicGamepadCamera":
  17114. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17115. case "StereoscopicUniversalCamera":
  17116. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17117. case "FreeCamera":// Forcing Universal here
  17118. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17119. default:// Universal Camera is the default value
  17120. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17121. }
  17122. };
  17123. Camera.Parse = function (parsedCamera, scene) {
  17124. var type = parsedCamera.type;
  17125. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17126. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17127. // Parent
  17128. if (parsedCamera.parentId) {
  17129. camera._waitingParentId = parsedCamera.parentId;
  17130. }
  17131. //If camera has an input manager, let it parse inputs settings
  17132. if (camera.inputs) {
  17133. camera.inputs.parse(parsedCamera);
  17134. camera._setupInputs();
  17135. }
  17136. if (camera.setPosition) {
  17137. camera.position.copyFromFloats(0, 0, 0);
  17138. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17139. }
  17140. // Target
  17141. if (parsedCamera.target) {
  17142. if (camera.setTarget) {
  17143. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17144. }
  17145. }
  17146. // Apply 3d rig, when found
  17147. if (parsedCamera.cameraRigMode) {
  17148. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17149. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17150. }
  17151. // Animations
  17152. if (parsedCamera.animations) {
  17153. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17154. var parsedAnimation = parsedCamera.animations[animationIndex];
  17155. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17156. }
  17157. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17158. }
  17159. if (parsedCamera.autoAnimate) {
  17160. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17161. }
  17162. return camera;
  17163. };
  17164. // Statics
  17165. Camera._PERSPECTIVE_CAMERA = 0;
  17166. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17167. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17168. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17169. Camera._RIG_MODE_NONE = 0;
  17170. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17171. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17172. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17173. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17174. Camera._RIG_MODE_VR = 20;
  17175. Camera._RIG_MODE_WEBVR = 21;
  17176. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17177. Camera.UseAlternateWebVRRendering = false;
  17178. __decorate([
  17179. BABYLON.serializeAsVector3()
  17180. ], Camera.prototype, "position", void 0);
  17181. __decorate([
  17182. BABYLON.serializeAsVector3()
  17183. ], Camera.prototype, "upVector", void 0);
  17184. __decorate([
  17185. BABYLON.serialize()
  17186. ], Camera.prototype, "orthoLeft", void 0);
  17187. __decorate([
  17188. BABYLON.serialize()
  17189. ], Camera.prototype, "orthoRight", void 0);
  17190. __decorate([
  17191. BABYLON.serialize()
  17192. ], Camera.prototype, "orthoBottom", void 0);
  17193. __decorate([
  17194. BABYLON.serialize()
  17195. ], Camera.prototype, "orthoTop", void 0);
  17196. __decorate([
  17197. BABYLON.serialize()
  17198. ], Camera.prototype, "fov", void 0);
  17199. __decorate([
  17200. BABYLON.serialize()
  17201. ], Camera.prototype, "minZ", void 0);
  17202. __decorate([
  17203. BABYLON.serialize()
  17204. ], Camera.prototype, "maxZ", void 0);
  17205. __decorate([
  17206. BABYLON.serialize()
  17207. ], Camera.prototype, "inertia", void 0);
  17208. __decorate([
  17209. BABYLON.serialize()
  17210. ], Camera.prototype, "mode", void 0);
  17211. __decorate([
  17212. BABYLON.serialize()
  17213. ], Camera.prototype, "layerMask", void 0);
  17214. __decorate([
  17215. BABYLON.serialize()
  17216. ], Camera.prototype, "fovMode", void 0);
  17217. __decorate([
  17218. BABYLON.serialize()
  17219. ], Camera.prototype, "cameraRigMode", void 0);
  17220. __decorate([
  17221. BABYLON.serialize()
  17222. ], Camera.prototype, "interaxialDistance", void 0);
  17223. __decorate([
  17224. BABYLON.serialize()
  17225. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17226. return Camera;
  17227. }(BABYLON.Node));
  17228. BABYLON.Camera = Camera;
  17229. })(BABYLON || (BABYLON = {}));
  17230. //# sourceMappingURL=babylon.camera.js.map
  17231. var BABYLON;
  17232. (function (BABYLON) {
  17233. var RenderingManager = /** @class */ (function () {
  17234. function RenderingManager(scene) {
  17235. this._renderingGroups = new Array();
  17236. this._autoClearDepthStencil = {};
  17237. this._customOpaqueSortCompareFn = {};
  17238. this._customAlphaTestSortCompareFn = {};
  17239. this._customTransparentSortCompareFn = {};
  17240. this._renderinGroupInfo = null;
  17241. this._scene = scene;
  17242. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17243. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17244. }
  17245. }
  17246. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17247. if (depth === void 0) { depth = true; }
  17248. if (stencil === void 0) { stencil = true; }
  17249. if (this._depthStencilBufferAlreadyCleaned) {
  17250. return;
  17251. }
  17252. this._scene.getEngine().clear(null, false, depth, stencil);
  17253. this._depthStencilBufferAlreadyCleaned = true;
  17254. };
  17255. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17256. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17257. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17258. var info = null;
  17259. if (observable) {
  17260. if (!this._renderinGroupInfo) {
  17261. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17262. }
  17263. info = this._renderinGroupInfo;
  17264. info.scene = this._scene;
  17265. info.camera = this._scene.activeCamera;
  17266. }
  17267. // Dispatch sprites
  17268. if (renderSprites) {
  17269. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17270. var manager = this._scene.spriteManagers[index];
  17271. this.dispatchSprites(manager);
  17272. }
  17273. }
  17274. // Render
  17275. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17276. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17277. var renderingGroup = this._renderingGroups[index];
  17278. if (!renderingGroup && !observable)
  17279. continue;
  17280. var renderingGroupMask = 0;
  17281. // Fire PRECLEAR stage
  17282. if (observable && info) {
  17283. renderingGroupMask = Math.pow(2, index);
  17284. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17285. info.renderingGroupId = index;
  17286. observable.notifyObservers(info, renderingGroupMask);
  17287. }
  17288. // Clear depth/stencil if needed
  17289. if (RenderingManager.AUTOCLEAR) {
  17290. var autoClear = this._autoClearDepthStencil[index];
  17291. if (autoClear && autoClear.autoClear) {
  17292. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17293. }
  17294. }
  17295. if (observable && info) {
  17296. // Fire PREOPAQUE stage
  17297. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17298. observable.notifyObservers(info, renderingGroupMask);
  17299. // Fire PRETRANSPARENT stage
  17300. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17301. observable.notifyObservers(info, renderingGroupMask);
  17302. }
  17303. if (renderingGroup)
  17304. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17305. // Fire POSTTRANSPARENT stage
  17306. if (observable && info) {
  17307. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17308. observable.notifyObservers(info, renderingGroupMask);
  17309. }
  17310. }
  17311. };
  17312. RenderingManager.prototype.reset = function () {
  17313. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17314. var renderingGroup = this._renderingGroups[index];
  17315. if (renderingGroup) {
  17316. renderingGroup.prepare();
  17317. }
  17318. }
  17319. };
  17320. RenderingManager.prototype.dispose = function () {
  17321. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17322. var renderingGroup = this._renderingGroups[index];
  17323. if (renderingGroup) {
  17324. renderingGroup.dispose();
  17325. }
  17326. }
  17327. this._renderingGroups.length = 0;
  17328. };
  17329. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17330. if (!this._renderingGroups[renderingGroupId]) {
  17331. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17332. }
  17333. };
  17334. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17335. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17336. this._prepareRenderingGroup(renderingGroupId);
  17337. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17338. };
  17339. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17340. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17341. this._prepareRenderingGroup(renderingGroupId);
  17342. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17343. };
  17344. RenderingManager.prototype.dispatch = function (subMesh) {
  17345. var mesh = subMesh.getMesh();
  17346. var renderingGroupId = mesh.renderingGroupId || 0;
  17347. this._prepareRenderingGroup(renderingGroupId);
  17348. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17349. };
  17350. /**
  17351. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17352. * This allowed control for front to back rendering or reversly depending of the special needs.
  17353. *
  17354. * @param renderingGroupId The rendering group id corresponding to its index
  17355. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17356. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17357. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17358. */
  17359. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17360. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17361. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17362. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17363. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17364. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17365. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17366. if (this._renderingGroups[renderingGroupId]) {
  17367. var group = this._renderingGroups[renderingGroupId];
  17368. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17369. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17370. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17371. }
  17372. };
  17373. /**
  17374. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17375. *
  17376. * @param renderingGroupId The rendering group id corresponding to its index
  17377. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17378. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17379. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17380. */
  17381. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17382. if (depth === void 0) { depth = true; }
  17383. if (stencil === void 0) { stencil = true; }
  17384. this._autoClearDepthStencil[renderingGroupId] = {
  17385. autoClear: autoClearDepthStencil,
  17386. depth: depth,
  17387. stencil: stencil
  17388. };
  17389. };
  17390. /**
  17391. * The max id used for rendering groups (not included)
  17392. */
  17393. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17394. /**
  17395. * The min id used for rendering groups (included)
  17396. */
  17397. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17398. /**
  17399. * Used to globally prevent autoclearing scenes.
  17400. */
  17401. RenderingManager.AUTOCLEAR = true;
  17402. return RenderingManager;
  17403. }());
  17404. BABYLON.RenderingManager = RenderingManager;
  17405. })(BABYLON || (BABYLON = {}));
  17406. //# sourceMappingURL=babylon.renderingManager.js.map
  17407. var BABYLON;
  17408. (function (BABYLON) {
  17409. var RenderingGroup = /** @class */ (function () {
  17410. /**
  17411. * Creates a new rendering group.
  17412. * @param index The rendering group index
  17413. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17414. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17415. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17416. */
  17417. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17418. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17419. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17420. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17421. this.index = index;
  17422. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17423. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17424. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17425. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17426. this._particleSystems = new BABYLON.SmartArray(256);
  17427. this._spriteManagers = new BABYLON.SmartArray(256);
  17428. this._edgesRenderers = new BABYLON.SmartArray(16);
  17429. this._scene = scene;
  17430. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17431. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17432. this.transparentSortCompareFn = transparentSortCompareFn;
  17433. }
  17434. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17435. /**
  17436. * Set the opaque sort comparison function.
  17437. * If null the sub meshes will be render in the order they were created
  17438. */
  17439. set: function (value) {
  17440. this._opaqueSortCompareFn = value;
  17441. if (value) {
  17442. this._renderOpaque = this.renderOpaqueSorted;
  17443. }
  17444. else {
  17445. this._renderOpaque = RenderingGroup.renderUnsorted;
  17446. }
  17447. },
  17448. enumerable: true,
  17449. configurable: true
  17450. });
  17451. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17452. /**
  17453. * Set the alpha test sort comparison function.
  17454. * If null the sub meshes will be render in the order they were created
  17455. */
  17456. set: function (value) {
  17457. this._alphaTestSortCompareFn = value;
  17458. if (value) {
  17459. this._renderAlphaTest = this.renderAlphaTestSorted;
  17460. }
  17461. else {
  17462. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17463. }
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17469. /**
  17470. * Set the transparent sort comparison function.
  17471. * If null the sub meshes will be render in the order they were created
  17472. */
  17473. set: function (value) {
  17474. if (value) {
  17475. this._transparentSortCompareFn = value;
  17476. }
  17477. else {
  17478. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17479. }
  17480. this._renderTransparent = this.renderTransparentSorted;
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. /**
  17486. * Render all the sub meshes contained in the group.
  17487. * @param customRenderFunction Used to override the default render behaviour of the group.
  17488. * @returns true if rendered some submeshes.
  17489. */
  17490. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17491. if (customRenderFunction) {
  17492. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17493. return;
  17494. }
  17495. var engine = this._scene.getEngine();
  17496. // Depth only
  17497. if (this._depthOnlySubMeshes.length !== 0) {
  17498. engine.setAlphaTesting(true);
  17499. engine.setColorWrite(false);
  17500. this._renderAlphaTest(this._depthOnlySubMeshes);
  17501. engine.setAlphaTesting(false);
  17502. engine.setColorWrite(true);
  17503. }
  17504. // Opaque
  17505. if (this._opaqueSubMeshes.length !== 0) {
  17506. this._renderOpaque(this._opaqueSubMeshes);
  17507. }
  17508. // Alpha test
  17509. if (this._alphaTestSubMeshes.length !== 0) {
  17510. engine.setAlphaTesting(true);
  17511. this._renderAlphaTest(this._alphaTestSubMeshes);
  17512. engine.setAlphaTesting(false);
  17513. }
  17514. var stencilState = engine.getStencilBuffer();
  17515. engine.setStencilBuffer(false);
  17516. // Sprites
  17517. if (renderSprites) {
  17518. this._renderSprites();
  17519. }
  17520. // Particles
  17521. if (renderParticles) {
  17522. this._renderParticles(activeMeshes);
  17523. }
  17524. if (this.onBeforeTransparentRendering) {
  17525. this.onBeforeTransparentRendering();
  17526. }
  17527. // Transparent
  17528. if (this._transparentSubMeshes.length !== 0) {
  17529. this._renderTransparent(this._transparentSubMeshes);
  17530. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17531. }
  17532. // Set back stencil to false in case it changes before the edge renderer.
  17533. engine.setStencilBuffer(false);
  17534. // Edges
  17535. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17536. this._edgesRenderers.data[edgesRendererIndex].render();
  17537. }
  17538. // Restore Stencil state.
  17539. engine.setStencilBuffer(stencilState);
  17540. };
  17541. /**
  17542. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17543. * @param subMeshes The submeshes to render
  17544. */
  17545. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17546. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17547. };
  17548. /**
  17549. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17550. * @param subMeshes The submeshes to render
  17551. */
  17552. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17553. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17554. };
  17555. /**
  17556. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17557. * @param subMeshes The submeshes to render
  17558. */
  17559. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17560. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17561. };
  17562. /**
  17563. * Renders the submeshes in a specified order.
  17564. * @param subMeshes The submeshes to sort before render
  17565. * @param sortCompareFn The comparison function use to sort
  17566. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17567. * @param transparent Specifies to activate blending if true
  17568. */
  17569. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17570. var subIndex = 0;
  17571. var subMesh;
  17572. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17573. for (; subIndex < subMeshes.length; subIndex++) {
  17574. subMesh = subMeshes.data[subIndex];
  17575. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17576. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17577. }
  17578. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17579. if (sortCompareFn) {
  17580. sortedArray.sort(sortCompareFn);
  17581. }
  17582. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17583. subMesh = sortedArray[subIndex];
  17584. if (transparent) {
  17585. var material = subMesh.getMaterial();
  17586. if (material && material.needDepthPrePass) {
  17587. var engine = material.getScene().getEngine();
  17588. engine.setColorWrite(false);
  17589. engine.setAlphaTesting(true);
  17590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17591. subMesh.render(false);
  17592. engine.setAlphaTesting(false);
  17593. engine.setColorWrite(true);
  17594. }
  17595. }
  17596. subMesh.render(transparent);
  17597. }
  17598. };
  17599. /**
  17600. * Renders the submeshes in the order they were dispatched (no sort applied).
  17601. * @param subMeshes The submeshes to render
  17602. */
  17603. RenderingGroup.renderUnsorted = function (subMeshes) {
  17604. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17605. var submesh = subMeshes.data[subIndex];
  17606. submesh.render(false);
  17607. }
  17608. };
  17609. /**
  17610. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17611. * are rendered back to front if in the same alpha index.
  17612. *
  17613. * @param a The first submesh
  17614. * @param b The second submesh
  17615. * @returns The result of the comparison
  17616. */
  17617. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17618. // Alpha index first
  17619. if (a._alphaIndex > b._alphaIndex) {
  17620. return 1;
  17621. }
  17622. if (a._alphaIndex < b._alphaIndex) {
  17623. return -1;
  17624. }
  17625. // Then distance to camera
  17626. return RenderingGroup.backToFrontSortCompare(a, b);
  17627. };
  17628. /**
  17629. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17630. * are rendered back to front.
  17631. *
  17632. * @param a The first submesh
  17633. * @param b The second submesh
  17634. * @returns The result of the comparison
  17635. */
  17636. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17637. // Then distance to camera
  17638. if (a._distanceToCamera < b._distanceToCamera) {
  17639. return 1;
  17640. }
  17641. if (a._distanceToCamera > b._distanceToCamera) {
  17642. return -1;
  17643. }
  17644. return 0;
  17645. };
  17646. /**
  17647. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17648. * are rendered front to back (prevent overdraw).
  17649. *
  17650. * @param a The first submesh
  17651. * @param b The second submesh
  17652. * @returns The result of the comparison
  17653. */
  17654. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17655. // Then distance to camera
  17656. if (a._distanceToCamera < b._distanceToCamera) {
  17657. return -1;
  17658. }
  17659. if (a._distanceToCamera > b._distanceToCamera) {
  17660. return 1;
  17661. }
  17662. return 0;
  17663. };
  17664. /**
  17665. * Resets the different lists of submeshes to prepare a new frame.
  17666. */
  17667. RenderingGroup.prototype.prepare = function () {
  17668. this._opaqueSubMeshes.reset();
  17669. this._transparentSubMeshes.reset();
  17670. this._alphaTestSubMeshes.reset();
  17671. this._depthOnlySubMeshes.reset();
  17672. this._particleSystems.reset();
  17673. this._spriteManagers.reset();
  17674. this._edgesRenderers.reset();
  17675. };
  17676. RenderingGroup.prototype.dispose = function () {
  17677. this._opaqueSubMeshes.dispose();
  17678. this._transparentSubMeshes.dispose();
  17679. this._alphaTestSubMeshes.dispose();
  17680. this._depthOnlySubMeshes.dispose();
  17681. this._particleSystems.dispose();
  17682. this._spriteManagers.dispose();
  17683. this._edgesRenderers.dispose();
  17684. };
  17685. /**
  17686. * Inserts the submesh in its correct queue depending on its material.
  17687. * @param subMesh The submesh to dispatch
  17688. */
  17689. RenderingGroup.prototype.dispatch = function (subMesh) {
  17690. var material = subMesh.getMaterial();
  17691. var mesh = subMesh.getMesh();
  17692. if (!material) {
  17693. return;
  17694. }
  17695. if (material.needAlphaBlendingForMesh(mesh)) {
  17696. this._transparentSubMeshes.push(subMesh);
  17697. }
  17698. else if (material.needAlphaTesting()) {
  17699. if (material.needDepthPrePass) {
  17700. this._depthOnlySubMeshes.push(subMesh);
  17701. }
  17702. this._alphaTestSubMeshes.push(subMesh);
  17703. }
  17704. else {
  17705. if (material.needDepthPrePass) {
  17706. this._depthOnlySubMeshes.push(subMesh);
  17707. }
  17708. this._opaqueSubMeshes.push(subMesh); // Opaque
  17709. }
  17710. if (mesh._edgesRenderer) {
  17711. this._edgesRenderers.push(mesh._edgesRenderer);
  17712. }
  17713. };
  17714. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17715. this._spriteManagers.push(spriteManager);
  17716. };
  17717. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17718. this._particleSystems.push(particleSystem);
  17719. };
  17720. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17721. if (this._particleSystems.length === 0) {
  17722. return;
  17723. }
  17724. // Particles
  17725. var activeCamera = this._scene.activeCamera;
  17726. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17727. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17728. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17729. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17730. continue;
  17731. }
  17732. var emitter = particleSystem.emitter;
  17733. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17734. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17735. }
  17736. }
  17737. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17738. };
  17739. RenderingGroup.prototype._renderSprites = function () {
  17740. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17741. return;
  17742. }
  17743. // Sprites
  17744. var activeCamera = this._scene.activeCamera;
  17745. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17746. for (var id = 0; id < this._spriteManagers.length; id++) {
  17747. var spriteManager = this._spriteManagers.data[id];
  17748. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17749. spriteManager.render();
  17750. }
  17751. }
  17752. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17753. };
  17754. return RenderingGroup;
  17755. }());
  17756. BABYLON.RenderingGroup = RenderingGroup;
  17757. })(BABYLON || (BABYLON = {}));
  17758. //# sourceMappingURL=babylon.renderingGroup.js.map
  17759. var BABYLON;
  17760. (function (BABYLON) {
  17761. var ClickInfo = /** @class */ (function () {
  17762. function ClickInfo() {
  17763. this._singleClick = false;
  17764. this._doubleClick = false;
  17765. this._hasSwiped = false;
  17766. this._ignore = false;
  17767. }
  17768. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17769. get: function () {
  17770. return this._singleClick;
  17771. },
  17772. set: function (b) {
  17773. this._singleClick = b;
  17774. },
  17775. enumerable: true,
  17776. configurable: true
  17777. });
  17778. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17779. get: function () {
  17780. return this._doubleClick;
  17781. },
  17782. set: function (b) {
  17783. this._doubleClick = b;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17789. get: function () {
  17790. return this._hasSwiped;
  17791. },
  17792. set: function (b) {
  17793. this._hasSwiped = b;
  17794. },
  17795. enumerable: true,
  17796. configurable: true
  17797. });
  17798. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17799. get: function () {
  17800. return this._ignore;
  17801. },
  17802. set: function (b) {
  17803. this._ignore = b;
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. return ClickInfo;
  17809. }());
  17810. /**
  17811. * This class is used by the onRenderingGroupObservable
  17812. */
  17813. var RenderingGroupInfo = /** @class */ (function () {
  17814. function RenderingGroupInfo() {
  17815. }
  17816. /**
  17817. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17818. * This stage will be fired no matter what
  17819. */
  17820. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17821. /**
  17822. * Called before opaque object are rendered.
  17823. * This stage will be fired only if there's 3D Opaque content to render
  17824. */
  17825. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17826. /**
  17827. * Called after the opaque objects are rendered and before the transparent ones
  17828. * This stage will be fired only if there's 3D transparent content to render
  17829. */
  17830. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17831. /**
  17832. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17833. * This stage will be fired no matter what
  17834. */
  17835. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17836. return RenderingGroupInfo;
  17837. }());
  17838. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17839. /**
  17840. * Represents a scene to be rendered by the engine.
  17841. * @see http://doc.babylonjs.com/page.php?p=21911
  17842. */
  17843. var Scene = /** @class */ (function () {
  17844. /**
  17845. * @constructor
  17846. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17847. */
  17848. function Scene(engine) {
  17849. // Members
  17850. this.autoClear = true;
  17851. this.autoClearDepthAndStencil = true;
  17852. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17853. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17854. this.forceWireframe = false;
  17855. this._forcePointsCloud = false;
  17856. this.forceShowBoundingBoxes = false;
  17857. this.animationsEnabled = true;
  17858. this.constantlyUpdateMeshUnderPointer = false;
  17859. this.hoverCursor = "pointer";
  17860. this.defaultCursor = "";
  17861. /**
  17862. * This is used to call preventDefault() on pointer down
  17863. * in order to block unwanted artifacts like system double clicks
  17864. */
  17865. this.preventDefaultOnPointerDown = true;
  17866. // Metadata
  17867. this.metadata = null;
  17868. /**
  17869. * An event triggered when the scene is disposed.
  17870. * @type {BABYLON.Observable}
  17871. */
  17872. this.onDisposeObservable = new BABYLON.Observable();
  17873. /**
  17874. * An event triggered before rendering the scene (right after animations and physics)
  17875. * @type {BABYLON.Observable}
  17876. */
  17877. this.onBeforeRenderObservable = new BABYLON.Observable();
  17878. /**
  17879. * An event triggered after rendering the scene
  17880. * @type {BABYLON.Observable}
  17881. */
  17882. this.onAfterRenderObservable = new BABYLON.Observable();
  17883. /**
  17884. * An event triggered before animating the scene
  17885. * @type {BABYLON.Observable}
  17886. */
  17887. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17888. /**
  17889. * An event triggered after animations processing
  17890. * @type {BABYLON.Observable}
  17891. */
  17892. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17893. /**
  17894. * An event triggered before draw calls are ready to be sent
  17895. * @type {BABYLON.Observable}
  17896. */
  17897. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17898. /**
  17899. * An event triggered after draw calls have been sent
  17900. * @type {BABYLON.Observable}
  17901. */
  17902. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17903. /**
  17904. * An event triggered when physic simulation is about to be run
  17905. * @type {BABYLON.Observable}
  17906. */
  17907. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17908. /**
  17909. * An event triggered when physic simulation has been done
  17910. * @type {BABYLON.Observable}
  17911. */
  17912. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17913. /**
  17914. * An event triggered when the scene is ready
  17915. * @type {BABYLON.Observable}
  17916. */
  17917. this.onReadyObservable = new BABYLON.Observable();
  17918. /**
  17919. * An event triggered before rendering a camera
  17920. * @type {BABYLON.Observable}
  17921. */
  17922. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17923. /**
  17924. * An event triggered after rendering a camera
  17925. * @type {BABYLON.Observable}
  17926. */
  17927. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17928. /**
  17929. * An event triggered when active meshes evaluation is about to start
  17930. * @type {BABYLON.Observable}
  17931. */
  17932. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17933. /**
  17934. * An event triggered when active meshes evaluation is done
  17935. * @type {BABYLON.Observable}
  17936. */
  17937. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17938. /**
  17939. * An event triggered when particles rendering is about to start
  17940. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17941. * @type {BABYLON.Observable}
  17942. */
  17943. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17944. /**
  17945. * An event triggered when particles rendering is done
  17946. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17947. * @type {BABYLON.Observable}
  17948. */
  17949. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17950. /**
  17951. * An event triggered when sprites rendering is about to start
  17952. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17953. * @type {BABYLON.Observable}
  17954. */
  17955. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17956. /**
  17957. * An event triggered when sprites rendering is done
  17958. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17959. * @type {BABYLON.Observable}
  17960. */
  17961. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17962. /**
  17963. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17964. * @type {BABYLON.Observable}
  17965. */
  17966. this.onDataLoadedObservable = new BABYLON.Observable();
  17967. /**
  17968. * An event triggered when a camera is created
  17969. * @type {BABYLON.Observable}
  17970. */
  17971. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17972. /**
  17973. * An event triggered when a camera is removed
  17974. * @type {BABYLON.Observable}
  17975. */
  17976. this.onCameraRemovedObservable = new BABYLON.Observable();
  17977. /**
  17978. * An event triggered when a light is created
  17979. * @type {BABYLON.Observable}
  17980. */
  17981. this.onNewLightAddedObservable = new BABYLON.Observable();
  17982. /**
  17983. * An event triggered when a light is removed
  17984. * @type {BABYLON.Observable}
  17985. */
  17986. this.onLightRemovedObservable = new BABYLON.Observable();
  17987. /**
  17988. * An event triggered when a geometry is created
  17989. * @type {BABYLON.Observable}
  17990. */
  17991. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17992. /**
  17993. * An event triggered when a geometry is removed
  17994. * @type {BABYLON.Observable}
  17995. */
  17996. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17997. /**
  17998. * An event triggered when a transform node is created
  17999. * @type {BABYLON.Observable}
  18000. */
  18001. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18002. /**
  18003. * An event triggered when a transform node is removed
  18004. * @type {BABYLON.Observable}
  18005. */
  18006. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18007. /**
  18008. * An event triggered when a mesh is created
  18009. * @type {BABYLON.Observable}
  18010. */
  18011. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18012. /**
  18013. * An event triggered when a mesh is removed
  18014. * @type {BABYLON.Observable}
  18015. */
  18016. this.onMeshRemovedObservable = new BABYLON.Observable();
  18017. /**
  18018. * An event triggered when render targets are about to be rendered
  18019. * Can happen multiple times per frame.
  18020. * @type {BABYLON.Observable}
  18021. */
  18022. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18023. /**
  18024. * An event triggered when render targets were rendered.
  18025. * Can happen multiple times per frame.
  18026. * @type {BABYLON.Observable}
  18027. */
  18028. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18029. /**
  18030. * An event triggered before calculating deterministic simulation step
  18031. * @type {BABYLON.Observable}
  18032. */
  18033. this.onBeforeStepObservable = new BABYLON.Observable();
  18034. /**
  18035. * An event triggered after calculating deterministic simulation step
  18036. * @type {BABYLON.Observable}
  18037. */
  18038. this.onAfterStepObservable = new BABYLON.Observable();
  18039. /**
  18040. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18041. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18042. * 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)
  18043. */
  18044. this.onRenderingGroupObservable = new BABYLON.Observable();
  18045. // Animations
  18046. this.animations = [];
  18047. /**
  18048. * 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).
  18049. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18050. */
  18051. this.onPrePointerObservable = new BABYLON.Observable();
  18052. /**
  18053. * Observable event triggered each time an input event is received from the rendering canvas
  18054. */
  18055. this.onPointerObservable = new BABYLON.Observable();
  18056. this._meshPickProceed = false;
  18057. this._currentPickResult = null;
  18058. this._previousPickResult = null;
  18059. this._totalPointersPressed = 0;
  18060. this._doubleClickOccured = false;
  18061. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18062. this.cameraToUseForPointers = null;
  18063. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18064. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18065. this._startingPointerTime = 0;
  18066. this._previousStartingPointerTime = 0;
  18067. // Deterministic lockstep
  18068. this._timeAccumulator = 0;
  18069. this._currentStepId = 0;
  18070. this._currentInternalStep = 0;
  18071. // Keyboard
  18072. /**
  18073. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18074. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18075. */
  18076. this.onPreKeyboardObservable = new BABYLON.Observable();
  18077. /**
  18078. * Observable event triggered each time an keyboard event is received from the hosting window
  18079. */
  18080. this.onKeyboardObservable = new BABYLON.Observable();
  18081. // Coordinate system
  18082. /**
  18083. * use right-handed coordinate system on this scene.
  18084. * @type {boolean}
  18085. */
  18086. this._useRightHandedSystem = false;
  18087. // Fog
  18088. this._fogEnabled = true;
  18089. this._fogMode = Scene.FOGMODE_NONE;
  18090. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18091. this.fogDensity = 0.1;
  18092. this.fogStart = 0;
  18093. this.fogEnd = 1000.0;
  18094. // Lights
  18095. /**
  18096. * is shadow enabled on this scene.
  18097. * @type {boolean}
  18098. */
  18099. this._shadowsEnabled = true;
  18100. /**
  18101. * is light enabled on this scene.
  18102. * @type {boolean}
  18103. */
  18104. this._lightsEnabled = true;
  18105. /**
  18106. * All of the lights added to this scene.
  18107. * @see BABYLON.Light
  18108. * @type {BABYLON.Light[]}
  18109. */
  18110. this.lights = new Array();
  18111. // Cameras
  18112. /** All of the cameras added to this scene. */
  18113. this.cameras = new Array();
  18114. /** All of the active cameras added to this scene. */
  18115. this.activeCameras = new Array();
  18116. // Meshes
  18117. /**
  18118. * All of the tranform nodes added to this scene.
  18119. * @see BABYLON.TransformNode
  18120. * @type {BABYLON.TransformNode[]}
  18121. */
  18122. this.transformNodes = new Array();
  18123. /**
  18124. * All of the (abstract) meshes added to this scene.
  18125. * @see BABYLON.AbstractMesh
  18126. * @type {BABYLON.AbstractMesh[]}
  18127. */
  18128. this.meshes = new Array();
  18129. // Geometries
  18130. this._geometries = new Array();
  18131. this.materials = new Array();
  18132. this.multiMaterials = new Array();
  18133. // Textures
  18134. this._texturesEnabled = true;
  18135. this.textures = new Array();
  18136. // Particles
  18137. this.particlesEnabled = true;
  18138. this.particleSystems = new Array();
  18139. // Sprites
  18140. this.spritesEnabled = true;
  18141. this.spriteManagers = new Array();
  18142. // Layers
  18143. this.layers = new Array();
  18144. this.highlightLayers = new Array();
  18145. // Skeletons
  18146. this._skeletonsEnabled = true;
  18147. this.skeletons = new Array();
  18148. // Morph targets
  18149. this.morphTargetManagers = new Array();
  18150. // Lens flares
  18151. this.lensFlaresEnabled = true;
  18152. this.lensFlareSystems = new Array();
  18153. // Collisions
  18154. this.collisionsEnabled = true;
  18155. /** Defines the gravity applied to this scene */
  18156. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18157. // Postprocesses
  18158. this.postProcesses = new Array();
  18159. this.postProcessesEnabled = true;
  18160. // Customs render targets
  18161. this.renderTargetsEnabled = true;
  18162. this.dumpNextRenderTargets = false;
  18163. this.customRenderTargets = new Array();
  18164. // Imported meshes
  18165. this.importedMeshesFiles = new Array();
  18166. // Probes
  18167. this.probesEnabled = true;
  18168. this.reflectionProbes = new Array();
  18169. this._actionManagers = new Array();
  18170. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18171. // Procedural textures
  18172. this.proceduralTexturesEnabled = true;
  18173. this._proceduralTextures = new Array();
  18174. this.soundTracks = new Array();
  18175. this._audioEnabled = true;
  18176. this._headphone = false;
  18177. // Performance counters
  18178. this._totalVertices = new BABYLON.PerfCounter();
  18179. this._activeIndices = new BABYLON.PerfCounter();
  18180. this._activeParticles = new BABYLON.PerfCounter();
  18181. this._activeBones = new BABYLON.PerfCounter();
  18182. this._animationTime = 0;
  18183. this.animationTimeScale = 1;
  18184. this._renderId = 0;
  18185. this._executeWhenReadyTimeoutId = -1;
  18186. this._intermediateRendering = false;
  18187. this._viewUpdateFlag = -1;
  18188. this._projectionUpdateFlag = -1;
  18189. this._alternateViewUpdateFlag = -1;
  18190. this._alternateProjectionUpdateFlag = -1;
  18191. this._toBeDisposed = new BABYLON.SmartArray(256);
  18192. this._pendingData = new Array();
  18193. this._isDisposed = false;
  18194. this._activeMeshes = new BABYLON.SmartArray(256);
  18195. this._processedMaterials = new BABYLON.SmartArray(256);
  18196. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18197. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18198. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18199. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18200. this._activeAnimatables = new Array();
  18201. this._transformMatrix = BABYLON.Matrix.Zero();
  18202. this._useAlternateCameraConfiguration = false;
  18203. this._alternateRendering = false;
  18204. this.requireLightSorting = false;
  18205. this._activeMeshesFrozen = false;
  18206. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18207. this._engine.scenes.push(this);
  18208. this._uid = null;
  18209. this._renderingManager = new BABYLON.RenderingManager(this);
  18210. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18211. if (BABYLON.OutlineRenderer) {
  18212. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18213. }
  18214. if (BABYLON.Tools.IsWindowObjectExist()) {
  18215. this.attachControl();
  18216. }
  18217. //simplification queue
  18218. if (BABYLON.SimplificationQueue) {
  18219. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18220. }
  18221. //collision coordinator initialization. For now legacy per default.
  18222. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18223. // Uniform Buffer
  18224. this._createUbo();
  18225. // Default Image processing definition.
  18226. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18227. }
  18228. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18229. /** The fog is deactivated */
  18230. get: function () {
  18231. return Scene._FOGMODE_NONE;
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18237. /** The fog density is following an exponential function */
  18238. get: function () {
  18239. return Scene._FOGMODE_EXP;
  18240. },
  18241. enumerable: true,
  18242. configurable: true
  18243. });
  18244. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18245. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18246. get: function () {
  18247. return Scene._FOGMODE_EXP2;
  18248. },
  18249. enumerable: true,
  18250. configurable: true
  18251. });
  18252. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18253. /** The fog density is following a linear function. */
  18254. get: function () {
  18255. return Scene._FOGMODE_LINEAR;
  18256. },
  18257. enumerable: true,
  18258. configurable: true
  18259. });
  18260. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18261. /**
  18262. * Texture used in all pbr material as the reflection texture.
  18263. * As in the majority of the scene they are the same (exception for multi room and so on),
  18264. * this is easier to reference from here than from all the materials.
  18265. */
  18266. get: function () {
  18267. return this._environmentTexture;
  18268. },
  18269. /**
  18270. * Texture used in all pbr material as the reflection texture.
  18271. * As in the majority of the scene they are the same (exception for multi room and so on),
  18272. * this is easier to set here than in all the materials.
  18273. */
  18274. set: function (value) {
  18275. if (this._environmentTexture === value) {
  18276. return;
  18277. }
  18278. this._environmentTexture = value;
  18279. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18280. },
  18281. enumerable: true,
  18282. configurable: true
  18283. });
  18284. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18285. /**
  18286. * Default image processing configuration used either in the rendering
  18287. * Forward main pass or through the imageProcessingPostProcess if present.
  18288. * As in the majority of the scene they are the same (exception for multi camera),
  18289. * this is easier to reference from here than from all the materials and post process.
  18290. *
  18291. * No setter as we it is a shared configuration, you can set the values instead.
  18292. */
  18293. get: function () {
  18294. return this._imageProcessingConfiguration;
  18295. },
  18296. enumerable: true,
  18297. configurable: true
  18298. });
  18299. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18300. get: function () {
  18301. return this._forcePointsCloud;
  18302. },
  18303. set: function (value) {
  18304. if (this._forcePointsCloud === value) {
  18305. return;
  18306. }
  18307. this._forcePointsCloud = value;
  18308. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18309. },
  18310. enumerable: true,
  18311. configurable: true
  18312. });
  18313. Object.defineProperty(Scene.prototype, "onDispose", {
  18314. /** A function to be executed when this scene is disposed. */
  18315. set: function (callback) {
  18316. if (this._onDisposeObserver) {
  18317. this.onDisposeObservable.remove(this._onDisposeObserver);
  18318. }
  18319. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. Object.defineProperty(Scene.prototype, "beforeRender", {
  18325. /** A function to be executed before rendering this scene */
  18326. set: function (callback) {
  18327. if (this._onBeforeRenderObserver) {
  18328. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18329. }
  18330. if (callback) {
  18331. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18332. }
  18333. },
  18334. enumerable: true,
  18335. configurable: true
  18336. });
  18337. Object.defineProperty(Scene.prototype, "afterRender", {
  18338. /** A function to be executed after rendering this scene */
  18339. set: function (callback) {
  18340. if (this._onAfterRenderObserver) {
  18341. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18342. }
  18343. if (callback) {
  18344. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18345. }
  18346. },
  18347. enumerable: true,
  18348. configurable: true
  18349. });
  18350. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18351. set: function (callback) {
  18352. if (this._onBeforeCameraRenderObserver) {
  18353. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18354. }
  18355. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18361. set: function (callback) {
  18362. if (this._onAfterCameraRenderObserver) {
  18363. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18364. }
  18365. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18371. get: function () {
  18372. if (!this._gamepadManager) {
  18373. this._gamepadManager = new BABYLON.GamepadManager();
  18374. }
  18375. return this._gamepadManager;
  18376. },
  18377. enumerable: true,
  18378. configurable: true
  18379. });
  18380. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18381. get: function () {
  18382. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18383. },
  18384. enumerable: true,
  18385. configurable: true
  18386. });
  18387. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18388. get: function () {
  18389. return this._useRightHandedSystem;
  18390. },
  18391. set: function (value) {
  18392. if (this._useRightHandedSystem === value) {
  18393. return;
  18394. }
  18395. this._useRightHandedSystem = value;
  18396. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. Scene.prototype.setStepId = function (newStepId) {
  18402. this._currentStepId = newStepId;
  18403. };
  18404. ;
  18405. Scene.prototype.getStepId = function () {
  18406. return this._currentStepId;
  18407. };
  18408. ;
  18409. Scene.prototype.getInternalStep = function () {
  18410. return this._currentInternalStep;
  18411. };
  18412. ;
  18413. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18414. get: function () {
  18415. return this._fogEnabled;
  18416. },
  18417. /**
  18418. * is fog enabled on this scene.
  18419. */
  18420. set: function (value) {
  18421. if (this._fogEnabled === value) {
  18422. return;
  18423. }
  18424. this._fogEnabled = value;
  18425. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Object.defineProperty(Scene.prototype, "fogMode", {
  18431. get: function () {
  18432. return this._fogMode;
  18433. },
  18434. set: function (value) {
  18435. if (this._fogMode === value) {
  18436. return;
  18437. }
  18438. this._fogMode = value;
  18439. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18445. get: function () {
  18446. return this._shadowsEnabled;
  18447. },
  18448. set: function (value) {
  18449. if (this._shadowsEnabled === value) {
  18450. return;
  18451. }
  18452. this._shadowsEnabled = value;
  18453. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18454. },
  18455. enumerable: true,
  18456. configurable: true
  18457. });
  18458. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18459. get: function () {
  18460. return this._lightsEnabled;
  18461. },
  18462. set: function (value) {
  18463. if (this._lightsEnabled === value) {
  18464. return;
  18465. }
  18466. this._lightsEnabled = value;
  18467. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18473. /** The default material used on meshes when no material is affected */
  18474. get: function () {
  18475. if (!this._defaultMaterial) {
  18476. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18477. }
  18478. return this._defaultMaterial;
  18479. },
  18480. /** The default material used on meshes when no material is affected */
  18481. set: function (value) {
  18482. this._defaultMaterial = value;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18488. get: function () {
  18489. return this._texturesEnabled;
  18490. },
  18491. set: function (value) {
  18492. if (this._texturesEnabled === value) {
  18493. return;
  18494. }
  18495. this._texturesEnabled = value;
  18496. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18502. get: function () {
  18503. return this._skeletonsEnabled;
  18504. },
  18505. set: function (value) {
  18506. if (this._skeletonsEnabled === value) {
  18507. return;
  18508. }
  18509. this._skeletonsEnabled = value;
  18510. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18516. get: function () {
  18517. if (!this._postProcessRenderPipelineManager) {
  18518. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18519. }
  18520. return this._postProcessRenderPipelineManager;
  18521. },
  18522. enumerable: true,
  18523. configurable: true
  18524. });
  18525. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18526. get: function () {
  18527. if (!this._mainSoundTrack) {
  18528. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18529. }
  18530. return this._mainSoundTrack;
  18531. },
  18532. enumerable: true,
  18533. configurable: true
  18534. });
  18535. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18536. get: function () {
  18537. return this._alternateRendering;
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18543. get: function () {
  18544. return this._frustumPlanes;
  18545. },
  18546. enumerable: true,
  18547. configurable: true
  18548. });
  18549. Object.defineProperty(Scene.prototype, "debugLayer", {
  18550. // Properties
  18551. get: function () {
  18552. if (!this._debugLayer) {
  18553. this._debugLayer = new BABYLON.DebugLayer(this);
  18554. }
  18555. return this._debugLayer;
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18561. get: function () {
  18562. return this._workerCollisions;
  18563. },
  18564. set: function (enabled) {
  18565. if (!BABYLON.CollisionCoordinatorLegacy) {
  18566. return;
  18567. }
  18568. enabled = (enabled && !!Worker);
  18569. this._workerCollisions = enabled;
  18570. if (this.collisionCoordinator) {
  18571. this.collisionCoordinator.destroy();
  18572. }
  18573. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18574. this.collisionCoordinator.init(this);
  18575. },
  18576. enumerable: true,
  18577. configurable: true
  18578. });
  18579. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18580. get: function () {
  18581. return this._selectionOctree;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18587. /**
  18588. * The mesh that is currently under the pointer.
  18589. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18590. */
  18591. get: function () {
  18592. return this._pointerOverMesh;
  18593. },
  18594. enumerable: true,
  18595. configurable: true
  18596. });
  18597. Object.defineProperty(Scene.prototype, "pointerX", {
  18598. /**
  18599. * Current on-screen X position of the pointer
  18600. * @return {number} X position of the pointer
  18601. */
  18602. get: function () {
  18603. return this._pointerX;
  18604. },
  18605. enumerable: true,
  18606. configurable: true
  18607. });
  18608. Object.defineProperty(Scene.prototype, "pointerY", {
  18609. /**
  18610. * Current on-screen Y position of the pointer
  18611. * @return {number} Y position of the pointer
  18612. */
  18613. get: function () {
  18614. return this._pointerY;
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Scene.prototype.getCachedMaterial = function () {
  18620. return this._cachedMaterial;
  18621. };
  18622. Scene.prototype.getCachedEffect = function () {
  18623. return this._cachedEffect;
  18624. };
  18625. Scene.prototype.getCachedVisibility = function () {
  18626. return this._cachedVisibility;
  18627. };
  18628. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18629. if (visibility === void 0) { visibility = 1; }
  18630. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18631. };
  18632. Scene.prototype.getBoundingBoxRenderer = function () {
  18633. if (!this._boundingBoxRenderer) {
  18634. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18635. }
  18636. return this._boundingBoxRenderer;
  18637. };
  18638. Scene.prototype.getOutlineRenderer = function () {
  18639. return this._outlineRenderer;
  18640. };
  18641. Scene.prototype.getEngine = function () {
  18642. return this._engine;
  18643. };
  18644. Scene.prototype.getTotalVertices = function () {
  18645. return this._totalVertices.current;
  18646. };
  18647. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18648. get: function () {
  18649. return this._totalVertices;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. Scene.prototype.getActiveIndices = function () {
  18655. return this._activeIndices.current;
  18656. };
  18657. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18658. get: function () {
  18659. return this._activeIndices;
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. Scene.prototype.getActiveParticles = function () {
  18665. return this._activeParticles.current;
  18666. };
  18667. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18668. get: function () {
  18669. return this._activeParticles;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Scene.prototype.getActiveBones = function () {
  18675. return this._activeBones.current;
  18676. };
  18677. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18678. get: function () {
  18679. return this._activeBones;
  18680. },
  18681. enumerable: true,
  18682. configurable: true
  18683. });
  18684. // Stats
  18685. Scene.prototype.getInterFramePerfCounter = function () {
  18686. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18687. return 0;
  18688. };
  18689. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18690. get: function () {
  18691. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18692. return null;
  18693. },
  18694. enumerable: true,
  18695. configurable: true
  18696. });
  18697. Scene.prototype.getLastFrameDuration = function () {
  18698. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18699. return 0;
  18700. };
  18701. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18702. get: function () {
  18703. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18704. return null;
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18710. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18711. return 0;
  18712. };
  18713. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18714. get: function () {
  18715. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18716. return null;
  18717. },
  18718. enumerable: true,
  18719. configurable: true
  18720. });
  18721. Scene.prototype.getActiveMeshes = function () {
  18722. return this._activeMeshes;
  18723. };
  18724. Scene.prototype.getRenderTargetsDuration = function () {
  18725. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18726. return 0;
  18727. };
  18728. Scene.prototype.getRenderDuration = function () {
  18729. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18730. return 0;
  18731. };
  18732. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18733. get: function () {
  18734. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18735. return null;
  18736. },
  18737. enumerable: true,
  18738. configurable: true
  18739. });
  18740. Scene.prototype.getParticlesDuration = function () {
  18741. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18742. return 0;
  18743. };
  18744. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18745. get: function () {
  18746. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18747. return null;
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. Scene.prototype.getSpritesDuration = function () {
  18753. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18754. return 0;
  18755. };
  18756. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18757. get: function () {
  18758. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18759. return null;
  18760. },
  18761. enumerable: true,
  18762. configurable: true
  18763. });
  18764. Scene.prototype.getAnimationRatio = function () {
  18765. return this._animationRatio;
  18766. };
  18767. Scene.prototype.getRenderId = function () {
  18768. return this._renderId;
  18769. };
  18770. Scene.prototype.incrementRenderId = function () {
  18771. this._renderId++;
  18772. };
  18773. Scene.prototype._updatePointerPosition = function (evt) {
  18774. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18775. if (!canvasRect) {
  18776. return;
  18777. }
  18778. this._pointerX = evt.clientX - canvasRect.left;
  18779. this._pointerY = evt.clientY - canvasRect.top;
  18780. this._unTranslatedPointerX = this._pointerX;
  18781. this._unTranslatedPointerY = this._pointerY;
  18782. };
  18783. Scene.prototype._createUbo = function () {
  18784. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18785. this._sceneUbo.addUniform("viewProjection", 16);
  18786. this._sceneUbo.addUniform("view", 16);
  18787. };
  18788. Scene.prototype._createAlternateUbo = function () {
  18789. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18790. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18791. this._alternateSceneUbo.addUniform("view", 16);
  18792. };
  18793. // Pointers handling
  18794. /**
  18795. * Use this method to simulate a pointer move on a mesh
  18796. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18797. */
  18798. Scene.prototype.simulatePointerMove = function (pickResult) {
  18799. var evt = new PointerEvent("pointermove");
  18800. return this._processPointerMove(pickResult, evt);
  18801. };
  18802. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18803. var canvas = this._engine.getRenderingCanvas();
  18804. if (!canvas) {
  18805. return this;
  18806. }
  18807. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18808. this.setPointerOverSprite(null);
  18809. this.setPointerOverMesh(pickResult.pickedMesh);
  18810. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18811. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18812. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18813. }
  18814. else {
  18815. canvas.style.cursor = this.hoverCursor;
  18816. }
  18817. }
  18818. else {
  18819. canvas.style.cursor = this.defaultCursor;
  18820. }
  18821. }
  18822. else {
  18823. this.setPointerOverMesh(null);
  18824. // Sprites
  18825. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18826. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18827. this.setPointerOverSprite(pickResult.pickedSprite);
  18828. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18829. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18830. }
  18831. else {
  18832. canvas.style.cursor = this.hoverCursor;
  18833. }
  18834. }
  18835. else {
  18836. this.setPointerOverSprite(null);
  18837. // Restore pointer
  18838. canvas.style.cursor = this.defaultCursor;
  18839. }
  18840. }
  18841. if (pickResult) {
  18842. if (this.onPointerMove) {
  18843. this.onPointerMove(evt, pickResult);
  18844. }
  18845. if (this.onPointerObservable.hasObservers()) {
  18846. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18847. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18848. this.onPointerObservable.notifyObservers(pi, type);
  18849. }
  18850. }
  18851. return this;
  18852. };
  18853. /**
  18854. * Use this method to simulate a pointer down on a mesh
  18855. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18856. */
  18857. Scene.prototype.simulatePointerDown = function (pickResult) {
  18858. var evt = new PointerEvent("pointerdown");
  18859. return this._processPointerDown(pickResult, evt);
  18860. };
  18861. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18862. var _this = this;
  18863. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18864. this._pickedDownMesh = pickResult.pickedMesh;
  18865. var actionManager = pickResult.pickedMesh.actionManager;
  18866. if (actionManager) {
  18867. if (actionManager.hasPickTriggers) {
  18868. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18869. switch (evt.button) {
  18870. case 0:
  18871. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18872. break;
  18873. case 1:
  18874. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18875. break;
  18876. case 2:
  18877. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18878. break;
  18879. }
  18880. }
  18881. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18882. window.setTimeout(function () {
  18883. 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);
  18884. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18885. if (_this._totalPointersPressed !== 0 &&
  18886. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18887. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18888. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18889. _this._startingPointerTime = 0;
  18890. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18891. }
  18892. }
  18893. }, Scene.LongPressDelay);
  18894. }
  18895. }
  18896. }
  18897. if (pickResult) {
  18898. if (this.onPointerDown) {
  18899. this.onPointerDown(evt, pickResult);
  18900. }
  18901. if (this.onPointerObservable.hasObservers()) {
  18902. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18903. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18904. this.onPointerObservable.notifyObservers(pi, type);
  18905. }
  18906. }
  18907. return this;
  18908. };
  18909. /**
  18910. * Use this method to simulate a pointer up on a mesh
  18911. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18912. */
  18913. Scene.prototype.simulatePointerUp = function (pickResult) {
  18914. var evt = new PointerEvent("pointerup");
  18915. var clickInfo = new ClickInfo();
  18916. clickInfo.singleClick = true;
  18917. return this._processPointerUp(pickResult, evt, clickInfo);
  18918. };
  18919. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18920. if (pickResult && pickResult && pickResult.pickedMesh) {
  18921. this._pickedUpMesh = pickResult.pickedMesh;
  18922. if (this._pickedDownMesh === this._pickedUpMesh) {
  18923. if (this.onPointerPick) {
  18924. this.onPointerPick(evt, pickResult);
  18925. }
  18926. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18927. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18928. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18929. this.onPointerObservable.notifyObservers(pi, type);
  18930. }
  18931. }
  18932. if (pickResult.pickedMesh.actionManager) {
  18933. if (clickInfo.ignore) {
  18934. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18935. }
  18936. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18937. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18938. }
  18939. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18940. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18941. }
  18942. }
  18943. }
  18944. if (this._pickedDownMesh &&
  18945. this._pickedDownMesh.actionManager &&
  18946. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18947. this._pickedDownMesh !== this._pickedUpMesh) {
  18948. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18949. }
  18950. if (this.onPointerUp) {
  18951. this.onPointerUp(evt, pickResult);
  18952. }
  18953. if (this.onPointerObservable.hasObservers()) {
  18954. if (!clickInfo.ignore) {
  18955. if (!clickInfo.hasSwiped) {
  18956. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18957. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18958. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18959. this.onPointerObservable.notifyObservers(pi, type);
  18960. }
  18961. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18962. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18963. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18964. this.onPointerObservable.notifyObservers(pi, type);
  18965. }
  18966. }
  18967. }
  18968. else {
  18969. var type = BABYLON.PointerEventTypes.POINTERUP;
  18970. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18971. this.onPointerObservable.notifyObservers(pi, type);
  18972. }
  18973. }
  18974. return this;
  18975. };
  18976. /**
  18977. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18978. * @param attachUp defines if you want to attach events to pointerup
  18979. * @param attachDown defines if you want to attach events to pointerdown
  18980. * @param attachMove defines if you want to attach events to pointermove
  18981. */
  18982. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18983. var _this = this;
  18984. if (attachUp === void 0) { attachUp = true; }
  18985. if (attachDown === void 0) { attachDown = true; }
  18986. if (attachMove === void 0) { attachMove = true; }
  18987. this._initActionManager = function (act, clickInfo) {
  18988. if (!_this._meshPickProceed) {
  18989. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18990. _this._currentPickResult = pickResult;
  18991. if (pickResult) {
  18992. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18993. }
  18994. _this._meshPickProceed = true;
  18995. }
  18996. return act;
  18997. };
  18998. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18999. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19000. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19001. btn !== _this._previousButtonPressed) {
  19002. _this._doubleClickOccured = false;
  19003. clickInfo.singleClick = true;
  19004. clickInfo.ignore = false;
  19005. cb(clickInfo, _this._currentPickResult);
  19006. }
  19007. };
  19008. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19009. var clickInfo = new ClickInfo();
  19010. _this._currentPickResult = null;
  19011. var act = null;
  19012. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19013. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19014. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19015. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19016. act = _this._initActionManager(act, clickInfo);
  19017. if (act)
  19018. checkPicking = act.hasPickTriggers;
  19019. }
  19020. if (checkPicking) {
  19021. var btn = evt.button;
  19022. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19023. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19024. if (!clickInfo.hasSwiped) {
  19025. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19026. if (!checkSingleClickImmediately) {
  19027. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19028. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19029. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19030. act = _this._initActionManager(act, clickInfo);
  19031. if (act)
  19032. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19033. }
  19034. }
  19035. if (checkSingleClickImmediately) {
  19036. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19037. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19038. btn !== _this._previousButtonPressed) {
  19039. clickInfo.singleClick = true;
  19040. cb(clickInfo, _this._currentPickResult);
  19041. }
  19042. }
  19043. else {
  19044. // wait that no double click has been raised during the double click delay
  19045. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19046. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19047. }
  19048. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19049. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19050. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19051. act = _this._initActionManager(act, clickInfo);
  19052. if (act)
  19053. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19054. }
  19055. if (checkDoubleClick) {
  19056. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19057. if (btn === _this._previousButtonPressed &&
  19058. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19059. !_this._doubleClickOccured) {
  19060. // pointer has not moved for 2 clicks, it's a double click
  19061. if (!clickInfo.hasSwiped &&
  19062. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19063. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19064. _this._previousStartingPointerTime = 0;
  19065. _this._doubleClickOccured = true;
  19066. clickInfo.doubleClick = true;
  19067. clickInfo.ignore = false;
  19068. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19069. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19070. }
  19071. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19072. cb(clickInfo, _this._currentPickResult);
  19073. }
  19074. else {
  19075. _this._doubleClickOccured = false;
  19076. _this._previousStartingPointerTime = _this._startingPointerTime;
  19077. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19078. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19079. _this._previousButtonPressed = btn;
  19080. if (Scene.ExclusiveDoubleClickMode) {
  19081. if (_this._previousDelayedSimpleClickTimeout) {
  19082. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19083. }
  19084. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19085. cb(clickInfo, _this._previousPickResult);
  19086. }
  19087. else {
  19088. cb(clickInfo, _this._currentPickResult);
  19089. }
  19090. }
  19091. }
  19092. else {
  19093. _this._doubleClickOccured = false;
  19094. _this._previousStartingPointerTime = _this._startingPointerTime;
  19095. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19096. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19097. _this._previousButtonPressed = btn;
  19098. }
  19099. }
  19100. }
  19101. }
  19102. clickInfo.ignore = true;
  19103. cb(clickInfo, _this._currentPickResult);
  19104. };
  19105. this._spritePredicate = function (sprite) {
  19106. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19107. };
  19108. this._onPointerMove = function (evt) {
  19109. _this._updatePointerPosition(evt);
  19110. // PreObservable support
  19111. if (_this.onPrePointerObservable.hasObservers()) {
  19112. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19113. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19114. _this.onPrePointerObservable.notifyObservers(pi, type);
  19115. if (pi.skipOnPointerObservable) {
  19116. return;
  19117. }
  19118. }
  19119. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19120. return;
  19121. }
  19122. if (!_this.pointerMovePredicate) {
  19123. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19124. }
  19125. // Meshes
  19126. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19127. _this._processPointerMove(pickResult, evt);
  19128. };
  19129. this._onPointerDown = function (evt) {
  19130. _this._totalPointersPressed++;
  19131. _this._pickedDownMesh = null;
  19132. _this._meshPickProceed = false;
  19133. _this._updatePointerPosition(evt);
  19134. if (_this.preventDefaultOnPointerDown && canvas) {
  19135. evt.preventDefault();
  19136. canvas.focus();
  19137. }
  19138. // PreObservable support
  19139. if (_this.onPrePointerObservable.hasObservers()) {
  19140. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19141. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19142. _this.onPrePointerObservable.notifyObservers(pi, type);
  19143. if (pi.skipOnPointerObservable) {
  19144. return;
  19145. }
  19146. }
  19147. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19148. return;
  19149. }
  19150. _this._startingPointerPosition.x = _this._pointerX;
  19151. _this._startingPointerPosition.y = _this._pointerY;
  19152. _this._startingPointerTime = new Date().getTime();
  19153. if (!_this.pointerDownPredicate) {
  19154. _this.pointerDownPredicate = function (mesh) {
  19155. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19156. };
  19157. }
  19158. // Meshes
  19159. _this._pickedDownMesh = null;
  19160. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19161. _this._processPointerDown(pickResult, evt);
  19162. // Sprites
  19163. _this._pickedDownSprite = null;
  19164. if (_this.spriteManagers.length > 0) {
  19165. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19166. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19167. if (pickResult.pickedSprite.actionManager) {
  19168. _this._pickedDownSprite = pickResult.pickedSprite;
  19169. switch (evt.button) {
  19170. case 0:
  19171. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19172. break;
  19173. case 1:
  19174. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19175. break;
  19176. case 2:
  19177. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19178. break;
  19179. }
  19180. if (pickResult.pickedSprite.actionManager) {
  19181. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19182. }
  19183. }
  19184. }
  19185. }
  19186. };
  19187. this._onPointerUp = function (evt) {
  19188. if (_this._totalPointersPressed === 0) {
  19189. return; // So we need to test it the pointer down was pressed before.
  19190. }
  19191. _this._totalPointersPressed--;
  19192. _this._pickedUpMesh = null;
  19193. _this._meshPickProceed = false;
  19194. _this._updatePointerPosition(evt);
  19195. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19196. // PreObservable support
  19197. if (_this.onPrePointerObservable.hasObservers()) {
  19198. if (!clickInfo.ignore) {
  19199. if (!clickInfo.hasSwiped) {
  19200. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19201. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19202. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19203. _this.onPrePointerObservable.notifyObservers(pi, type);
  19204. if (pi.skipOnPointerObservable) {
  19205. return;
  19206. }
  19207. }
  19208. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19209. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19210. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19211. _this.onPrePointerObservable.notifyObservers(pi, type);
  19212. if (pi.skipOnPointerObservable) {
  19213. return;
  19214. }
  19215. }
  19216. }
  19217. }
  19218. else {
  19219. var type = BABYLON.PointerEventTypes.POINTERUP;
  19220. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19221. _this.onPrePointerObservable.notifyObservers(pi, type);
  19222. if (pi.skipOnPointerObservable) {
  19223. return;
  19224. }
  19225. }
  19226. }
  19227. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19228. return;
  19229. }
  19230. if (!_this.pointerUpPredicate) {
  19231. _this.pointerUpPredicate = function (mesh) {
  19232. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19233. };
  19234. }
  19235. // Meshes
  19236. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19237. _this._initActionManager(null, clickInfo);
  19238. }
  19239. if (!pickResult) {
  19240. pickResult = _this._currentPickResult;
  19241. }
  19242. _this._processPointerUp(pickResult, evt, clickInfo);
  19243. // Sprites
  19244. if (_this.spriteManagers.length > 0) {
  19245. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19246. if (spritePickResult) {
  19247. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19248. if (spritePickResult.pickedSprite.actionManager) {
  19249. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19250. if (spritePickResult.pickedSprite.actionManager) {
  19251. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19252. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19253. }
  19254. }
  19255. }
  19256. }
  19257. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19258. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19259. }
  19260. }
  19261. }
  19262. _this._previousPickResult = _this._currentPickResult;
  19263. });
  19264. };
  19265. this._onKeyDown = function (evt) {
  19266. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19267. if (_this.onPreKeyboardObservable.hasObservers()) {
  19268. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19269. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19270. if (pi.skipOnPointerObservable) {
  19271. return;
  19272. }
  19273. }
  19274. if (_this.onKeyboardObservable.hasObservers()) {
  19275. var pi = new BABYLON.KeyboardInfo(type, evt);
  19276. _this.onKeyboardObservable.notifyObservers(pi, type);
  19277. }
  19278. if (_this.actionManager) {
  19279. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19280. }
  19281. };
  19282. this._onKeyUp = function (evt) {
  19283. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19284. if (_this.onPreKeyboardObservable.hasObservers()) {
  19285. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19286. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19287. if (pi.skipOnPointerObservable) {
  19288. return;
  19289. }
  19290. }
  19291. if (_this.onKeyboardObservable.hasObservers()) {
  19292. var pi = new BABYLON.KeyboardInfo(type, evt);
  19293. _this.onKeyboardObservable.notifyObservers(pi, type);
  19294. }
  19295. if (_this.actionManager) {
  19296. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19297. }
  19298. };
  19299. var engine = this.getEngine();
  19300. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19301. if (!canvas) {
  19302. return;
  19303. }
  19304. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19305. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19306. });
  19307. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19308. if (!canvas) {
  19309. return;
  19310. }
  19311. canvas.removeEventListener("keydown", _this._onKeyDown);
  19312. canvas.removeEventListener("keyup", _this._onKeyUp);
  19313. });
  19314. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19315. var canvas = this._engine.getRenderingCanvas();
  19316. if (!canvas) {
  19317. return;
  19318. }
  19319. if (attachMove) {
  19320. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19321. // Wheel
  19322. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19323. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19324. }
  19325. if (attachDown) {
  19326. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19327. }
  19328. if (attachUp) {
  19329. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19330. }
  19331. canvas.tabIndex = 1;
  19332. };
  19333. Scene.prototype.detachControl = function () {
  19334. var engine = this.getEngine();
  19335. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19336. var canvas = engine.getRenderingCanvas();
  19337. if (!canvas) {
  19338. return;
  19339. }
  19340. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19341. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19342. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19343. if (this._onCanvasBlurObserver) {
  19344. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19345. }
  19346. if (this._onCanvasFocusObserver) {
  19347. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19348. }
  19349. // Wheel
  19350. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19351. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19352. // Keyboard
  19353. canvas.removeEventListener("keydown", this._onKeyDown);
  19354. canvas.removeEventListener("keyup", this._onKeyUp);
  19355. // Observables
  19356. this.onKeyboardObservable.clear();
  19357. this.onPreKeyboardObservable.clear();
  19358. this.onPointerObservable.clear();
  19359. this.onPrePointerObservable.clear();
  19360. };
  19361. // Ready
  19362. Scene.prototype.isReady = function () {
  19363. if (this._isDisposed) {
  19364. return false;
  19365. }
  19366. if (this._pendingData.length > 0) {
  19367. return false;
  19368. }
  19369. var index;
  19370. // Geometries
  19371. for (index = 0; index < this._geometries.length; index++) {
  19372. var geometry = this._geometries[index];
  19373. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19374. return false;
  19375. }
  19376. }
  19377. // Meshes
  19378. for (index = 0; index < this.meshes.length; index++) {
  19379. var mesh = this.meshes[index];
  19380. if (!mesh.isEnabled()) {
  19381. continue;
  19382. }
  19383. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19384. continue;
  19385. }
  19386. if (!mesh.isReady()) {
  19387. return false;
  19388. }
  19389. var mat = mesh.material;
  19390. if (mat) {
  19391. if (!mat.isReady(mesh)) {
  19392. return false;
  19393. }
  19394. }
  19395. }
  19396. return true;
  19397. };
  19398. Scene.prototype.resetCachedMaterial = function () {
  19399. this._cachedMaterial = null;
  19400. this._cachedEffect = null;
  19401. this._cachedVisibility = null;
  19402. };
  19403. Scene.prototype.registerBeforeRender = function (func) {
  19404. this.onBeforeRenderObservable.add(func);
  19405. };
  19406. Scene.prototype.unregisterBeforeRender = function (func) {
  19407. this.onBeforeRenderObservable.removeCallback(func);
  19408. };
  19409. Scene.prototype.registerAfterRender = function (func) {
  19410. this.onAfterRenderObservable.add(func);
  19411. };
  19412. Scene.prototype.unregisterAfterRender = function (func) {
  19413. this.onAfterRenderObservable.removeCallback(func);
  19414. };
  19415. Scene.prototype._addPendingData = function (data) {
  19416. this._pendingData.push(data);
  19417. };
  19418. Scene.prototype._removePendingData = function (data) {
  19419. var wasLoading = this.isLoading;
  19420. var index = this._pendingData.indexOf(data);
  19421. if (index !== -1) {
  19422. this._pendingData.splice(index, 1);
  19423. }
  19424. if (wasLoading && !this.isLoading) {
  19425. this.onDataLoadedObservable.notifyObservers(this);
  19426. }
  19427. };
  19428. Scene.prototype.getWaitingItemsCount = function () {
  19429. return this._pendingData.length;
  19430. };
  19431. Object.defineProperty(Scene.prototype, "isLoading", {
  19432. get: function () {
  19433. return this._pendingData.length > 0;
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. /**
  19439. * Registers a function to be executed when the scene is ready.
  19440. * @param {Function} func - the function to be executed.
  19441. */
  19442. Scene.prototype.executeWhenReady = function (func) {
  19443. var _this = this;
  19444. this.onReadyObservable.add(func);
  19445. if (this._executeWhenReadyTimeoutId !== -1) {
  19446. return;
  19447. }
  19448. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19449. _this._checkIsReady();
  19450. }, 150);
  19451. };
  19452. Scene.prototype._checkIsReady = function () {
  19453. var _this = this;
  19454. if (this.isReady()) {
  19455. this.onReadyObservable.notifyObservers(this);
  19456. this.onReadyObservable.clear();
  19457. this._executeWhenReadyTimeoutId = -1;
  19458. return;
  19459. }
  19460. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19461. _this._checkIsReady();
  19462. }, 150);
  19463. };
  19464. // Animations
  19465. /**
  19466. * Will start the animation sequence of a given target
  19467. * @param target - the target
  19468. * @param {number} from - from which frame should animation start
  19469. * @param {number} to - till which frame should animation run.
  19470. * @param {boolean} [loop] - should the animation loop
  19471. * @param {number} [speedRatio] - the speed in which to run the animation
  19472. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19473. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19474. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19475. * See BABYLON.Animatable
  19476. */
  19477. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19478. if (speedRatio === void 0) { speedRatio = 1.0; }
  19479. if (from > to && speedRatio > 0) {
  19480. speedRatio *= -1;
  19481. }
  19482. this.stopAnimation(target);
  19483. if (!animatable) {
  19484. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19485. }
  19486. // Local animations
  19487. if (target.animations) {
  19488. animatable.appendAnimations(target, target.animations);
  19489. }
  19490. // Children animations
  19491. if (target.getAnimatables) {
  19492. var animatables = target.getAnimatables();
  19493. for (var index = 0; index < animatables.length; index++) {
  19494. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19495. }
  19496. }
  19497. animatable.reset();
  19498. return animatable;
  19499. };
  19500. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19501. if (speedRatio === undefined) {
  19502. speedRatio = 1.0;
  19503. }
  19504. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19505. return animatable;
  19506. };
  19507. Scene.prototype.getAnimatableByTarget = function (target) {
  19508. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19509. if (this._activeAnimatables[index].target === target) {
  19510. return this._activeAnimatables[index];
  19511. }
  19512. }
  19513. return null;
  19514. };
  19515. Object.defineProperty(Scene.prototype, "Animatables", {
  19516. get: function () {
  19517. return this._activeAnimatables;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. /**
  19523. * Will stop the animation of the given target
  19524. * @param target - the target
  19525. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19526. * @see beginAnimation
  19527. */
  19528. Scene.prototype.stopAnimation = function (target, animationName) {
  19529. var animatable = this.getAnimatableByTarget(target);
  19530. if (animatable) {
  19531. animatable.stop(animationName);
  19532. }
  19533. };
  19534. /**
  19535. * Stops and removes all animations that have been applied to the scene
  19536. */
  19537. Scene.prototype.stopAllAnimations = function () {
  19538. if (this._activeAnimatables) {
  19539. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19540. this._activeAnimatables[i].stop();
  19541. }
  19542. this._activeAnimatables = [];
  19543. }
  19544. };
  19545. Scene.prototype._animate = function () {
  19546. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19547. return;
  19548. }
  19549. // Getting time
  19550. var now = BABYLON.Tools.Now;
  19551. if (!this._animationTimeLast) {
  19552. if (this._pendingData.length > 0) {
  19553. return;
  19554. }
  19555. this._animationTimeLast = now;
  19556. }
  19557. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19558. this._animationTime += deltaTime;
  19559. this._animationTimeLast = now;
  19560. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19561. this._activeAnimatables[index]._animate(this._animationTime);
  19562. }
  19563. };
  19564. // Matrix
  19565. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19566. this._useAlternateCameraConfiguration = active;
  19567. };
  19568. Scene.prototype.getViewMatrix = function () {
  19569. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19570. };
  19571. Scene.prototype.getProjectionMatrix = function () {
  19572. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19573. };
  19574. Scene.prototype.getTransformMatrix = function () {
  19575. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19576. };
  19577. Scene.prototype.setTransformMatrix = function (view, projection) {
  19578. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19579. return;
  19580. }
  19581. this._viewUpdateFlag = view.updateFlag;
  19582. this._projectionUpdateFlag = projection.updateFlag;
  19583. this._viewMatrix = view;
  19584. this._projectionMatrix = projection;
  19585. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19586. // Update frustum
  19587. if (!this._frustumPlanes) {
  19588. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19589. }
  19590. else {
  19591. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19592. }
  19593. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19594. var otherCamera = this.activeCamera._alternateCamera;
  19595. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19596. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19597. }
  19598. if (this._sceneUbo.useUbo) {
  19599. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19600. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19601. this._sceneUbo.update();
  19602. }
  19603. };
  19604. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19605. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19606. return;
  19607. }
  19608. this._alternateViewUpdateFlag = view.updateFlag;
  19609. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19610. this._alternateViewMatrix = view;
  19611. this._alternateProjectionMatrix = projection;
  19612. if (!this._alternateTransformMatrix) {
  19613. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19614. }
  19615. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19616. if (!this._alternateSceneUbo) {
  19617. this._createAlternateUbo();
  19618. }
  19619. if (this._alternateSceneUbo.useUbo) {
  19620. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19621. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19622. this._alternateSceneUbo.update();
  19623. }
  19624. };
  19625. Scene.prototype.getSceneUniformBuffer = function () {
  19626. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19627. };
  19628. // Methods
  19629. Scene.prototype.getUniqueId = function () {
  19630. var result = Scene._uniqueIdCounter;
  19631. Scene._uniqueIdCounter++;
  19632. return result;
  19633. };
  19634. Scene.prototype.addMesh = function (newMesh) {
  19635. this.meshes.push(newMesh);
  19636. //notify the collision coordinator
  19637. if (this.collisionCoordinator) {
  19638. this.collisionCoordinator.onMeshAdded(newMesh);
  19639. }
  19640. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19641. };
  19642. Scene.prototype.removeMesh = function (toRemove) {
  19643. var index = this.meshes.indexOf(toRemove);
  19644. if (index !== -1) {
  19645. // Remove from the scene if mesh found
  19646. this.meshes.splice(index, 1);
  19647. }
  19648. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19649. return index;
  19650. };
  19651. Scene.prototype.addTransformNode = function (newTransformNode) {
  19652. this.transformNodes.push(newTransformNode);
  19653. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19654. };
  19655. Scene.prototype.removeTransformNode = function (toRemove) {
  19656. var index = this.transformNodes.indexOf(toRemove);
  19657. if (index !== -1) {
  19658. // Remove from the scene if found
  19659. this.transformNodes.splice(index, 1);
  19660. }
  19661. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19662. return index;
  19663. };
  19664. Scene.prototype.removeSkeleton = function (toRemove) {
  19665. var index = this.skeletons.indexOf(toRemove);
  19666. if (index !== -1) {
  19667. // Remove from the scene if found
  19668. this.skeletons.splice(index, 1);
  19669. }
  19670. return index;
  19671. };
  19672. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19673. var index = this.morphTargetManagers.indexOf(toRemove);
  19674. if (index !== -1) {
  19675. // Remove from the scene if found
  19676. this.morphTargetManagers.splice(index, 1);
  19677. }
  19678. return index;
  19679. };
  19680. Scene.prototype.removeLight = function (toRemove) {
  19681. var index = this.lights.indexOf(toRemove);
  19682. if (index !== -1) {
  19683. // Remove from the scene if mesh found
  19684. this.lights.splice(index, 1);
  19685. this.sortLightsByPriority();
  19686. }
  19687. this.onLightRemovedObservable.notifyObservers(toRemove);
  19688. return index;
  19689. };
  19690. Scene.prototype.removeCamera = function (toRemove) {
  19691. var index = this.cameras.indexOf(toRemove);
  19692. if (index !== -1) {
  19693. // Remove from the scene if mesh found
  19694. this.cameras.splice(index, 1);
  19695. }
  19696. // Remove from activeCameras
  19697. var index2 = this.activeCameras.indexOf(toRemove);
  19698. if (index2 !== -1) {
  19699. // Remove from the scene if mesh found
  19700. this.activeCameras.splice(index2, 1);
  19701. }
  19702. // Reset the activeCamera
  19703. if (this.activeCamera === toRemove) {
  19704. if (this.cameras.length > 0) {
  19705. this.activeCamera = this.cameras[0];
  19706. }
  19707. else {
  19708. this.activeCamera = null;
  19709. }
  19710. }
  19711. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19712. return index;
  19713. };
  19714. Scene.prototype.addLight = function (newLight) {
  19715. this.lights.push(newLight);
  19716. this.sortLightsByPriority();
  19717. this.onNewLightAddedObservable.notifyObservers(newLight);
  19718. };
  19719. Scene.prototype.sortLightsByPriority = function () {
  19720. if (this.requireLightSorting) {
  19721. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19722. }
  19723. };
  19724. Scene.prototype.addCamera = function (newCamera) {
  19725. this.cameras.push(newCamera);
  19726. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19727. };
  19728. /**
  19729. * Switch active camera
  19730. * @param {Camera} newCamera - new active camera
  19731. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19732. */
  19733. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19734. if (attachControl === void 0) { attachControl = true; }
  19735. var canvas = this._engine.getRenderingCanvas();
  19736. if (!canvas) {
  19737. return;
  19738. }
  19739. if (this.activeCamera) {
  19740. this.activeCamera.detachControl(canvas);
  19741. }
  19742. this.activeCamera = newCamera;
  19743. if (attachControl) {
  19744. newCamera.attachControl(canvas);
  19745. }
  19746. };
  19747. /**
  19748. * sets the active camera of the scene using its ID
  19749. * @param {string} id - the camera's ID
  19750. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19751. * @see activeCamera
  19752. */
  19753. Scene.prototype.setActiveCameraByID = function (id) {
  19754. var camera = this.getCameraByID(id);
  19755. if (camera) {
  19756. this.activeCamera = camera;
  19757. return camera;
  19758. }
  19759. return null;
  19760. };
  19761. /**
  19762. * sets the active camera of the scene using its name
  19763. * @param {string} name - the camera's name
  19764. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19765. * @see activeCamera
  19766. */
  19767. Scene.prototype.setActiveCameraByName = function (name) {
  19768. var camera = this.getCameraByName(name);
  19769. if (camera) {
  19770. this.activeCamera = camera;
  19771. return camera;
  19772. }
  19773. return null;
  19774. };
  19775. /**
  19776. * get a material using its id
  19777. * @param {string} the material's ID
  19778. * @return {BABYLON.Material|null} the material or null if none found.
  19779. */
  19780. Scene.prototype.getMaterialByID = function (id) {
  19781. for (var index = 0; index < this.materials.length; index++) {
  19782. if (this.materials[index].id === id) {
  19783. return this.materials[index];
  19784. }
  19785. }
  19786. return null;
  19787. };
  19788. /**
  19789. * get a material using its name
  19790. * @param {string} the material's name
  19791. * @return {BABYLON.Material|null} the material or null if none found.
  19792. */
  19793. Scene.prototype.getMaterialByName = function (name) {
  19794. for (var index = 0; index < this.materials.length; index++) {
  19795. if (this.materials[index].name === name) {
  19796. return this.materials[index];
  19797. }
  19798. }
  19799. return null;
  19800. };
  19801. Scene.prototype.getLensFlareSystemByName = function (name) {
  19802. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19803. if (this.lensFlareSystems[index].name === name) {
  19804. return this.lensFlareSystems[index];
  19805. }
  19806. }
  19807. return null;
  19808. };
  19809. Scene.prototype.getLensFlareSystemByID = function (id) {
  19810. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19811. if (this.lensFlareSystems[index].id === id) {
  19812. return this.lensFlareSystems[index];
  19813. }
  19814. }
  19815. return null;
  19816. };
  19817. Scene.prototype.getCameraByID = function (id) {
  19818. for (var index = 0; index < this.cameras.length; index++) {
  19819. if (this.cameras[index].id === id) {
  19820. return this.cameras[index];
  19821. }
  19822. }
  19823. return null;
  19824. };
  19825. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19826. for (var index = 0; index < this.cameras.length; index++) {
  19827. if (this.cameras[index].uniqueId === uniqueId) {
  19828. return this.cameras[index];
  19829. }
  19830. }
  19831. return null;
  19832. };
  19833. /**
  19834. * get a camera using its name
  19835. * @param {string} the camera's name
  19836. * @return {BABYLON.Camera|null} the camera or null if none found.
  19837. */
  19838. Scene.prototype.getCameraByName = function (name) {
  19839. for (var index = 0; index < this.cameras.length; index++) {
  19840. if (this.cameras[index].name === name) {
  19841. return this.cameras[index];
  19842. }
  19843. }
  19844. return null;
  19845. };
  19846. /**
  19847. * get a bone using its id
  19848. * @param {string} the bone's id
  19849. * @return {BABYLON.Bone|null} the bone or null if not found
  19850. */
  19851. Scene.prototype.getBoneByID = function (id) {
  19852. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19853. var skeleton = this.skeletons[skeletonIndex];
  19854. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19855. if (skeleton.bones[boneIndex].id === id) {
  19856. return skeleton.bones[boneIndex];
  19857. }
  19858. }
  19859. }
  19860. return null;
  19861. };
  19862. /**
  19863. * get a bone using its id
  19864. * @param {string} the bone's name
  19865. * @return {BABYLON.Bone|null} the bone or null if not found
  19866. */
  19867. Scene.prototype.getBoneByName = function (name) {
  19868. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19869. var skeleton = this.skeletons[skeletonIndex];
  19870. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19871. if (skeleton.bones[boneIndex].name === name) {
  19872. return skeleton.bones[boneIndex];
  19873. }
  19874. }
  19875. }
  19876. return null;
  19877. };
  19878. /**
  19879. * get a light node using its name
  19880. * @param {string} the light's name
  19881. * @return {BABYLON.Light|null} the light or null if none found.
  19882. */
  19883. Scene.prototype.getLightByName = function (name) {
  19884. for (var index = 0; index < this.lights.length; index++) {
  19885. if (this.lights[index].name === name) {
  19886. return this.lights[index];
  19887. }
  19888. }
  19889. return null;
  19890. };
  19891. /**
  19892. * get a light node using its ID
  19893. * @param {string} the light's id
  19894. * @return {BABYLON.Light|null} the light or null if none found.
  19895. */
  19896. Scene.prototype.getLightByID = function (id) {
  19897. for (var index = 0; index < this.lights.length; index++) {
  19898. if (this.lights[index].id === id) {
  19899. return this.lights[index];
  19900. }
  19901. }
  19902. return null;
  19903. };
  19904. /**
  19905. * get a light node using its scene-generated unique ID
  19906. * @param {number} the light's unique id
  19907. * @return {BABYLON.Light|null} the light or null if none found.
  19908. */
  19909. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19910. for (var index = 0; index < this.lights.length; index++) {
  19911. if (this.lights[index].uniqueId === uniqueId) {
  19912. return this.lights[index];
  19913. }
  19914. }
  19915. return null;
  19916. };
  19917. /**
  19918. * get a particle system by id
  19919. * @param id {number} the particle system id
  19920. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19921. */
  19922. Scene.prototype.getParticleSystemByID = function (id) {
  19923. for (var index = 0; index < this.particleSystems.length; index++) {
  19924. if (this.particleSystems[index].id === id) {
  19925. return this.particleSystems[index];
  19926. }
  19927. }
  19928. return null;
  19929. };
  19930. /**
  19931. * get a geometry using its ID
  19932. * @param {string} the geometry's id
  19933. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19934. */
  19935. Scene.prototype.getGeometryByID = function (id) {
  19936. for (var index = 0; index < this._geometries.length; index++) {
  19937. if (this._geometries[index].id === id) {
  19938. return this._geometries[index];
  19939. }
  19940. }
  19941. return null;
  19942. };
  19943. /**
  19944. * add a new geometry to this scene.
  19945. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19946. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19947. * @return {boolean} was the geometry added or not
  19948. */
  19949. Scene.prototype.pushGeometry = function (geometry, force) {
  19950. if (!force && this.getGeometryByID(geometry.id)) {
  19951. return false;
  19952. }
  19953. this._geometries.push(geometry);
  19954. //notify the collision coordinator
  19955. if (this.collisionCoordinator) {
  19956. this.collisionCoordinator.onGeometryAdded(geometry);
  19957. }
  19958. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19959. return true;
  19960. };
  19961. /**
  19962. * Removes an existing geometry
  19963. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19964. * @return {boolean} was the geometry removed or not
  19965. */
  19966. Scene.prototype.removeGeometry = function (geometry) {
  19967. var index = this._geometries.indexOf(geometry);
  19968. if (index > -1) {
  19969. this._geometries.splice(index, 1);
  19970. //notify the collision coordinator
  19971. if (this.collisionCoordinator) {
  19972. this.collisionCoordinator.onGeometryDeleted(geometry);
  19973. }
  19974. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19975. return true;
  19976. }
  19977. return false;
  19978. };
  19979. Scene.prototype.getGeometries = function () {
  19980. return this._geometries;
  19981. };
  19982. /**
  19983. * Get the first added mesh found of a given ID
  19984. * @param {string} id - the id to search for
  19985. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19986. */
  19987. Scene.prototype.getMeshByID = function (id) {
  19988. for (var index = 0; index < this.meshes.length; index++) {
  19989. if (this.meshes[index].id === id) {
  19990. return this.meshes[index];
  19991. }
  19992. }
  19993. return null;
  19994. };
  19995. Scene.prototype.getMeshesByID = function (id) {
  19996. return this.meshes.filter(function (m) {
  19997. return m.id === id;
  19998. });
  19999. };
  20000. /**
  20001. * Get the first added transform node found of a given ID
  20002. * @param {string} id - the id to search for
  20003. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20004. */
  20005. Scene.prototype.getTransformNodeByID = function (id) {
  20006. for (var index = 0; index < this.transformNodes.length; index++) {
  20007. if (this.transformNodes[index].id === id) {
  20008. return this.transformNodes[index];
  20009. }
  20010. }
  20011. return null;
  20012. };
  20013. Scene.prototype.getTransformNodesByID = function (id) {
  20014. return this.transformNodes.filter(function (m) {
  20015. return m.id === id;
  20016. });
  20017. };
  20018. /**
  20019. * Get a mesh with its auto-generated unique id
  20020. * @param {number} uniqueId - the unique id to search for
  20021. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20022. */
  20023. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20024. for (var index = 0; index < this.meshes.length; index++) {
  20025. if (this.meshes[index].uniqueId === uniqueId) {
  20026. return this.meshes[index];
  20027. }
  20028. }
  20029. return null;
  20030. };
  20031. /**
  20032. * Get a the last added mesh found of a given ID
  20033. * @param {string} id - the id to search for
  20034. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20035. */
  20036. Scene.prototype.getLastMeshByID = function (id) {
  20037. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20038. if (this.meshes[index].id === id) {
  20039. return this.meshes[index];
  20040. }
  20041. }
  20042. return null;
  20043. };
  20044. /**
  20045. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20046. * @param {string} id - the id to search for
  20047. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20048. */
  20049. Scene.prototype.getLastEntryByID = function (id) {
  20050. var index;
  20051. for (index = this.meshes.length - 1; index >= 0; index--) {
  20052. if (this.meshes[index].id === id) {
  20053. return this.meshes[index];
  20054. }
  20055. }
  20056. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20057. if (this.transformNodes[index].id === id) {
  20058. return this.transformNodes[index];
  20059. }
  20060. }
  20061. for (index = this.cameras.length - 1; index >= 0; index--) {
  20062. if (this.cameras[index].id === id) {
  20063. return this.cameras[index];
  20064. }
  20065. }
  20066. for (index = this.lights.length - 1; index >= 0; index--) {
  20067. if (this.lights[index].id === id) {
  20068. return this.lights[index];
  20069. }
  20070. }
  20071. return null;
  20072. };
  20073. Scene.prototype.getNodeByID = function (id) {
  20074. var mesh = this.getMeshByID(id);
  20075. if (mesh) {
  20076. return mesh;
  20077. }
  20078. var light = this.getLightByID(id);
  20079. if (light) {
  20080. return light;
  20081. }
  20082. var camera = this.getCameraByID(id);
  20083. if (camera) {
  20084. return camera;
  20085. }
  20086. var bone = this.getBoneByID(id);
  20087. return bone;
  20088. };
  20089. Scene.prototype.getNodeByName = function (name) {
  20090. var mesh = this.getMeshByName(name);
  20091. if (mesh) {
  20092. return mesh;
  20093. }
  20094. var light = this.getLightByName(name);
  20095. if (light) {
  20096. return light;
  20097. }
  20098. var camera = this.getCameraByName(name);
  20099. if (camera) {
  20100. return camera;
  20101. }
  20102. var bone = this.getBoneByName(name);
  20103. return bone;
  20104. };
  20105. Scene.prototype.getMeshByName = function (name) {
  20106. for (var index = 0; index < this.meshes.length; index++) {
  20107. if (this.meshes[index].name === name) {
  20108. return this.meshes[index];
  20109. }
  20110. }
  20111. return null;
  20112. };
  20113. Scene.prototype.getTransformNodeByName = function (name) {
  20114. for (var index = 0; index < this.transformNodes.length; index++) {
  20115. if (this.transformNodes[index].name === name) {
  20116. return this.transformNodes[index];
  20117. }
  20118. }
  20119. return null;
  20120. };
  20121. Scene.prototype.getSoundByName = function (name) {
  20122. var index;
  20123. if (BABYLON.AudioEngine) {
  20124. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20125. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20126. return this.mainSoundTrack.soundCollection[index];
  20127. }
  20128. }
  20129. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20130. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20131. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20132. return this.soundTracks[sdIndex].soundCollection[index];
  20133. }
  20134. }
  20135. }
  20136. }
  20137. return null;
  20138. };
  20139. Scene.prototype.getLastSkeletonByID = function (id) {
  20140. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20141. if (this.skeletons[index].id === id) {
  20142. return this.skeletons[index];
  20143. }
  20144. }
  20145. return null;
  20146. };
  20147. Scene.prototype.getSkeletonById = function (id) {
  20148. for (var index = 0; index < this.skeletons.length; index++) {
  20149. if (this.skeletons[index].id === id) {
  20150. return this.skeletons[index];
  20151. }
  20152. }
  20153. return null;
  20154. };
  20155. Scene.prototype.getSkeletonByName = function (name) {
  20156. for (var index = 0; index < this.skeletons.length; index++) {
  20157. if (this.skeletons[index].name === name) {
  20158. return this.skeletons[index];
  20159. }
  20160. }
  20161. return null;
  20162. };
  20163. Scene.prototype.getMorphTargetManagerById = function (id) {
  20164. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20165. if (this.morphTargetManagers[index].uniqueId === id) {
  20166. return this.morphTargetManagers[index];
  20167. }
  20168. }
  20169. return null;
  20170. };
  20171. Scene.prototype.isActiveMesh = function (mesh) {
  20172. return (this._activeMeshes.indexOf(mesh) !== -1);
  20173. };
  20174. /**
  20175. * Return a the first highlight layer of the scene with a given name.
  20176. * @param name The name of the highlight layer to look for.
  20177. * @return The highlight layer if found otherwise null.
  20178. */
  20179. Scene.prototype.getHighlightLayerByName = function (name) {
  20180. for (var index = 0; index < this.highlightLayers.length; index++) {
  20181. if (this.highlightLayers[index].name === name) {
  20182. return this.highlightLayers[index];
  20183. }
  20184. }
  20185. return null;
  20186. };
  20187. Object.defineProperty(Scene.prototype, "uid", {
  20188. /**
  20189. * Return a unique id as a string which can serve as an identifier for the scene
  20190. */
  20191. get: function () {
  20192. if (!this._uid) {
  20193. this._uid = BABYLON.Tools.RandomId();
  20194. }
  20195. return this._uid;
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. /**
  20201. * Add an externaly attached data from its key.
  20202. * This method call will fail and return false, if such key already exists.
  20203. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20204. * @param key the unique key that identifies the data
  20205. * @param data the data object to associate to the key for this Engine instance
  20206. * @return true if no such key were already present and the data was added successfully, false otherwise
  20207. */
  20208. Scene.prototype.addExternalData = function (key, data) {
  20209. if (!this._externalData) {
  20210. this._externalData = new BABYLON.StringDictionary();
  20211. }
  20212. return this._externalData.add(key, data);
  20213. };
  20214. /**
  20215. * Get an externaly attached data from its key
  20216. * @param key the unique key that identifies the data
  20217. * @return the associated data, if present (can be null), or undefined if not present
  20218. */
  20219. Scene.prototype.getExternalData = function (key) {
  20220. if (!this._externalData) {
  20221. return null;
  20222. }
  20223. return this._externalData.get(key);
  20224. };
  20225. /**
  20226. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20227. * @param key the unique key that identifies the data
  20228. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20229. * @return the associated data, can be null if the factory returned null.
  20230. */
  20231. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20232. if (!this._externalData) {
  20233. this._externalData = new BABYLON.StringDictionary();
  20234. }
  20235. return this._externalData.getOrAddWithFactory(key, factory);
  20236. };
  20237. /**
  20238. * Remove an externaly attached data from the Engine instance
  20239. * @param key the unique key that identifies the data
  20240. * @return true if the data was successfully removed, false if it doesn't exist
  20241. */
  20242. Scene.prototype.removeExternalData = function (key) {
  20243. return this._externalData.remove(key);
  20244. };
  20245. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20246. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20247. var material = subMesh.getMaterial();
  20248. if (mesh.showSubMeshesBoundingBox) {
  20249. var boundingInfo = subMesh.getBoundingInfo();
  20250. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20251. }
  20252. if (material) {
  20253. // Render targets
  20254. if (material.getRenderTargetTextures) {
  20255. if (this._processedMaterials.indexOf(material) === -1) {
  20256. this._processedMaterials.push(material);
  20257. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20258. }
  20259. }
  20260. // Dispatch
  20261. this._activeIndices.addCount(subMesh.indexCount, false);
  20262. this._renderingManager.dispatch(subMesh);
  20263. }
  20264. }
  20265. };
  20266. Scene.prototype._isInIntermediateRendering = function () {
  20267. return this._intermediateRendering;
  20268. };
  20269. /**
  20270. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20271. */
  20272. Scene.prototype.freezeActiveMeshes = function () {
  20273. this._evaluateActiveMeshes();
  20274. this._activeMeshesFrozen = true;
  20275. return this;
  20276. };
  20277. /**
  20278. * Use this function to restart evaluating active meshes on every frame
  20279. */
  20280. Scene.prototype.unfreezeActiveMeshes = function () {
  20281. this._activeMeshesFrozen = false;
  20282. return this;
  20283. };
  20284. Scene.prototype._evaluateActiveMeshes = function () {
  20285. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20286. return;
  20287. }
  20288. if (!this.activeCamera) {
  20289. return;
  20290. }
  20291. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20292. this.activeCamera._activeMeshes.reset();
  20293. this._activeMeshes.reset();
  20294. this._renderingManager.reset();
  20295. this._processedMaterials.reset();
  20296. this._activeParticleSystems.reset();
  20297. this._activeSkeletons.reset();
  20298. this._softwareSkinnedMeshes.reset();
  20299. if (this._boundingBoxRenderer) {
  20300. this._boundingBoxRenderer.reset();
  20301. }
  20302. // Meshes
  20303. var meshes;
  20304. var len;
  20305. if (this._selectionOctree) {
  20306. var selection = this._selectionOctree.select(this._frustumPlanes);
  20307. meshes = selection.data;
  20308. len = selection.length;
  20309. }
  20310. else {
  20311. len = this.meshes.length;
  20312. meshes = this.meshes;
  20313. }
  20314. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20315. var mesh = meshes[meshIndex];
  20316. if (mesh.isBlocked) {
  20317. continue;
  20318. }
  20319. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20320. if (!mesh.isReady() || !mesh.isEnabled()) {
  20321. continue;
  20322. }
  20323. mesh.computeWorldMatrix();
  20324. // Intersections
  20325. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20326. this._meshesForIntersections.pushNoDuplicate(mesh);
  20327. }
  20328. // Switch to current LOD
  20329. var meshLOD = mesh.getLOD(this.activeCamera);
  20330. if (!meshLOD) {
  20331. continue;
  20332. }
  20333. mesh._preActivate();
  20334. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20335. this._activeMeshes.push(mesh);
  20336. this.activeCamera._activeMeshes.push(mesh);
  20337. mesh._activate(this._renderId);
  20338. if (meshLOD !== mesh) {
  20339. meshLOD._activate(this._renderId);
  20340. }
  20341. this._activeMesh(mesh, meshLOD);
  20342. }
  20343. }
  20344. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20345. // Particle systems
  20346. if (this.particlesEnabled) {
  20347. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20348. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20349. var particleSystem = this.particleSystems[particleIndex];
  20350. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20351. continue;
  20352. }
  20353. var emitter = particleSystem.emitter;
  20354. if (!emitter.position || emitter.isEnabled()) {
  20355. this._activeParticleSystems.push(particleSystem);
  20356. particleSystem.animate();
  20357. this._renderingManager.dispatchParticles(particleSystem);
  20358. }
  20359. }
  20360. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20361. }
  20362. };
  20363. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20364. if (mesh.skeleton && this.skeletonsEnabled) {
  20365. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20366. mesh.skeleton.prepare();
  20367. }
  20368. if (!mesh.computeBonesUsingShaders) {
  20369. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20370. }
  20371. }
  20372. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20373. var boundingInfo = sourceMesh.getBoundingInfo();
  20374. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20375. }
  20376. if (mesh && mesh.subMeshes) {
  20377. // Submeshes Octrees
  20378. var len;
  20379. var subMeshes;
  20380. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20381. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20382. len = intersections.length;
  20383. subMeshes = intersections.data;
  20384. }
  20385. else {
  20386. subMeshes = mesh.subMeshes;
  20387. len = subMeshes.length;
  20388. }
  20389. for (var subIndex = 0; subIndex < len; subIndex++) {
  20390. var subMesh = subMeshes[subIndex];
  20391. this._evaluateSubMesh(subMesh, mesh);
  20392. }
  20393. }
  20394. };
  20395. Scene.prototype.updateTransformMatrix = function (force) {
  20396. if (!this.activeCamera) {
  20397. return;
  20398. }
  20399. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20400. };
  20401. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20402. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20403. };
  20404. Scene.prototype._renderForCamera = function (camera) {
  20405. if (camera && camera._skipRendering) {
  20406. return;
  20407. }
  20408. var engine = this._engine;
  20409. this.activeCamera = camera;
  20410. if (!this.activeCamera)
  20411. throw new Error("Active camera not set");
  20412. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20413. // Viewport
  20414. engine.setViewport(this.activeCamera.viewport);
  20415. // Camera
  20416. this.resetCachedMaterial();
  20417. this._renderId++;
  20418. this.activeCamera.update();
  20419. this.updateTransformMatrix();
  20420. if (camera._alternateCamera) {
  20421. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20422. this._alternateRendering = true;
  20423. }
  20424. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20425. // Meshes
  20426. this._evaluateActiveMeshes();
  20427. // Software skinning
  20428. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20429. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20430. mesh.applySkeleton(mesh.skeleton);
  20431. }
  20432. // Render targets
  20433. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20434. var needsRestoreFrameBuffer = false;
  20435. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20436. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20437. }
  20438. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20439. this._intermediateRendering = true;
  20440. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20441. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20442. var renderTarget = this._renderTargets.data[renderIndex];
  20443. if (renderTarget._shouldRender()) {
  20444. this._renderId++;
  20445. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20446. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20447. }
  20448. }
  20449. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20450. this._intermediateRendering = false;
  20451. this._renderId++;
  20452. needsRestoreFrameBuffer = true; // Restore back buffer
  20453. }
  20454. // Render HighlightLayer Texture
  20455. var stencilState = this._engine.getStencilBuffer();
  20456. var renderhighlights = false;
  20457. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20458. this._intermediateRendering = true;
  20459. for (var i = 0; i < this.highlightLayers.length; i++) {
  20460. var highlightLayer = this.highlightLayers[i];
  20461. if (highlightLayer.shouldRender() &&
  20462. (!highlightLayer.camera ||
  20463. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20464. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20465. renderhighlights = true;
  20466. var renderTarget = highlightLayer._mainTexture;
  20467. if (renderTarget._shouldRender()) {
  20468. this._renderId++;
  20469. renderTarget.render(false, false);
  20470. needsRestoreFrameBuffer = true;
  20471. }
  20472. }
  20473. }
  20474. this._intermediateRendering = false;
  20475. this._renderId++;
  20476. }
  20477. if (needsRestoreFrameBuffer) {
  20478. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20479. }
  20480. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20481. // Prepare Frame
  20482. this.postProcessManager._prepareFrame();
  20483. // Backgrounds
  20484. var layerIndex;
  20485. var layer;
  20486. if (this.layers.length) {
  20487. engine.setDepthBuffer(false);
  20488. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20489. layer = this.layers[layerIndex];
  20490. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20491. layer.render();
  20492. }
  20493. }
  20494. engine.setDepthBuffer(true);
  20495. }
  20496. // Activate HighlightLayer stencil
  20497. if (renderhighlights) {
  20498. this._engine.setStencilBuffer(true);
  20499. }
  20500. // Render
  20501. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20502. this._renderingManager.render(null, null, true, true);
  20503. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20504. // Restore HighlightLayer stencil
  20505. if (renderhighlights) {
  20506. this._engine.setStencilBuffer(stencilState);
  20507. }
  20508. // Bounding boxes
  20509. if (this._boundingBoxRenderer) {
  20510. this._boundingBoxRenderer.render();
  20511. }
  20512. // Lens flares
  20513. if (this.lensFlaresEnabled) {
  20514. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20515. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20516. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20517. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20518. lensFlareSystem.render();
  20519. }
  20520. }
  20521. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20522. }
  20523. // Foregrounds
  20524. if (this.layers.length) {
  20525. engine.setDepthBuffer(false);
  20526. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20527. layer = this.layers[layerIndex];
  20528. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20529. layer.render();
  20530. }
  20531. }
  20532. engine.setDepthBuffer(true);
  20533. }
  20534. // Highlight Layer
  20535. if (renderhighlights) {
  20536. engine.setDepthBuffer(false);
  20537. for (var i = 0; i < this.highlightLayers.length; i++) {
  20538. if (this.highlightLayers[i].shouldRender()) {
  20539. this.highlightLayers[i].render();
  20540. }
  20541. }
  20542. engine.setDepthBuffer(true);
  20543. }
  20544. // Finalize frame
  20545. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20546. // Reset some special arrays
  20547. this._renderTargets.reset();
  20548. this._alternateRendering = false;
  20549. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20550. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20551. };
  20552. Scene.prototype._processSubCameras = function (camera) {
  20553. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20554. this._renderForCamera(camera);
  20555. return;
  20556. }
  20557. // Update camera
  20558. if (this.activeCamera) {
  20559. this.activeCamera.update();
  20560. }
  20561. // rig cameras
  20562. for (var index = 0; index < camera._rigCameras.length; index++) {
  20563. this._renderForCamera(camera._rigCameras[index]);
  20564. }
  20565. this.activeCamera = camera;
  20566. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20567. };
  20568. Scene.prototype._checkIntersections = function () {
  20569. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20570. var sourceMesh = this._meshesForIntersections.data[index];
  20571. if (!sourceMesh.actionManager) {
  20572. continue;
  20573. }
  20574. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20575. var action = sourceMesh.actionManager.actions[actionIndex];
  20576. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20577. var parameters = action.getTriggerParameter();
  20578. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20579. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20580. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20581. if (areIntersecting && currentIntersectionInProgress === -1) {
  20582. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20583. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20584. sourceMesh._intersectionsInProgress.push(otherMesh);
  20585. }
  20586. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20587. sourceMesh._intersectionsInProgress.push(otherMesh);
  20588. }
  20589. }
  20590. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20591. //They intersected, and now they don't.
  20592. //is this trigger an exit trigger? execute an event.
  20593. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20594. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20595. }
  20596. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20597. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20598. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20599. }
  20600. }
  20601. }
  20602. }
  20603. }
  20604. };
  20605. Scene.prototype.render = function () {
  20606. if (this.isDisposed) {
  20607. return;
  20608. }
  20609. this._activeParticles.fetchNewFrame();
  20610. this._totalVertices.fetchNewFrame();
  20611. this._activeIndices.fetchNewFrame();
  20612. this._activeBones.fetchNewFrame();
  20613. this._meshesForIntersections.reset();
  20614. this.resetCachedMaterial();
  20615. this.onBeforeAnimationsObservable.notifyObservers(this);
  20616. // Actions
  20617. if (this.actionManager) {
  20618. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20619. }
  20620. //Simplification Queue
  20621. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20622. this.simplificationQueue.executeNext();
  20623. }
  20624. if (this._engine.isDeterministicLockStep()) {
  20625. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20626. var defaultFPS = (60.0 / 1000.0);
  20627. var defaultFrameTime = 1000 / 60; // frame time in MS
  20628. if (this._physicsEngine) {
  20629. defaultFrameTime = this._physicsEngine.getTimeStep() / 1000; //timestep in physics engine is in seconds
  20630. }
  20631. var stepsTaken = 0;
  20632. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20633. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20634. internalSteps = Math.min(internalSteps, maxSubSteps);
  20635. do {
  20636. this.onBeforeStepObservable.notifyObservers(this);
  20637. // Animations
  20638. this._animationRatio = defaultFrameTime * defaultFPS;
  20639. this._animate();
  20640. this.onAfterAnimationsObservable.notifyObservers(this);
  20641. // Physics
  20642. if (this._physicsEngine) {
  20643. this.onBeforePhysicsObservable.notifyObservers(this);
  20644. this._physicsEngine._step(defaultFPS);
  20645. this.onAfterPhysicsObservable.notifyObservers(this);
  20646. }
  20647. this.onAfterStepObservable.notifyObservers(this);
  20648. this._currentStepId++;
  20649. if ((internalSteps > 1) && (stepsTaken != internalSteps - 1)) {
  20650. this._evaluateActiveMeshes();
  20651. }
  20652. stepsTaken++;
  20653. deltaTime -= defaultFrameTime;
  20654. } while (deltaTime > 0 && stepsTaken < maxSubSteps);
  20655. this._timeAccumulator = deltaTime;
  20656. }
  20657. else {
  20658. // Animations
  20659. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20660. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20661. this._animate();
  20662. this.onAfterAnimationsObservable.notifyObservers(this);
  20663. // Physics
  20664. if (this._physicsEngine) {
  20665. this.onBeforePhysicsObservable.notifyObservers(this);
  20666. this._physicsEngine._step(deltaTime / 1000.0);
  20667. this.onAfterPhysicsObservable.notifyObservers(this);
  20668. }
  20669. }
  20670. // Before render
  20671. this.onBeforeRenderObservable.notifyObservers(this);
  20672. // Customs render targets
  20673. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20674. var engine = this.getEngine();
  20675. var currentActiveCamera = this.activeCamera;
  20676. if (this.renderTargetsEnabled) {
  20677. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20678. this._intermediateRendering = true;
  20679. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20680. var renderTarget = this.customRenderTargets[customIndex];
  20681. if (renderTarget._shouldRender()) {
  20682. this._renderId++;
  20683. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20684. if (!this.activeCamera)
  20685. throw new Error("Active camera not set");
  20686. // Viewport
  20687. engine.setViewport(this.activeCamera.viewport);
  20688. // Camera
  20689. this.updateTransformMatrix();
  20690. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20691. }
  20692. }
  20693. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20694. this._intermediateRendering = false;
  20695. this._renderId++;
  20696. }
  20697. // Restore back buffer
  20698. if (this.customRenderTargets.length > 0) {
  20699. engine.restoreDefaultFramebuffer();
  20700. }
  20701. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20702. this.activeCamera = currentActiveCamera;
  20703. // Procedural textures
  20704. if (this.proceduralTexturesEnabled) {
  20705. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20706. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20707. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20708. if (proceduralTexture._shouldRender()) {
  20709. proceduralTexture.render();
  20710. }
  20711. }
  20712. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20713. }
  20714. // Clear
  20715. if (this.autoClearDepthAndStencil || this.autoClear) {
  20716. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20717. }
  20718. // Shadows
  20719. if (this.shadowsEnabled) {
  20720. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20721. var light = this.lights[lightIndex];
  20722. var shadowGenerator = light.getShadowGenerator();
  20723. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20724. var shadowMap = (shadowGenerator.getShadowMap());
  20725. if (this.textures.indexOf(shadowMap) !== -1) {
  20726. this._renderTargets.push(shadowMap);
  20727. }
  20728. }
  20729. }
  20730. }
  20731. // Depth renderer
  20732. if (this._depthRenderer) {
  20733. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20734. }
  20735. // Geometry renderer
  20736. if (this._geometryBufferRenderer) {
  20737. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20738. }
  20739. // RenderPipeline
  20740. if (this._postProcessRenderPipelineManager) {
  20741. this._postProcessRenderPipelineManager.update();
  20742. }
  20743. // Multi-cameras?
  20744. if (this.activeCameras.length > 0) {
  20745. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20746. if (cameraIndex > 0) {
  20747. this._engine.clear(null, false, true, true);
  20748. }
  20749. this._processSubCameras(this.activeCameras[cameraIndex]);
  20750. }
  20751. }
  20752. else {
  20753. if (!this.activeCamera) {
  20754. throw new Error("No camera defined");
  20755. }
  20756. this._processSubCameras(this.activeCamera);
  20757. }
  20758. // Intersection checks
  20759. this._checkIntersections();
  20760. // Update the audio listener attached to the camera
  20761. if (BABYLON.AudioEngine) {
  20762. this._updateAudioParameters();
  20763. }
  20764. // After render
  20765. if (this.afterRender) {
  20766. this.afterRender();
  20767. }
  20768. this.onAfterRenderObservable.notifyObservers(this);
  20769. // Cleaning
  20770. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20771. var data = this._toBeDisposed.data[index];
  20772. if (data) {
  20773. data.dispose();
  20774. }
  20775. this._toBeDisposed[index] = null;
  20776. }
  20777. this._toBeDisposed.reset();
  20778. if (this.dumpNextRenderTargets) {
  20779. this.dumpNextRenderTargets = false;
  20780. }
  20781. this._activeBones.addCount(0, true);
  20782. this._activeIndices.addCount(0, true);
  20783. this._activeParticles.addCount(0, true);
  20784. };
  20785. Scene.prototype._updateAudioParameters = function () {
  20786. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20787. return;
  20788. }
  20789. var listeningCamera;
  20790. var audioEngine = BABYLON.Engine.audioEngine;
  20791. if (this.activeCameras.length > 0) {
  20792. listeningCamera = this.activeCameras[0];
  20793. }
  20794. else {
  20795. listeningCamera = this.activeCamera;
  20796. }
  20797. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20798. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20799. // for VR cameras
  20800. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20801. listeningCamera = listeningCamera.rigCameras[0];
  20802. }
  20803. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20804. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20805. cameraDirection.normalize();
  20806. // To avoid some errors on GearVR
  20807. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20808. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20809. }
  20810. var i;
  20811. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20812. var sound = this.mainSoundTrack.soundCollection[i];
  20813. if (sound.useCustomAttenuation) {
  20814. sound.updateDistanceFromListener();
  20815. }
  20816. }
  20817. for (i = 0; i < this.soundTracks.length; i++) {
  20818. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20819. sound = this.soundTracks[i].soundCollection[j];
  20820. if (sound.useCustomAttenuation) {
  20821. sound.updateDistanceFromListener();
  20822. }
  20823. }
  20824. }
  20825. }
  20826. };
  20827. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20828. // Audio
  20829. get: function () {
  20830. return this._audioEnabled;
  20831. },
  20832. set: function (value) {
  20833. this._audioEnabled = value;
  20834. if (BABYLON.AudioEngine) {
  20835. if (this._audioEnabled) {
  20836. this._enableAudio();
  20837. }
  20838. else {
  20839. this._disableAudio();
  20840. }
  20841. }
  20842. },
  20843. enumerable: true,
  20844. configurable: true
  20845. });
  20846. Scene.prototype._disableAudio = function () {
  20847. var i;
  20848. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20849. this.mainSoundTrack.soundCollection[i].pause();
  20850. }
  20851. for (i = 0; i < this.soundTracks.length; i++) {
  20852. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20853. this.soundTracks[i].soundCollection[j].pause();
  20854. }
  20855. }
  20856. };
  20857. Scene.prototype._enableAudio = function () {
  20858. var i;
  20859. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20860. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20861. this.mainSoundTrack.soundCollection[i].play();
  20862. }
  20863. }
  20864. for (i = 0; i < this.soundTracks.length; i++) {
  20865. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20866. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20867. this.soundTracks[i].soundCollection[j].play();
  20868. }
  20869. }
  20870. }
  20871. };
  20872. Object.defineProperty(Scene.prototype, "headphone", {
  20873. get: function () {
  20874. return this._headphone;
  20875. },
  20876. set: function (value) {
  20877. this._headphone = value;
  20878. if (BABYLON.AudioEngine) {
  20879. if (this._headphone) {
  20880. this._switchAudioModeForHeadphones();
  20881. }
  20882. else {
  20883. this._switchAudioModeForNormalSpeakers();
  20884. }
  20885. }
  20886. },
  20887. enumerable: true,
  20888. configurable: true
  20889. });
  20890. Scene.prototype._switchAudioModeForHeadphones = function () {
  20891. this.mainSoundTrack.switchPanningModelToHRTF();
  20892. for (var i = 0; i < this.soundTracks.length; i++) {
  20893. this.soundTracks[i].switchPanningModelToHRTF();
  20894. }
  20895. };
  20896. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20897. this.mainSoundTrack.switchPanningModelToEqualPower();
  20898. for (var i = 0; i < this.soundTracks.length; i++) {
  20899. this.soundTracks[i].switchPanningModelToEqualPower();
  20900. }
  20901. };
  20902. Scene.prototype.enableDepthRenderer = function () {
  20903. if (this._depthRenderer) {
  20904. return this._depthRenderer;
  20905. }
  20906. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20907. return this._depthRenderer;
  20908. };
  20909. Scene.prototype.disableDepthRenderer = function () {
  20910. if (!this._depthRenderer) {
  20911. return;
  20912. }
  20913. this._depthRenderer.dispose();
  20914. this._depthRenderer = null;
  20915. };
  20916. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20917. if (ratio === void 0) { ratio = 1; }
  20918. if (this._geometryBufferRenderer) {
  20919. return this._geometryBufferRenderer;
  20920. }
  20921. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20922. if (!this._geometryBufferRenderer.isSupported) {
  20923. this._geometryBufferRenderer = null;
  20924. }
  20925. return this._geometryBufferRenderer;
  20926. };
  20927. Scene.prototype.disableGeometryBufferRenderer = function () {
  20928. if (!this._geometryBufferRenderer) {
  20929. return;
  20930. }
  20931. this._geometryBufferRenderer.dispose();
  20932. this._geometryBufferRenderer = null;
  20933. };
  20934. Scene.prototype.freezeMaterials = function () {
  20935. for (var i = 0; i < this.materials.length; i++) {
  20936. this.materials[i].freeze();
  20937. }
  20938. };
  20939. Scene.prototype.unfreezeMaterials = function () {
  20940. for (var i = 0; i < this.materials.length; i++) {
  20941. this.materials[i].unfreeze();
  20942. }
  20943. };
  20944. Scene.prototype.dispose = function () {
  20945. this.beforeRender = null;
  20946. this.afterRender = null;
  20947. this.skeletons = [];
  20948. this.morphTargetManagers = [];
  20949. this.importedMeshesFiles = new Array();
  20950. this.stopAllAnimations();
  20951. this.resetCachedMaterial();
  20952. if (this._depthRenderer) {
  20953. this._depthRenderer.dispose();
  20954. }
  20955. if (this._gamepadManager) {
  20956. this._gamepadManager.dispose();
  20957. this._gamepadManager = null;
  20958. }
  20959. // Smart arrays
  20960. if (this.activeCamera) {
  20961. this.activeCamera._activeMeshes.dispose();
  20962. this.activeCamera = null;
  20963. }
  20964. this._activeMeshes.dispose();
  20965. this._renderingManager.dispose();
  20966. this._processedMaterials.dispose();
  20967. this._activeParticleSystems.dispose();
  20968. this._activeSkeletons.dispose();
  20969. this._softwareSkinnedMeshes.dispose();
  20970. this._renderTargets.dispose();
  20971. if (this._boundingBoxRenderer) {
  20972. this._boundingBoxRenderer.dispose();
  20973. }
  20974. this._meshesForIntersections.dispose();
  20975. this._toBeDisposed.dispose();
  20976. // Debug layer
  20977. if (this._debugLayer) {
  20978. this._debugLayer.hide();
  20979. }
  20980. // Events
  20981. this.onDisposeObservable.notifyObservers(this);
  20982. this.onDisposeObservable.clear();
  20983. this.onBeforeRenderObservable.clear();
  20984. this.onAfterRenderObservable.clear();
  20985. this.OnBeforeRenderTargetsRenderObservable.clear();
  20986. this.OnAfterRenderTargetsRenderObservable.clear();
  20987. this.onAfterStepObservable.clear();
  20988. this.onBeforeStepObservable.clear();
  20989. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20990. this.onAfterActiveMeshesEvaluationObservable.clear();
  20991. this.onBeforeParticlesRenderingObservable.clear();
  20992. this.onAfterParticlesRenderingObservable.clear();
  20993. this.onBeforeSpritesRenderingObservable.clear();
  20994. this.onAfterSpritesRenderingObservable.clear();
  20995. this.onBeforeDrawPhaseObservable.clear();
  20996. this.onAfterDrawPhaseObservable.clear();
  20997. this.onBeforePhysicsObservable.clear();
  20998. this.onAfterPhysicsObservable.clear();
  20999. this.onBeforeAnimationsObservable.clear();
  21000. this.onAfterAnimationsObservable.clear();
  21001. this.onDataLoadedObservable.clear();
  21002. this.detachControl();
  21003. // Release sounds & sounds tracks
  21004. if (BABYLON.AudioEngine) {
  21005. this.disposeSounds();
  21006. }
  21007. // VR Helper
  21008. if (this.VRHelper) {
  21009. this.VRHelper.dispose();
  21010. }
  21011. // Detach cameras
  21012. var canvas = this._engine.getRenderingCanvas();
  21013. if (canvas) {
  21014. var index;
  21015. for (index = 0; index < this.cameras.length; index++) {
  21016. this.cameras[index].detachControl(canvas);
  21017. }
  21018. }
  21019. // Release lights
  21020. while (this.lights.length) {
  21021. this.lights[0].dispose();
  21022. }
  21023. // Release meshes
  21024. while (this.meshes.length) {
  21025. this.meshes[0].dispose(true);
  21026. }
  21027. while (this.transformNodes.length) {
  21028. this.removeTransformNode(this.transformNodes[0]);
  21029. }
  21030. // Release cameras
  21031. while (this.cameras.length) {
  21032. this.cameras[0].dispose();
  21033. }
  21034. // Release materials
  21035. if (this.defaultMaterial) {
  21036. this.defaultMaterial.dispose();
  21037. }
  21038. while (this.multiMaterials.length) {
  21039. this.multiMaterials[0].dispose();
  21040. }
  21041. while (this.materials.length) {
  21042. this.materials[0].dispose();
  21043. }
  21044. // Release particles
  21045. while (this.particleSystems.length) {
  21046. this.particleSystems[0].dispose();
  21047. }
  21048. // Release sprites
  21049. while (this.spriteManagers.length) {
  21050. this.spriteManagers[0].dispose();
  21051. }
  21052. // Release postProcesses
  21053. while (this.postProcesses.length) {
  21054. this.postProcesses[0].dispose();
  21055. }
  21056. // Release layers
  21057. while (this.layers.length) {
  21058. this.layers[0].dispose();
  21059. }
  21060. while (this.highlightLayers.length) {
  21061. this.highlightLayers[0].dispose();
  21062. }
  21063. // Release textures
  21064. while (this.textures.length) {
  21065. this.textures[0].dispose();
  21066. }
  21067. // Release UBO
  21068. this._sceneUbo.dispose();
  21069. if (this._alternateSceneUbo) {
  21070. this._alternateSceneUbo.dispose();
  21071. }
  21072. // Post-processes
  21073. this.postProcessManager.dispose();
  21074. if (this._postProcessRenderPipelineManager) {
  21075. this._postProcessRenderPipelineManager.dispose();
  21076. }
  21077. // Physics
  21078. if (this._physicsEngine) {
  21079. this.disablePhysicsEngine();
  21080. }
  21081. // Remove from engine
  21082. index = this._engine.scenes.indexOf(this);
  21083. if (index > -1) {
  21084. this._engine.scenes.splice(index, 1);
  21085. }
  21086. this._engine.wipeCaches();
  21087. this._isDisposed = true;
  21088. };
  21089. Object.defineProperty(Scene.prototype, "isDisposed", {
  21090. get: function () {
  21091. return this._isDisposed;
  21092. },
  21093. enumerable: true,
  21094. configurable: true
  21095. });
  21096. // Release sounds & sounds tracks
  21097. Scene.prototype.disposeSounds = function () {
  21098. if (!this._mainSoundTrack) {
  21099. return;
  21100. }
  21101. this.mainSoundTrack.dispose();
  21102. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21103. this.soundTracks[scIndex].dispose();
  21104. }
  21105. };
  21106. // Octrees
  21107. Scene.prototype.getWorldExtends = function () {
  21108. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21109. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21110. for (var index = 0; index < this.meshes.length; index++) {
  21111. var mesh = this.meshes[index];
  21112. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21113. continue;
  21114. }
  21115. mesh.computeWorldMatrix(true);
  21116. var boundingInfo = mesh.getBoundingInfo();
  21117. var minBox = boundingInfo.boundingBox.minimumWorld;
  21118. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21119. BABYLON.Tools.CheckExtends(minBox, min, max);
  21120. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21121. }
  21122. return {
  21123. min: min,
  21124. max: max
  21125. };
  21126. };
  21127. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21128. if (maxCapacity === void 0) { maxCapacity = 64; }
  21129. if (maxDepth === void 0) { maxDepth = 2; }
  21130. if (!this._selectionOctree) {
  21131. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21132. }
  21133. var worldExtends = this.getWorldExtends();
  21134. // Update octree
  21135. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21136. return this._selectionOctree;
  21137. };
  21138. // Picking
  21139. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21140. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21141. var result = BABYLON.Ray.Zero();
  21142. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21143. return result;
  21144. };
  21145. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21146. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21147. var engine = this._engine;
  21148. if (!camera) {
  21149. if (!this.activeCamera)
  21150. throw new Error("Active camera not set");
  21151. camera = this.activeCamera;
  21152. }
  21153. var cameraViewport = camera.viewport;
  21154. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21155. // Moving coordinates to local viewport world
  21156. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21157. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21158. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21159. return this;
  21160. };
  21161. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21162. var result = BABYLON.Ray.Zero();
  21163. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21164. return result;
  21165. };
  21166. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21167. if (!BABYLON.PickingInfo) {
  21168. return this;
  21169. }
  21170. var engine = this._engine;
  21171. if (!camera) {
  21172. if (!this.activeCamera)
  21173. throw new Error("Active camera not set");
  21174. camera = this.activeCamera;
  21175. }
  21176. var cameraViewport = camera.viewport;
  21177. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21178. var identity = BABYLON.Matrix.Identity();
  21179. // Moving coordinates to local viewport world
  21180. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21181. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21182. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21183. return this;
  21184. };
  21185. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21186. if (!BABYLON.PickingInfo) {
  21187. return null;
  21188. }
  21189. var pickingInfo = null;
  21190. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21191. var mesh = this.meshes[meshIndex];
  21192. if (predicate) {
  21193. if (!predicate(mesh)) {
  21194. continue;
  21195. }
  21196. }
  21197. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21198. continue;
  21199. }
  21200. var world = mesh.getWorldMatrix();
  21201. var ray = rayFunction(world);
  21202. var result = mesh.intersects(ray, fastCheck);
  21203. if (!result || !result.hit)
  21204. continue;
  21205. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21206. continue;
  21207. pickingInfo = result;
  21208. if (fastCheck) {
  21209. break;
  21210. }
  21211. }
  21212. return pickingInfo || new BABYLON.PickingInfo();
  21213. };
  21214. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21215. if (!BABYLON.PickingInfo) {
  21216. return null;
  21217. }
  21218. var pickingInfos = new Array();
  21219. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21220. var mesh = this.meshes[meshIndex];
  21221. if (predicate) {
  21222. if (!predicate(mesh)) {
  21223. continue;
  21224. }
  21225. }
  21226. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21227. continue;
  21228. }
  21229. var world = mesh.getWorldMatrix();
  21230. var ray = rayFunction(world);
  21231. var result = mesh.intersects(ray, false);
  21232. if (!result || !result.hit)
  21233. continue;
  21234. pickingInfos.push(result);
  21235. }
  21236. return pickingInfos;
  21237. };
  21238. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21239. if (!BABYLON.PickingInfo) {
  21240. return null;
  21241. }
  21242. var pickingInfo = null;
  21243. if (!camera) {
  21244. if (!this.activeCamera) {
  21245. return null;
  21246. }
  21247. camera = this.activeCamera;
  21248. }
  21249. if (this.spriteManagers.length > 0) {
  21250. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21251. var spriteManager = this.spriteManagers[spriteIndex];
  21252. if (!spriteManager.isPickable) {
  21253. continue;
  21254. }
  21255. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21256. if (!result || !result.hit)
  21257. continue;
  21258. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21259. continue;
  21260. pickingInfo = result;
  21261. if (fastCheck) {
  21262. break;
  21263. }
  21264. }
  21265. }
  21266. return pickingInfo || new BABYLON.PickingInfo();
  21267. };
  21268. /** Launch a ray to try to pick a mesh in the scene
  21269. * @param x position on screen
  21270. * @param y position on screen
  21271. * @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
  21272. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21273. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21274. */
  21275. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21276. var _this = this;
  21277. if (!this._tempPickingRay) {
  21278. this._tempPickingRay = BABYLON.Ray.Zero();
  21279. }
  21280. return this._internalPick(function (world) {
  21281. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21282. return _this._tempPickingRay;
  21283. }, predicate, fastCheck);
  21284. };
  21285. /** Launch a ray to try to pick a sprite in the scene
  21286. * @param x position on screen
  21287. * @param y position on screen
  21288. * @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
  21289. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21290. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21291. */
  21292. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21293. if (!this._tempPickingRay) {
  21294. this._tempPickingRay = BABYLON.Ray.Zero();
  21295. }
  21296. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21297. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21298. };
  21299. /** Use the given ray to pick a mesh in the scene
  21300. * @param ray The ray to use to pick meshes
  21301. * @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
  21302. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21303. */
  21304. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21305. var _this = this;
  21306. return this._internalPick(function (world) {
  21307. if (!_this._pickWithRayInverseMatrix) {
  21308. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21309. }
  21310. world.invertToRef(_this._pickWithRayInverseMatrix);
  21311. if (!_this._cachedRayForTransform) {
  21312. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21313. }
  21314. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21315. return _this._cachedRayForTransform;
  21316. }, predicate, fastCheck);
  21317. };
  21318. /**
  21319. * Launch a ray to try to pick a mesh in the scene
  21320. * @param x X position on screen
  21321. * @param y Y position on screen
  21322. * @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
  21323. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21324. */
  21325. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21326. var _this = this;
  21327. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21328. };
  21329. /**
  21330. * Launch a ray to try to pick a mesh in the scene
  21331. * @param ray Ray to use
  21332. * @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
  21333. */
  21334. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21335. var _this = this;
  21336. return this._internalMultiPick(function (world) {
  21337. if (!_this._pickWithRayInverseMatrix) {
  21338. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21339. }
  21340. world.invertToRef(_this._pickWithRayInverseMatrix);
  21341. if (!_this._cachedRayForTransform) {
  21342. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21343. }
  21344. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21345. return _this._cachedRayForTransform;
  21346. }, predicate);
  21347. };
  21348. Scene.prototype.setPointerOverMesh = function (mesh) {
  21349. if (this._pointerOverMesh === mesh) {
  21350. return;
  21351. }
  21352. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21353. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21354. }
  21355. this._pointerOverMesh = mesh;
  21356. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21357. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21358. }
  21359. };
  21360. Scene.prototype.getPointerOverMesh = function () {
  21361. return this._pointerOverMesh;
  21362. };
  21363. Scene.prototype.setPointerOverSprite = function (sprite) {
  21364. if (this._pointerOverSprite === sprite) {
  21365. return;
  21366. }
  21367. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21368. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21369. }
  21370. this._pointerOverSprite = sprite;
  21371. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21372. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21373. }
  21374. };
  21375. Scene.prototype.getPointerOverSprite = function () {
  21376. return this._pointerOverSprite;
  21377. };
  21378. // Physics
  21379. Scene.prototype.getPhysicsEngine = function () {
  21380. return this._physicsEngine;
  21381. };
  21382. /**
  21383. * Enables physics to the current scene
  21384. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21385. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21386. * @return {boolean} was the physics engine initialized
  21387. */
  21388. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21389. if (gravity === void 0) { gravity = null; }
  21390. if (this._physicsEngine) {
  21391. return true;
  21392. }
  21393. try {
  21394. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21395. return true;
  21396. }
  21397. catch (e) {
  21398. BABYLON.Tools.Error(e.message);
  21399. return false;
  21400. }
  21401. };
  21402. Scene.prototype.disablePhysicsEngine = function () {
  21403. if (!this._physicsEngine) {
  21404. return;
  21405. }
  21406. this._physicsEngine.dispose();
  21407. this._physicsEngine = null;
  21408. };
  21409. Scene.prototype.isPhysicsEnabled = function () {
  21410. return this._physicsEngine !== undefined;
  21411. };
  21412. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21413. var mesh = compound.parts[0].mesh;
  21414. if (mesh.physicsImpostor) {
  21415. mesh.physicsImpostor.dispose();
  21416. mesh.physicsImpostor = null;
  21417. }
  21418. };
  21419. // Misc.
  21420. Scene.prototype._rebuildGeometries = function () {
  21421. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21422. var geometry = _a[_i];
  21423. geometry._rebuild();
  21424. }
  21425. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21426. var mesh = _c[_b];
  21427. mesh._rebuild();
  21428. }
  21429. if (this.postProcessManager) {
  21430. this.postProcessManager._rebuild();
  21431. }
  21432. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21433. var layer = _e[_d];
  21434. layer._rebuild();
  21435. }
  21436. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21437. var highlightLayer = _g[_f];
  21438. highlightLayer._rebuild();
  21439. }
  21440. if (this._boundingBoxRenderer) {
  21441. this._boundingBoxRenderer._rebuild();
  21442. }
  21443. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21444. var system = _j[_h];
  21445. system.rebuild();
  21446. }
  21447. if (this._postProcessRenderPipelineManager) {
  21448. this._postProcessRenderPipelineManager._rebuild();
  21449. }
  21450. };
  21451. Scene.prototype._rebuildTextures = function () {
  21452. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21453. var texture = _a[_i];
  21454. texture._rebuild();
  21455. }
  21456. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21457. };
  21458. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21459. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21460. if (replace === void 0) { replace = false; }
  21461. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21462. // Dispose existing camera or light in replace mode.
  21463. if (replace) {
  21464. if (this.activeCamera) {
  21465. this.activeCamera.dispose();
  21466. this.activeCamera = null;
  21467. }
  21468. if (this.lights) {
  21469. for (var i = 0; i < this.lights.length; i++) {
  21470. this.lights[i].dispose();
  21471. }
  21472. }
  21473. }
  21474. // Light
  21475. if (this.lights.length === 0) {
  21476. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21477. }
  21478. // Camera
  21479. if (!this.activeCamera) {
  21480. var worldExtends = this.getWorldExtends();
  21481. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21482. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21483. var camera;
  21484. var radius = worldSize.length() * 1.5;
  21485. if (createArcRotateCamera) {
  21486. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21487. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21488. arcRotateCamera.wheelPrecision = 100 / radius;
  21489. camera = arcRotateCamera;
  21490. }
  21491. else {
  21492. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21493. freeCamera.setTarget(worldCenter);
  21494. camera = freeCamera;
  21495. }
  21496. camera.minZ = radius * 0.01;
  21497. camera.maxZ = radius * 100;
  21498. camera.speed = radius * 0.2;
  21499. this.activeCamera = camera;
  21500. var canvas = this.getEngine().getRenderingCanvas();
  21501. if (attachCameraControls && canvas) {
  21502. camera.attachControl(canvas);
  21503. }
  21504. }
  21505. };
  21506. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21507. if (pbr === void 0) { pbr = false; }
  21508. if (scale === void 0) { scale = 1000; }
  21509. if (blur === void 0) { blur = 0; }
  21510. if (environmentTexture) {
  21511. this.environmentTexture = environmentTexture;
  21512. }
  21513. if (!this.environmentTexture) {
  21514. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21515. return null;
  21516. }
  21517. // Skybox
  21518. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21519. if (pbr) {
  21520. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21521. hdrSkyboxMaterial.backFaceCulling = false;
  21522. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21523. if (hdrSkyboxMaterial.reflectionTexture) {
  21524. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21525. }
  21526. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21527. hdrSkyboxMaterial.disableLighting = true;
  21528. hdrSkyboxMaterial.twoSidedLighting = true;
  21529. hdrSkybox.infiniteDistance = true;
  21530. hdrSkybox.material = hdrSkyboxMaterial;
  21531. }
  21532. else {
  21533. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21534. skyboxMaterial.backFaceCulling = false;
  21535. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21536. if (skyboxMaterial.reflectionTexture) {
  21537. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21538. }
  21539. skyboxMaterial.disableLighting = true;
  21540. hdrSkybox.infiniteDistance = true;
  21541. hdrSkybox.material = skyboxMaterial;
  21542. }
  21543. return hdrSkybox;
  21544. };
  21545. Scene.prototype.createDefaultEnvironment = function (options) {
  21546. if (BABYLON.EnvironmentHelper) {
  21547. return new BABYLON.EnvironmentHelper(options, this);
  21548. }
  21549. return null;
  21550. };
  21551. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21552. if (webVROptions === void 0) { webVROptions = {}; }
  21553. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21554. };
  21555. // Tags
  21556. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21557. if (tagsQuery === undefined) {
  21558. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21559. return list;
  21560. }
  21561. var listByTags = [];
  21562. forEach = forEach || (function (item) { return; });
  21563. for (var i in list) {
  21564. var item = list[i];
  21565. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21566. listByTags.push(item);
  21567. forEach(item);
  21568. }
  21569. }
  21570. return listByTags;
  21571. };
  21572. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21573. return this._getByTags(this.meshes, tagsQuery, forEach);
  21574. };
  21575. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21576. return this._getByTags(this.cameras, tagsQuery, forEach);
  21577. };
  21578. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21579. return this._getByTags(this.lights, tagsQuery, forEach);
  21580. };
  21581. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21582. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21583. };
  21584. /**
  21585. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21586. * This allowed control for front to back rendering or reversly depending of the special needs.
  21587. *
  21588. * @param renderingGroupId The rendering group id corresponding to its index
  21589. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21590. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21591. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21592. */
  21593. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21594. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21595. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21596. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21597. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21598. };
  21599. /**
  21600. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21601. *
  21602. * @param renderingGroupId The rendering group id corresponding to its index
  21603. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21604. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21605. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21606. */
  21607. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21608. if (depth === void 0) { depth = true; }
  21609. if (stencil === void 0) { stencil = true; }
  21610. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21611. };
  21612. /**
  21613. * Will flag all materials as dirty to trigger new shader compilation
  21614. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21615. */
  21616. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21617. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21618. var material = _a[_i];
  21619. if (predicate && !predicate(material)) {
  21620. continue;
  21621. }
  21622. material.markAsDirty(flag);
  21623. }
  21624. };
  21625. // Statics
  21626. Scene._FOGMODE_NONE = 0;
  21627. Scene._FOGMODE_EXP = 1;
  21628. Scene._FOGMODE_EXP2 = 2;
  21629. Scene._FOGMODE_LINEAR = 3;
  21630. Scene._uniqueIdCounter = 0;
  21631. Scene.MinDeltaTime = 1.0;
  21632. Scene.MaxDeltaTime = 1000.0;
  21633. /** The distance in pixel that you have to move to prevent some events */
  21634. Scene.DragMovementThreshold = 10; // in pixels
  21635. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21636. Scene.LongPressDelay = 500; // in milliseconds
  21637. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21638. Scene.DoubleClickDelay = 300; // in milliseconds
  21639. /** If you need to check double click without raising a single click at first click, enable this flag */
  21640. Scene.ExclusiveDoubleClickMode = false;
  21641. return Scene;
  21642. }());
  21643. BABYLON.Scene = Scene;
  21644. })(BABYLON || (BABYLON = {}));
  21645. //# sourceMappingURL=babylon.scene.js.map
  21646. var BABYLON;
  21647. (function (BABYLON) {
  21648. var Buffer = /** @class */ (function () {
  21649. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21650. if (instanced === void 0) { instanced = false; }
  21651. if (engine instanceof BABYLON.Mesh) {
  21652. this._engine = engine.getScene().getEngine();
  21653. }
  21654. else {
  21655. this._engine = engine;
  21656. }
  21657. this._updatable = updatable;
  21658. this._data = data;
  21659. this._strideSize = stride;
  21660. if (!postponeInternalCreation) {
  21661. this.create();
  21662. }
  21663. this._instanced = instanced;
  21664. this._instanceDivisor = instanced ? 1 : 0;
  21665. }
  21666. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21667. // a lot of these parameters are ignored as they are overriden by the buffer
  21668. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21669. };
  21670. // Properties
  21671. Buffer.prototype.isUpdatable = function () {
  21672. return this._updatable;
  21673. };
  21674. Buffer.prototype.getData = function () {
  21675. return this._data;
  21676. };
  21677. Buffer.prototype.getBuffer = function () {
  21678. return this._buffer;
  21679. };
  21680. Buffer.prototype.getStrideSize = function () {
  21681. return this._strideSize;
  21682. };
  21683. Buffer.prototype.getIsInstanced = function () {
  21684. return this._instanced;
  21685. };
  21686. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21687. get: function () {
  21688. return this._instanceDivisor;
  21689. },
  21690. set: function (value) {
  21691. this._instanceDivisor = value;
  21692. if (value == 0) {
  21693. this._instanced = false;
  21694. }
  21695. else {
  21696. this._instanced = true;
  21697. }
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. // Methods
  21703. Buffer.prototype.create = function (data) {
  21704. if (data === void 0) { data = null; }
  21705. if (!data && this._buffer) {
  21706. return; // nothing to do
  21707. }
  21708. data = data || this._data;
  21709. if (!data) {
  21710. return;
  21711. }
  21712. if (!this._buffer) {
  21713. if (this._updatable) {
  21714. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21715. this._data = data;
  21716. }
  21717. else {
  21718. this._buffer = this._engine.createVertexBuffer(data);
  21719. }
  21720. }
  21721. else if (this._updatable) {
  21722. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21723. this._data = data;
  21724. }
  21725. };
  21726. Buffer.prototype._rebuild = function () {
  21727. this._buffer = null;
  21728. this.create(this._data);
  21729. };
  21730. Buffer.prototype.update = function (data) {
  21731. this.create(data);
  21732. };
  21733. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21734. if (!this._buffer) {
  21735. return;
  21736. }
  21737. if (this._updatable) {
  21738. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21739. this._data = null;
  21740. }
  21741. };
  21742. Buffer.prototype.dispose = function () {
  21743. if (!this._buffer) {
  21744. return;
  21745. }
  21746. if (this._engine._releaseBuffer(this._buffer)) {
  21747. this._buffer = null;
  21748. }
  21749. };
  21750. return Buffer;
  21751. }());
  21752. BABYLON.Buffer = Buffer;
  21753. })(BABYLON || (BABYLON = {}));
  21754. //# sourceMappingURL=babylon.buffer.js.map
  21755. var BABYLON;
  21756. (function (BABYLON) {
  21757. var VertexBuffer = /** @class */ (function () {
  21758. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21759. if (!stride) {
  21760. // Deduce stride from kind
  21761. switch (kind) {
  21762. case VertexBuffer.PositionKind:
  21763. stride = 3;
  21764. break;
  21765. case VertexBuffer.NormalKind:
  21766. stride = 3;
  21767. break;
  21768. case VertexBuffer.UVKind:
  21769. case VertexBuffer.UV2Kind:
  21770. case VertexBuffer.UV3Kind:
  21771. case VertexBuffer.UV4Kind:
  21772. case VertexBuffer.UV5Kind:
  21773. case VertexBuffer.UV6Kind:
  21774. stride = 2;
  21775. break;
  21776. case VertexBuffer.TangentKind:
  21777. case VertexBuffer.ColorKind:
  21778. stride = 4;
  21779. break;
  21780. case VertexBuffer.MatricesIndicesKind:
  21781. case VertexBuffer.MatricesIndicesExtraKind:
  21782. stride = 4;
  21783. break;
  21784. case VertexBuffer.MatricesWeightsKind:
  21785. case VertexBuffer.MatricesWeightsExtraKind:
  21786. default:
  21787. stride = 4;
  21788. break;
  21789. }
  21790. }
  21791. if (data instanceof BABYLON.Buffer) {
  21792. if (!stride) {
  21793. stride = data.getStrideSize();
  21794. }
  21795. this._buffer = data;
  21796. this._ownsBuffer = false;
  21797. }
  21798. else {
  21799. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21800. this._ownsBuffer = true;
  21801. }
  21802. this._stride = stride;
  21803. this._offset = offset ? offset : 0;
  21804. this._size = size ? size : stride;
  21805. this._kind = kind;
  21806. }
  21807. VertexBuffer.prototype._rebuild = function () {
  21808. if (!this._buffer) {
  21809. return;
  21810. }
  21811. this._buffer._rebuild();
  21812. };
  21813. /**
  21814. * Returns the kind of the VertexBuffer (string).
  21815. */
  21816. VertexBuffer.prototype.getKind = function () {
  21817. return this._kind;
  21818. };
  21819. // Properties
  21820. /**
  21821. * Boolean : is the VertexBuffer updatable ?
  21822. */
  21823. VertexBuffer.prototype.isUpdatable = function () {
  21824. return this._buffer.isUpdatable();
  21825. };
  21826. /**
  21827. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21828. */
  21829. VertexBuffer.prototype.getData = function () {
  21830. return this._buffer.getData();
  21831. };
  21832. /**
  21833. * Returns the WebGLBuffer associated to the VertexBuffer.
  21834. */
  21835. VertexBuffer.prototype.getBuffer = function () {
  21836. return this._buffer.getBuffer();
  21837. };
  21838. /**
  21839. * Returns the stride of the VertexBuffer (integer).
  21840. */
  21841. VertexBuffer.prototype.getStrideSize = function () {
  21842. return this._stride;
  21843. };
  21844. /**
  21845. * Returns the offset (integer).
  21846. */
  21847. VertexBuffer.prototype.getOffset = function () {
  21848. return this._offset;
  21849. };
  21850. /**
  21851. * Returns the VertexBuffer total size (integer).
  21852. */
  21853. VertexBuffer.prototype.getSize = function () {
  21854. return this._size;
  21855. };
  21856. /**
  21857. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21858. */
  21859. VertexBuffer.prototype.getIsInstanced = function () {
  21860. return this._buffer.getIsInstanced();
  21861. };
  21862. /**
  21863. * Returns the instancing divisor, zero for non-instanced (integer).
  21864. */
  21865. VertexBuffer.prototype.getInstanceDivisor = function () {
  21866. return this._buffer.instanceDivisor;
  21867. };
  21868. // Methods
  21869. /**
  21870. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21871. * Returns the created WebGLBuffer.
  21872. */
  21873. VertexBuffer.prototype.create = function (data) {
  21874. return this._buffer.create(data);
  21875. };
  21876. /**
  21877. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21878. * Returns the updated WebGLBuffer.
  21879. */
  21880. VertexBuffer.prototype.update = function (data) {
  21881. return this._buffer.update(data);
  21882. };
  21883. /**
  21884. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21885. * Returns the directly updated WebGLBuffer.
  21886. */
  21887. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21888. return this._buffer.updateDirectly(data, offset);
  21889. };
  21890. /**
  21891. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21892. */
  21893. VertexBuffer.prototype.dispose = function () {
  21894. if (this._ownsBuffer) {
  21895. this._buffer.dispose();
  21896. }
  21897. };
  21898. Object.defineProperty(VertexBuffer, "PositionKind", {
  21899. get: function () {
  21900. return VertexBuffer._PositionKind;
  21901. },
  21902. enumerable: true,
  21903. configurable: true
  21904. });
  21905. Object.defineProperty(VertexBuffer, "NormalKind", {
  21906. get: function () {
  21907. return VertexBuffer._NormalKind;
  21908. },
  21909. enumerable: true,
  21910. configurable: true
  21911. });
  21912. Object.defineProperty(VertexBuffer, "TangentKind", {
  21913. get: function () {
  21914. return VertexBuffer._TangentKind;
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(VertexBuffer, "UVKind", {
  21920. get: function () {
  21921. return VertexBuffer._UVKind;
  21922. },
  21923. enumerable: true,
  21924. configurable: true
  21925. });
  21926. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21927. get: function () {
  21928. return VertexBuffer._UV2Kind;
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21934. get: function () {
  21935. return VertexBuffer._UV3Kind;
  21936. },
  21937. enumerable: true,
  21938. configurable: true
  21939. });
  21940. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21941. get: function () {
  21942. return VertexBuffer._UV4Kind;
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21948. get: function () {
  21949. return VertexBuffer._UV5Kind;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21955. get: function () {
  21956. return VertexBuffer._UV6Kind;
  21957. },
  21958. enumerable: true,
  21959. configurable: true
  21960. });
  21961. Object.defineProperty(VertexBuffer, "ColorKind", {
  21962. get: function () {
  21963. return VertexBuffer._ColorKind;
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21969. get: function () {
  21970. return VertexBuffer._MatricesIndicesKind;
  21971. },
  21972. enumerable: true,
  21973. configurable: true
  21974. });
  21975. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21976. get: function () {
  21977. return VertexBuffer._MatricesWeightsKind;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21983. get: function () {
  21984. return VertexBuffer._MatricesIndicesExtraKind;
  21985. },
  21986. enumerable: true,
  21987. configurable: true
  21988. });
  21989. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21990. get: function () {
  21991. return VertexBuffer._MatricesWeightsExtraKind;
  21992. },
  21993. enumerable: true,
  21994. configurable: true
  21995. });
  21996. // Enums
  21997. VertexBuffer._PositionKind = "position";
  21998. VertexBuffer._NormalKind = "normal";
  21999. VertexBuffer._TangentKind = "tangent";
  22000. VertexBuffer._UVKind = "uv";
  22001. VertexBuffer._UV2Kind = "uv2";
  22002. VertexBuffer._UV3Kind = "uv3";
  22003. VertexBuffer._UV4Kind = "uv4";
  22004. VertexBuffer._UV5Kind = "uv5";
  22005. VertexBuffer._UV6Kind = "uv6";
  22006. VertexBuffer._ColorKind = "color";
  22007. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22008. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22009. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22010. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22011. return VertexBuffer;
  22012. }());
  22013. BABYLON.VertexBuffer = VertexBuffer;
  22014. })(BABYLON || (BABYLON = {}));
  22015. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22016. var BABYLON;
  22017. (function (BABYLON) {
  22018. var InternalTexture = /** @class */ (function () {
  22019. function InternalTexture(engine, dataSource) {
  22020. this.onLoadedObservable = new BABYLON.Observable();
  22021. // Private
  22022. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22023. this._references = 1;
  22024. this._engine = engine;
  22025. this._dataSource = dataSource;
  22026. this._webGLTexture = engine._createTexture();
  22027. }
  22028. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22029. get: function () {
  22030. return this._dataSource;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. InternalTexture.prototype.incrementReferences = function () {
  22036. this._references++;
  22037. };
  22038. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22039. if (depth === void 0) { depth = 1; }
  22040. this.width = width;
  22041. this.height = height;
  22042. this.depth = depth;
  22043. this.baseWidth = width;
  22044. this.baseHeight = height;
  22045. this.baseDepth = depth;
  22046. this._size = width * height * depth;
  22047. };
  22048. InternalTexture.prototype._rebuild = function () {
  22049. var _this = this;
  22050. var proxy;
  22051. this.isReady = false;
  22052. this._cachedCoordinatesMode = null;
  22053. this._cachedWrapU = null;
  22054. this._cachedWrapV = null;
  22055. this._cachedAnisotropicFilteringLevel = null;
  22056. switch (this._dataSource) {
  22057. case InternalTexture.DATASOURCE_TEMP:
  22058. return;
  22059. case InternalTexture.DATASOURCE_URL:
  22060. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22061. _this.isReady = true;
  22062. }, null, this._buffer, undefined, this.format);
  22063. proxy._swapAndDie(this);
  22064. return;
  22065. case InternalTexture.DATASOURCE_RAW:
  22066. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22067. proxy._swapAndDie(this);
  22068. this.isReady = true;
  22069. return;
  22070. case InternalTexture.DATASOURCE_RAW3D:
  22071. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22072. proxy._swapAndDie(this);
  22073. this.isReady = true;
  22074. return;
  22075. case InternalTexture.DATASOURCE_DYNAMIC:
  22076. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22077. proxy._swapAndDie(this);
  22078. // The engine will make sure to update content so no need to flag it as isReady = true
  22079. return;
  22080. case InternalTexture.DATASOURCE_RENDERTARGET:
  22081. var options = new BABYLON.RenderTargetCreationOptions();
  22082. options.generateDepthBuffer = this._generateDepthBuffer;
  22083. options.generateMipMaps = this.generateMipMaps;
  22084. options.generateStencilBuffer = this._generateStencilBuffer;
  22085. options.samplingMode = this.samplingMode;
  22086. options.type = this.type;
  22087. if (this.isCube) {
  22088. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22089. }
  22090. else {
  22091. var size = {
  22092. width: this.width,
  22093. height: this.height
  22094. };
  22095. proxy = this._engine.createRenderTargetTexture(size, options);
  22096. }
  22097. proxy._swapAndDie(this);
  22098. this.isReady = true;
  22099. return;
  22100. case InternalTexture.DATASOURCE_CUBE:
  22101. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22102. _this.isReady = true;
  22103. }, null, this.format, this._extension);
  22104. proxy._swapAndDie(this);
  22105. return;
  22106. case InternalTexture.DATASOURCE_CUBERAW:
  22107. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22108. proxy._swapAndDie(this);
  22109. this.isReady = true;
  22110. return;
  22111. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22112. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22113. if (proxy) {
  22114. proxy._swapAndDie(_this);
  22115. }
  22116. _this.isReady = true;
  22117. }, null, this.format, this._extension);
  22118. return;
  22119. }
  22120. };
  22121. InternalTexture.prototype._swapAndDie = function (target) {
  22122. target._webGLTexture = this._webGLTexture;
  22123. if (this._framebuffer) {
  22124. target._framebuffer = this._framebuffer;
  22125. }
  22126. if (this._depthStencilBuffer) {
  22127. target._depthStencilBuffer = this._depthStencilBuffer;
  22128. }
  22129. if (this._lodTextureHigh) {
  22130. if (target._lodTextureHigh) {
  22131. target._lodTextureHigh.dispose();
  22132. }
  22133. target._lodTextureHigh = this._lodTextureHigh;
  22134. }
  22135. if (this._lodTextureMid) {
  22136. if (target._lodTextureMid) {
  22137. target._lodTextureMid.dispose();
  22138. }
  22139. target._lodTextureMid = this._lodTextureMid;
  22140. }
  22141. if (this._lodTextureLow) {
  22142. if (target._lodTextureLow) {
  22143. target._lodTextureLow.dispose();
  22144. }
  22145. target._lodTextureLow = this._lodTextureLow;
  22146. }
  22147. var cache = this._engine.getLoadedTexturesCache();
  22148. var index = cache.indexOf(this);
  22149. if (index !== -1) {
  22150. cache.splice(index, 1);
  22151. }
  22152. };
  22153. InternalTexture.prototype.dispose = function () {
  22154. if (!this._webGLTexture) {
  22155. return;
  22156. }
  22157. this._references--;
  22158. if (this._references === 0) {
  22159. this._engine._releaseTexture(this);
  22160. this._webGLTexture = null;
  22161. }
  22162. };
  22163. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22164. InternalTexture.DATASOURCE_URL = 1;
  22165. InternalTexture.DATASOURCE_TEMP = 2;
  22166. InternalTexture.DATASOURCE_RAW = 3;
  22167. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22168. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22169. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22170. InternalTexture.DATASOURCE_CUBE = 7;
  22171. InternalTexture.DATASOURCE_CUBERAW = 8;
  22172. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22173. InternalTexture.DATASOURCE_RAW3D = 10;
  22174. return InternalTexture;
  22175. }());
  22176. BABYLON.InternalTexture = InternalTexture;
  22177. })(BABYLON || (BABYLON = {}));
  22178. //# sourceMappingURL=babylon.internalTexture.js.map
  22179. var BABYLON;
  22180. (function (BABYLON) {
  22181. var BaseTexture = /** @class */ (function () {
  22182. function BaseTexture(scene) {
  22183. this._hasAlpha = false;
  22184. this.getAlphaFromRGB = false;
  22185. this.level = 1;
  22186. this.coordinatesIndex = 0;
  22187. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22188. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22189. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22190. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22191. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22192. this.isCube = false;
  22193. this.is3D = false;
  22194. this.gammaSpace = true;
  22195. this.invertZ = false;
  22196. this.lodLevelInAlpha = false;
  22197. this.lodGenerationOffset = 0.0;
  22198. this.lodGenerationScale = 0.8;
  22199. this.isRenderTarget = false;
  22200. this.animations = new Array();
  22201. /**
  22202. * An event triggered when the texture is disposed.
  22203. * @type {BABYLON.Observable}
  22204. */
  22205. this.onDisposeObservable = new BABYLON.Observable();
  22206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22207. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22208. if (this._scene) {
  22209. this._scene.textures.push(this);
  22210. }
  22211. this._uid = null;
  22212. }
  22213. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22214. get: function () {
  22215. return this._hasAlpha;
  22216. },
  22217. set: function (value) {
  22218. if (this._hasAlpha === value) {
  22219. return;
  22220. }
  22221. this._hasAlpha = value;
  22222. if (this._scene) {
  22223. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22224. }
  22225. },
  22226. enumerable: true,
  22227. configurable: true
  22228. });
  22229. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22230. get: function () {
  22231. return this._coordinatesMode;
  22232. },
  22233. set: function (value) {
  22234. if (this._coordinatesMode === value) {
  22235. return;
  22236. }
  22237. this._coordinatesMode = value;
  22238. if (this._scene) {
  22239. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22240. }
  22241. },
  22242. enumerable: true,
  22243. configurable: true
  22244. });
  22245. Object.defineProperty(BaseTexture.prototype, "uid", {
  22246. get: function () {
  22247. if (!this._uid) {
  22248. this._uid = BABYLON.Tools.RandomId();
  22249. }
  22250. return this._uid;
  22251. },
  22252. enumerable: true,
  22253. configurable: true
  22254. });
  22255. BaseTexture.prototype.toString = function () {
  22256. return this.name;
  22257. };
  22258. BaseTexture.prototype.getClassName = function () {
  22259. return "BaseTexture";
  22260. };
  22261. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22262. set: function (callback) {
  22263. if (this._onDisposeObserver) {
  22264. this.onDisposeObservable.remove(this._onDisposeObserver);
  22265. }
  22266. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22272. get: function () {
  22273. return true;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. BaseTexture.prototype.getScene = function () {
  22279. return this._scene;
  22280. };
  22281. BaseTexture.prototype.getTextureMatrix = function () {
  22282. return BABYLON.Matrix.IdentityReadOnly;
  22283. };
  22284. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22285. return BABYLON.Matrix.IdentityReadOnly;
  22286. };
  22287. BaseTexture.prototype.getInternalTexture = function () {
  22288. return this._texture;
  22289. };
  22290. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22291. return !this.isBlocking || this.isReady();
  22292. };
  22293. BaseTexture.prototype.isReady = function () {
  22294. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22295. this.delayLoad();
  22296. return false;
  22297. }
  22298. if (this._texture) {
  22299. return this._texture.isReady;
  22300. }
  22301. return false;
  22302. };
  22303. BaseTexture.prototype.getSize = function () {
  22304. if (this._texture && this._texture.width) {
  22305. return new BABYLON.Size(this._texture.width, this._texture.height);
  22306. }
  22307. if (this._texture && this._texture._size) {
  22308. return new BABYLON.Size(this._texture._size, this._texture._size);
  22309. }
  22310. return BABYLON.Size.Zero();
  22311. };
  22312. BaseTexture.prototype.getBaseSize = function () {
  22313. if (!this.isReady() || !this._texture)
  22314. return BABYLON.Size.Zero();
  22315. if (this._texture._size) {
  22316. return new BABYLON.Size(this._texture._size, this._texture._size);
  22317. }
  22318. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22319. };
  22320. BaseTexture.prototype.scale = function (ratio) {
  22321. };
  22322. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22323. get: function () {
  22324. return false;
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22330. if (!this._scene) {
  22331. return null;
  22332. }
  22333. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22334. for (var index = 0; index < texturesCache.length; index++) {
  22335. var texturesCacheEntry = texturesCache[index];
  22336. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22337. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22338. texturesCacheEntry.incrementReferences();
  22339. return texturesCacheEntry;
  22340. }
  22341. }
  22342. }
  22343. return null;
  22344. };
  22345. BaseTexture.prototype._rebuild = function () {
  22346. };
  22347. BaseTexture.prototype.delayLoad = function () {
  22348. };
  22349. BaseTexture.prototype.clone = function () {
  22350. return null;
  22351. };
  22352. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22353. get: function () {
  22354. if (!this._texture) {
  22355. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22356. }
  22357. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22363. get: function () {
  22364. if (!this._texture) {
  22365. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22366. }
  22367. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. BaseTexture.prototype.readPixels = function (faceIndex) {
  22373. if (faceIndex === void 0) { faceIndex = 0; }
  22374. if (!this._texture) {
  22375. return null;
  22376. }
  22377. var size = this.getSize();
  22378. var scene = this.getScene();
  22379. if (!scene) {
  22380. return null;
  22381. }
  22382. var engine = scene.getEngine();
  22383. if (this._texture.isCube) {
  22384. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22385. }
  22386. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22387. };
  22388. BaseTexture.prototype.releaseInternalTexture = function () {
  22389. if (this._texture) {
  22390. this._texture.dispose();
  22391. this._texture = null;
  22392. }
  22393. };
  22394. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22395. get: function () {
  22396. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22397. return null;
  22398. }
  22399. if (!this._texture._sphericalPolynomial) {
  22400. this._texture._sphericalPolynomial =
  22401. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22402. }
  22403. return this._texture._sphericalPolynomial;
  22404. },
  22405. set: function (value) {
  22406. if (this._texture) {
  22407. this._texture._sphericalPolynomial = value;
  22408. }
  22409. },
  22410. enumerable: true,
  22411. configurable: true
  22412. });
  22413. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22414. get: function () {
  22415. if (this._texture) {
  22416. return this._texture._lodTextureHigh;
  22417. }
  22418. return null;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22424. get: function () {
  22425. if (this._texture) {
  22426. return this._texture._lodTextureMid;
  22427. }
  22428. return null;
  22429. },
  22430. enumerable: true,
  22431. configurable: true
  22432. });
  22433. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22434. get: function () {
  22435. if (this._texture) {
  22436. return this._texture._lodTextureLow;
  22437. }
  22438. return null;
  22439. },
  22440. enumerable: true,
  22441. configurable: true
  22442. });
  22443. BaseTexture.prototype.dispose = function () {
  22444. if (!this._scene) {
  22445. return;
  22446. }
  22447. // Animations
  22448. this._scene.stopAnimation(this);
  22449. // Remove from scene
  22450. this._scene._removePendingData(this);
  22451. var index = this._scene.textures.indexOf(this);
  22452. if (index >= 0) {
  22453. this._scene.textures.splice(index, 1);
  22454. }
  22455. if (this._texture === undefined) {
  22456. return;
  22457. }
  22458. // Release
  22459. this.releaseInternalTexture();
  22460. // Callback
  22461. this.onDisposeObservable.notifyObservers(this);
  22462. this.onDisposeObservable.clear();
  22463. };
  22464. BaseTexture.prototype.serialize = function () {
  22465. if (!this.name) {
  22466. return null;
  22467. }
  22468. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22469. // Animations
  22470. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22471. return serializationObject;
  22472. };
  22473. BaseTexture.WhenAllReady = function (textures, callback) {
  22474. var numRemaining = textures.length;
  22475. if (numRemaining === 0) {
  22476. callback();
  22477. return;
  22478. }
  22479. var _loop_1 = function () {
  22480. texture = textures[i];
  22481. if (texture.isReady()) {
  22482. if (--numRemaining === 0) {
  22483. callback();
  22484. }
  22485. }
  22486. else {
  22487. onLoadObservable = texture.onLoadObservable;
  22488. var onLoadCallback_1 = function () {
  22489. onLoadObservable.removeCallback(onLoadCallback_1);
  22490. if (--numRemaining === 0) {
  22491. callback();
  22492. }
  22493. };
  22494. onLoadObservable.add(onLoadCallback_1);
  22495. }
  22496. };
  22497. var texture, onLoadObservable;
  22498. for (var i = 0; i < textures.length; i++) {
  22499. _loop_1();
  22500. }
  22501. };
  22502. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22503. __decorate([
  22504. BABYLON.serialize()
  22505. ], BaseTexture.prototype, "name", void 0);
  22506. __decorate([
  22507. BABYLON.serialize("hasAlpha")
  22508. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22509. __decorate([
  22510. BABYLON.serialize()
  22511. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22512. __decorate([
  22513. BABYLON.serialize()
  22514. ], BaseTexture.prototype, "level", void 0);
  22515. __decorate([
  22516. BABYLON.serialize()
  22517. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22518. __decorate([
  22519. BABYLON.serialize("coordinatesMode")
  22520. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22521. __decorate([
  22522. BABYLON.serialize()
  22523. ], BaseTexture.prototype, "wrapU", void 0);
  22524. __decorate([
  22525. BABYLON.serialize()
  22526. ], BaseTexture.prototype, "wrapV", void 0);
  22527. __decorate([
  22528. BABYLON.serialize()
  22529. ], BaseTexture.prototype, "wrapR", void 0);
  22530. __decorate([
  22531. BABYLON.serialize()
  22532. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22533. __decorate([
  22534. BABYLON.serialize()
  22535. ], BaseTexture.prototype, "isCube", void 0);
  22536. __decorate([
  22537. BABYLON.serialize()
  22538. ], BaseTexture.prototype, "is3D", void 0);
  22539. __decorate([
  22540. BABYLON.serialize()
  22541. ], BaseTexture.prototype, "gammaSpace", void 0);
  22542. __decorate([
  22543. BABYLON.serialize()
  22544. ], BaseTexture.prototype, "invertZ", void 0);
  22545. __decorate([
  22546. BABYLON.serialize()
  22547. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22548. __decorate([
  22549. BABYLON.serialize()
  22550. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22551. __decorate([
  22552. BABYLON.serialize()
  22553. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22554. __decorate([
  22555. BABYLON.serialize()
  22556. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22557. return BaseTexture;
  22558. }());
  22559. BABYLON.BaseTexture = BaseTexture;
  22560. })(BABYLON || (BABYLON = {}));
  22561. //# sourceMappingURL=babylon.baseTexture.js.map
  22562. var BABYLON;
  22563. (function (BABYLON) {
  22564. var Texture = /** @class */ (function (_super) {
  22565. __extends(Texture, _super);
  22566. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22567. if (noMipmap === void 0) { noMipmap = false; }
  22568. if (invertY === void 0) { invertY = true; }
  22569. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22570. if (onLoad === void 0) { onLoad = null; }
  22571. if (onError === void 0) { onError = null; }
  22572. if (buffer === void 0) { buffer = null; }
  22573. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22574. var _this = _super.call(this, scene) || this;
  22575. _this.uOffset = 0;
  22576. _this.vOffset = 0;
  22577. _this.uScale = 1.0;
  22578. _this.vScale = 1.0;
  22579. _this.uAng = 0;
  22580. _this.vAng = 0;
  22581. _this.wAng = 0;
  22582. _this._isBlocking = true;
  22583. _this.name = url || "";
  22584. _this.url = url;
  22585. _this._noMipmap = noMipmap;
  22586. _this._invertY = invertY;
  22587. _this._samplingMode = samplingMode;
  22588. _this._buffer = buffer;
  22589. _this._deleteBuffer = deleteBuffer;
  22590. if (format) {
  22591. _this._format = format;
  22592. }
  22593. scene = _this.getScene();
  22594. if (!scene) {
  22595. return _this;
  22596. }
  22597. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22598. var load = function () {
  22599. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22600. _this.onLoadObservable.notifyObservers(_this);
  22601. }
  22602. if (onLoad) {
  22603. onLoad();
  22604. }
  22605. if (!_this.isBlocking && scene) {
  22606. scene.resetCachedMaterial();
  22607. }
  22608. };
  22609. if (!_this.url) {
  22610. _this._delayedOnLoad = load;
  22611. _this._delayedOnError = onError;
  22612. return _this;
  22613. }
  22614. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22615. if (!_this._texture) {
  22616. if (!scene.useDelayedTextureLoading) {
  22617. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22618. if (deleteBuffer) {
  22619. delete _this._buffer;
  22620. }
  22621. }
  22622. else {
  22623. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22624. _this._delayedOnLoad = load;
  22625. _this._delayedOnError = onError;
  22626. }
  22627. }
  22628. else {
  22629. if (_this._texture.isReady) {
  22630. BABYLON.Tools.SetImmediate(function () { return load(); });
  22631. }
  22632. else {
  22633. _this._texture.onLoadedObservable.add(load);
  22634. }
  22635. }
  22636. return _this;
  22637. }
  22638. Object.defineProperty(Texture.prototype, "noMipmap", {
  22639. get: function () {
  22640. return this._noMipmap;
  22641. },
  22642. enumerable: true,
  22643. configurable: true
  22644. });
  22645. Object.defineProperty(Texture.prototype, "isBlocking", {
  22646. get: function () {
  22647. return this._isBlocking;
  22648. },
  22649. set: function (value) {
  22650. this._isBlocking = value;
  22651. },
  22652. enumerable: true,
  22653. configurable: true
  22654. });
  22655. Object.defineProperty(Texture.prototype, "samplingMode", {
  22656. get: function () {
  22657. return this._samplingMode;
  22658. },
  22659. enumerable: true,
  22660. configurable: true
  22661. });
  22662. Texture.prototype.updateURL = function (url) {
  22663. this.url = url;
  22664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22665. this.delayLoad();
  22666. };
  22667. Texture.prototype.delayLoad = function () {
  22668. var _this = this;
  22669. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22670. return;
  22671. }
  22672. var scene = this.getScene();
  22673. if (!scene) {
  22674. return;
  22675. }
  22676. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22677. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22678. if (!this._texture) {
  22679. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22680. if (this._deleteBuffer) {
  22681. delete this._buffer;
  22682. }
  22683. }
  22684. else {
  22685. if (this._texture.isReady) {
  22686. BABYLON.Tools.SetImmediate(function () {
  22687. if (!_this._delayedOnLoad) {
  22688. return;
  22689. }
  22690. _this._delayedOnLoad();
  22691. });
  22692. }
  22693. else {
  22694. if (this._delayedOnLoad) {
  22695. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22696. }
  22697. }
  22698. }
  22699. };
  22700. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22701. if (!this._texture) {
  22702. return;
  22703. }
  22704. var scene = this.getScene();
  22705. if (!scene) {
  22706. return;
  22707. }
  22708. this._samplingMode = samplingMode;
  22709. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22710. };
  22711. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22712. x *= this.uScale;
  22713. y *= this.vScale;
  22714. x -= 0.5 * this.uScale;
  22715. y -= 0.5 * this.vScale;
  22716. z -= 0.5;
  22717. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22718. t.x += 0.5 * this.uScale + this.uOffset;
  22719. t.y += 0.5 * this.vScale + this.vOffset;
  22720. t.z += 0.5;
  22721. };
  22722. Texture.prototype.getTextureMatrix = function () {
  22723. var _this = this;
  22724. if (this.uOffset === this._cachedUOffset &&
  22725. this.vOffset === this._cachedVOffset &&
  22726. this.uScale === this._cachedUScale &&
  22727. this.vScale === this._cachedVScale &&
  22728. this.uAng === this._cachedUAng &&
  22729. this.vAng === this._cachedVAng &&
  22730. this.wAng === this._cachedWAng) {
  22731. return this._cachedTextureMatrix;
  22732. }
  22733. this._cachedUOffset = this.uOffset;
  22734. this._cachedVOffset = this.vOffset;
  22735. this._cachedUScale = this.uScale;
  22736. this._cachedVScale = this.vScale;
  22737. this._cachedUAng = this.uAng;
  22738. this._cachedVAng = this.vAng;
  22739. this._cachedWAng = this.wAng;
  22740. if (!this._cachedTextureMatrix) {
  22741. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22742. this._rowGenerationMatrix = new BABYLON.Matrix();
  22743. this._t0 = BABYLON.Vector3.Zero();
  22744. this._t1 = BABYLON.Vector3.Zero();
  22745. this._t2 = BABYLON.Vector3.Zero();
  22746. }
  22747. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22748. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22749. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22750. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22751. this._t1.subtractInPlace(this._t0);
  22752. this._t2.subtractInPlace(this._t0);
  22753. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22754. this._cachedTextureMatrix.m[0] = this._t1.x;
  22755. this._cachedTextureMatrix.m[1] = this._t1.y;
  22756. this._cachedTextureMatrix.m[2] = this._t1.z;
  22757. this._cachedTextureMatrix.m[4] = this._t2.x;
  22758. this._cachedTextureMatrix.m[5] = this._t2.y;
  22759. this._cachedTextureMatrix.m[6] = this._t2.z;
  22760. this._cachedTextureMatrix.m[8] = this._t0.x;
  22761. this._cachedTextureMatrix.m[9] = this._t0.y;
  22762. this._cachedTextureMatrix.m[10] = this._t0.z;
  22763. var scene = this.getScene();
  22764. if (!scene) {
  22765. return this._cachedTextureMatrix;
  22766. }
  22767. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22768. return mat.hasTexture(_this);
  22769. });
  22770. return this._cachedTextureMatrix;
  22771. };
  22772. Texture.prototype.getReflectionTextureMatrix = function () {
  22773. var _this = this;
  22774. var scene = this.getScene();
  22775. if (!scene) {
  22776. return this._cachedTextureMatrix;
  22777. }
  22778. if (this.uOffset === this._cachedUOffset &&
  22779. this.vOffset === this._cachedVOffset &&
  22780. this.uScale === this._cachedUScale &&
  22781. this.vScale === this._cachedVScale &&
  22782. this.coordinatesMode === this._cachedCoordinatesMode) {
  22783. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22784. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22785. return this._cachedTextureMatrix;
  22786. }
  22787. }
  22788. else {
  22789. return this._cachedTextureMatrix;
  22790. }
  22791. }
  22792. if (!this._cachedTextureMatrix) {
  22793. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22794. }
  22795. if (!this._projectionModeMatrix) {
  22796. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22797. }
  22798. this._cachedUOffset = this.uOffset;
  22799. this._cachedVOffset = this.vOffset;
  22800. this._cachedUScale = this.uScale;
  22801. this._cachedVScale = this.vScale;
  22802. this._cachedCoordinatesMode = this.coordinatesMode;
  22803. switch (this.coordinatesMode) {
  22804. case Texture.PLANAR_MODE:
  22805. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22806. this._cachedTextureMatrix[0] = this.uScale;
  22807. this._cachedTextureMatrix[5] = this.vScale;
  22808. this._cachedTextureMatrix[12] = this.uOffset;
  22809. this._cachedTextureMatrix[13] = this.vOffset;
  22810. break;
  22811. case Texture.PROJECTION_MODE:
  22812. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22813. this._projectionModeMatrix.m[0] = 0.5;
  22814. this._projectionModeMatrix.m[5] = -0.5;
  22815. this._projectionModeMatrix.m[10] = 0.0;
  22816. this._projectionModeMatrix.m[12] = 0.5;
  22817. this._projectionModeMatrix.m[13] = 0.5;
  22818. this._projectionModeMatrix.m[14] = 1.0;
  22819. this._projectionModeMatrix.m[15] = 1.0;
  22820. var projectionMatrix = scene.getProjectionMatrix();
  22821. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22822. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22823. break;
  22824. default:
  22825. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22826. break;
  22827. }
  22828. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22829. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22830. });
  22831. return this._cachedTextureMatrix;
  22832. };
  22833. Texture.prototype.clone = function () {
  22834. var _this = this;
  22835. return BABYLON.SerializationHelper.Clone(function () {
  22836. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22837. }, this);
  22838. };
  22839. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22840. get: function () {
  22841. if (!this._onLoadObservable) {
  22842. this._onLoadObservable = new BABYLON.Observable();
  22843. }
  22844. return this._onLoadObservable;
  22845. },
  22846. enumerable: true,
  22847. configurable: true
  22848. });
  22849. Texture.prototype.serialize = function () {
  22850. var serializationObject = _super.prototype.serialize.call(this);
  22851. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22852. serializationObject.base64String = this._buffer;
  22853. serializationObject.name = serializationObject.name.replace("data:", "");
  22854. }
  22855. return serializationObject;
  22856. };
  22857. Texture.prototype.getClassName = function () {
  22858. return "Texture";
  22859. };
  22860. Texture.prototype.dispose = function () {
  22861. _super.prototype.dispose.call(this);
  22862. if (this.onLoadObservable) {
  22863. this.onLoadObservable.clear();
  22864. this._onLoadObservable = null;
  22865. }
  22866. this._delayedOnLoad = null;
  22867. this._delayedOnError = null;
  22868. };
  22869. // Statics
  22870. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22871. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22872. if (onLoad === void 0) { onLoad = null; }
  22873. if (onError === void 0) { onError = null; }
  22874. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22875. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22876. };
  22877. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22878. if (parsedTexture.customType) {
  22879. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22880. // Update Sampling Mode
  22881. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22882. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22883. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22884. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22885. }
  22886. }
  22887. return parsedCustomTexture;
  22888. }
  22889. if (parsedTexture.isCube) {
  22890. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22891. }
  22892. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22893. return null;
  22894. }
  22895. var texture = BABYLON.SerializationHelper.Parse(function () {
  22896. var generateMipMaps = true;
  22897. if (parsedTexture.noMipmap) {
  22898. generateMipMaps = false;
  22899. }
  22900. if (parsedTexture.mirrorPlane) {
  22901. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22902. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22903. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22904. return mirrorTexture;
  22905. }
  22906. else if (parsedTexture.isRenderTarget) {
  22907. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22908. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22909. return renderTargetTexture;
  22910. }
  22911. else {
  22912. var texture;
  22913. if (parsedTexture.base64String) {
  22914. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  22915. }
  22916. else {
  22917. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  22918. }
  22919. return texture;
  22920. }
  22921. }, parsedTexture, scene);
  22922. // Update Sampling Mode
  22923. if (parsedTexture.samplingMode) {
  22924. var sampling = parsedTexture.samplingMode;
  22925. if (texture._samplingMode !== sampling) {
  22926. texture.updateSamplingMode(sampling);
  22927. }
  22928. }
  22929. // Animations
  22930. if (parsedTexture.animations) {
  22931. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22932. var parsedAnimation = parsedTexture.animations[animationIndex];
  22933. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22934. }
  22935. }
  22936. return texture;
  22937. };
  22938. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22939. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22940. if (noMipmap === void 0) { noMipmap = false; }
  22941. if (invertY === void 0) { invertY = true; }
  22942. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22943. if (onLoad === void 0) { onLoad = null; }
  22944. if (onError === void 0) { onError = null; }
  22945. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22946. if (name.substr(0, 5) !== "data:") {
  22947. name = "data:" + name;
  22948. }
  22949. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22950. };
  22951. // Constants
  22952. Texture.NEAREST_SAMPLINGMODE = 1;
  22953. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22954. Texture.BILINEAR_SAMPLINGMODE = 2;
  22955. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22956. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22957. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22958. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22959. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22960. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22961. Texture.NEAREST_LINEAR = 7;
  22962. Texture.NEAREST_NEAREST = 8;
  22963. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22964. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22965. Texture.LINEAR_LINEAR = 11;
  22966. Texture.LINEAR_NEAREST = 12;
  22967. Texture.EXPLICIT_MODE = 0;
  22968. Texture.SPHERICAL_MODE = 1;
  22969. Texture.PLANAR_MODE = 2;
  22970. Texture.CUBIC_MODE = 3;
  22971. Texture.PROJECTION_MODE = 4;
  22972. Texture.SKYBOX_MODE = 5;
  22973. Texture.INVCUBIC_MODE = 6;
  22974. Texture.EQUIRECTANGULAR_MODE = 7;
  22975. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22976. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22977. Texture.CLAMP_ADDRESSMODE = 0;
  22978. Texture.WRAP_ADDRESSMODE = 1;
  22979. Texture.MIRROR_ADDRESSMODE = 2;
  22980. __decorate([
  22981. BABYLON.serialize()
  22982. ], Texture.prototype, "url", void 0);
  22983. __decorate([
  22984. BABYLON.serialize()
  22985. ], Texture.prototype, "uOffset", void 0);
  22986. __decorate([
  22987. BABYLON.serialize()
  22988. ], Texture.prototype, "vOffset", void 0);
  22989. __decorate([
  22990. BABYLON.serialize()
  22991. ], Texture.prototype, "uScale", void 0);
  22992. __decorate([
  22993. BABYLON.serialize()
  22994. ], Texture.prototype, "vScale", void 0);
  22995. __decorate([
  22996. BABYLON.serialize()
  22997. ], Texture.prototype, "uAng", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], Texture.prototype, "vAng", void 0);
  23001. __decorate([
  23002. BABYLON.serialize()
  23003. ], Texture.prototype, "wAng", void 0);
  23004. __decorate([
  23005. BABYLON.serialize()
  23006. ], Texture.prototype, "isBlocking", null);
  23007. return Texture;
  23008. }(BABYLON.BaseTexture));
  23009. BABYLON.Texture = Texture;
  23010. })(BABYLON || (BABYLON = {}));
  23011. //# sourceMappingURL=babylon.texture.js.map
  23012. var BABYLON;
  23013. (function (BABYLON) {
  23014. var _InstancesBatch = /** @class */ (function () {
  23015. function _InstancesBatch() {
  23016. this.mustReturn = false;
  23017. this.visibleInstances = new Array();
  23018. this.renderSelf = new Array();
  23019. }
  23020. return _InstancesBatch;
  23021. }());
  23022. BABYLON._InstancesBatch = _InstancesBatch;
  23023. var Mesh = /** @class */ (function (_super) {
  23024. __extends(Mesh, _super);
  23025. /**
  23026. * @constructor
  23027. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23028. * @param {Scene} scene The scene to add this mesh to.
  23029. * @param {Node} parent The parent of this mesh, if it has one
  23030. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23031. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23032. * When false, achieved by calling a clone(), also passing False.
  23033. * This will make creation of children, recursive.
  23034. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23035. */
  23036. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23037. if (scene === void 0) { scene = null; }
  23038. if (parent === void 0) { parent = null; }
  23039. if (source === void 0) { source = null; }
  23040. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23041. var _this = _super.call(this, name, scene) || this;
  23042. // Events
  23043. /**
  23044. * An event triggered before rendering the mesh
  23045. * @type {BABYLON.Observable}
  23046. */
  23047. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23048. /**
  23049. * An event triggered after rendering the mesh
  23050. * @type {BABYLON.Observable}
  23051. */
  23052. _this.onAfterRenderObservable = new BABYLON.Observable();
  23053. /**
  23054. * An event triggered before drawing the mesh
  23055. * @type {BABYLON.Observable}
  23056. */
  23057. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23058. // Members
  23059. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23060. _this.instances = new Array();
  23061. _this._LODLevels = new Array();
  23062. _this._visibleInstances = {};
  23063. _this._renderIdForInstances = new Array();
  23064. _this._batchCache = new _InstancesBatch();
  23065. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23066. // Use by builder only to know what orientation were the mesh build in.
  23067. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23068. _this.overrideMaterialSideOrientation = null;
  23069. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23070. // Will be used to save a source mesh reference, If any
  23071. _this._source = null;
  23072. scene = _this.getScene();
  23073. if (source) {
  23074. // Source mesh
  23075. _this._source = source;
  23076. // Geometry
  23077. if (source._geometry) {
  23078. source._geometry.applyToMesh(_this);
  23079. }
  23080. // Deep copy
  23081. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23082. // Tags
  23083. if (BABYLON.Tags.HasTags(source)) {
  23084. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23085. }
  23086. _this.metadata = source.metadata;
  23087. // Parent
  23088. _this.parent = source.parent;
  23089. // Pivot
  23090. _this.setPivotMatrix(source.getPivotMatrix());
  23091. _this.id = name + "." + source.id;
  23092. // Material
  23093. _this.material = source.material;
  23094. var index;
  23095. if (!doNotCloneChildren) {
  23096. // Children
  23097. var directDescendants = source.getDescendants(true);
  23098. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23099. var child = directDescendants[index_1];
  23100. if (child.clone) {
  23101. child.clone(name + "." + child.name, _this);
  23102. }
  23103. }
  23104. }
  23105. // Physics clone
  23106. var physicsEngine = _this.getScene().getPhysicsEngine();
  23107. if (clonePhysicsImpostor && physicsEngine) {
  23108. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23109. if (impostor) {
  23110. _this.physicsImpostor = impostor.clone(_this);
  23111. }
  23112. }
  23113. // Particles
  23114. for (index = 0; index < scene.particleSystems.length; index++) {
  23115. var system = scene.particleSystems[index];
  23116. if (system.emitter === source) {
  23117. system.clone(system.name, _this);
  23118. }
  23119. }
  23120. _this.computeWorldMatrix(true);
  23121. }
  23122. // Parent
  23123. if (parent !== null) {
  23124. _this.parent = parent;
  23125. }
  23126. return _this;
  23127. }
  23128. Object.defineProperty(Mesh, "FRONTSIDE", {
  23129. /**
  23130. * Mesh side orientation : usually the external or front surface
  23131. */
  23132. get: function () {
  23133. return Mesh._FRONTSIDE;
  23134. },
  23135. enumerable: true,
  23136. configurable: true
  23137. });
  23138. Object.defineProperty(Mesh, "BACKSIDE", {
  23139. /**
  23140. * Mesh side orientation : usually the internal or back surface
  23141. */
  23142. get: function () {
  23143. return Mesh._BACKSIDE;
  23144. },
  23145. enumerable: true,
  23146. configurable: true
  23147. });
  23148. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23149. /**
  23150. * Mesh side orientation : both internal and external or front and back surfaces
  23151. */
  23152. get: function () {
  23153. return Mesh._DOUBLESIDE;
  23154. },
  23155. enumerable: true,
  23156. configurable: true
  23157. });
  23158. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23159. /**
  23160. * Mesh side orientation : by default, `FRONTSIDE`
  23161. */
  23162. get: function () {
  23163. return Mesh._DEFAULTSIDE;
  23164. },
  23165. enumerable: true,
  23166. configurable: true
  23167. });
  23168. Object.defineProperty(Mesh, "NO_CAP", {
  23169. /**
  23170. * Mesh cap setting : no cap
  23171. */
  23172. get: function () {
  23173. return Mesh._NO_CAP;
  23174. },
  23175. enumerable: true,
  23176. configurable: true
  23177. });
  23178. Object.defineProperty(Mesh, "CAP_START", {
  23179. /**
  23180. * Mesh cap setting : one cap at the beginning of the mesh
  23181. */
  23182. get: function () {
  23183. return Mesh._CAP_START;
  23184. },
  23185. enumerable: true,
  23186. configurable: true
  23187. });
  23188. Object.defineProperty(Mesh, "CAP_END", {
  23189. /**
  23190. * Mesh cap setting : one cap at the end of the mesh
  23191. */
  23192. get: function () {
  23193. return Mesh._CAP_END;
  23194. },
  23195. enumerable: true,
  23196. configurable: true
  23197. });
  23198. Object.defineProperty(Mesh, "CAP_ALL", {
  23199. /**
  23200. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23201. */
  23202. get: function () {
  23203. return Mesh._CAP_ALL;
  23204. },
  23205. enumerable: true,
  23206. configurable: true
  23207. });
  23208. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23209. set: function (callback) {
  23210. if (this._onBeforeDrawObserver) {
  23211. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23212. }
  23213. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23214. },
  23215. enumerable: true,
  23216. configurable: true
  23217. });
  23218. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23219. get: function () {
  23220. return this._morphTargetManager;
  23221. },
  23222. set: function (value) {
  23223. if (this._morphTargetManager === value) {
  23224. return;
  23225. }
  23226. this._morphTargetManager = value;
  23227. this._syncGeometryWithMorphTargetManager();
  23228. },
  23229. enumerable: true,
  23230. configurable: true
  23231. });
  23232. Object.defineProperty(Mesh.prototype, "source", {
  23233. get: function () {
  23234. return this._source;
  23235. },
  23236. enumerable: true,
  23237. configurable: true
  23238. });
  23239. // Methods
  23240. /**
  23241. * Returns the string "Mesh".
  23242. */
  23243. Mesh.prototype.getClassName = function () {
  23244. return "Mesh";
  23245. };
  23246. /**
  23247. * Returns a string.
  23248. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23249. */
  23250. Mesh.prototype.toString = function (fullDetails) {
  23251. var ret = _super.prototype.toString.call(this, fullDetails);
  23252. ret += ", n vertices: " + this.getTotalVertices();
  23253. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23254. if (this.animations) {
  23255. for (var i = 0; i < this.animations.length; i++) {
  23256. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23257. }
  23258. }
  23259. if (fullDetails) {
  23260. if (this._geometry) {
  23261. var ib = this.getIndices();
  23262. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23263. if (vb && ib) {
  23264. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23265. }
  23266. }
  23267. else {
  23268. ret += ", flat shading: UNKNOWN";
  23269. }
  23270. }
  23271. return ret;
  23272. };
  23273. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23274. /**
  23275. * True if the mesh has some Levels Of Details (LOD).
  23276. * Returns a boolean.
  23277. */
  23278. get: function () {
  23279. return this._LODLevels.length > 0;
  23280. },
  23281. enumerable: true,
  23282. configurable: true
  23283. });
  23284. Mesh.prototype._sortLODLevels = function () {
  23285. this._LODLevels.sort(function (a, b) {
  23286. if (a.distance < b.distance) {
  23287. return 1;
  23288. }
  23289. if (a.distance > b.distance) {
  23290. return -1;
  23291. }
  23292. return 0;
  23293. });
  23294. };
  23295. /**
  23296. * Add a mesh as LOD level triggered at the given distance.
  23297. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23298. * @param {number} distance The distance from the center of the object to show this level
  23299. * @param {Mesh} mesh The mesh to be added as LOD level
  23300. * @return {Mesh} This mesh (for chaining)
  23301. */
  23302. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23303. if (mesh && mesh._masterMesh) {
  23304. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23305. return this;
  23306. }
  23307. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23308. this._LODLevels.push(level);
  23309. if (mesh) {
  23310. mesh._masterMesh = this;
  23311. }
  23312. this._sortLODLevels();
  23313. return this;
  23314. };
  23315. /**
  23316. * Returns the LOD level mesh at the passed distance or null if not found.
  23317. * It is related to the method `addLODLevel(distance, mesh)`.
  23318. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23319. * Returns an object Mesh or `null`.
  23320. */
  23321. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23322. for (var index = 0; index < this._LODLevels.length; index++) {
  23323. var level = this._LODLevels[index];
  23324. if (level.distance === distance) {
  23325. return level.mesh;
  23326. }
  23327. }
  23328. return null;
  23329. };
  23330. /**
  23331. * Remove a mesh from the LOD array
  23332. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23333. * @param {Mesh} mesh The mesh to be removed.
  23334. * @return {Mesh} This mesh (for chaining)
  23335. */
  23336. Mesh.prototype.removeLODLevel = function (mesh) {
  23337. for (var index = 0; index < this._LODLevels.length; index++) {
  23338. if (this._LODLevels[index].mesh === mesh) {
  23339. this._LODLevels.splice(index, 1);
  23340. if (mesh) {
  23341. mesh._masterMesh = null;
  23342. }
  23343. }
  23344. }
  23345. this._sortLODLevels();
  23346. return this;
  23347. };
  23348. /**
  23349. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23350. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23351. */
  23352. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23353. if (!this._LODLevels || this._LODLevels.length === 0) {
  23354. return this;
  23355. }
  23356. var bSphere;
  23357. if (boundingSphere) {
  23358. bSphere = boundingSphere;
  23359. }
  23360. else {
  23361. var boundingInfo = this.getBoundingInfo();
  23362. bSphere = boundingInfo.boundingSphere;
  23363. }
  23364. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23365. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23366. if (this.onLODLevelSelection) {
  23367. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23368. }
  23369. return this;
  23370. }
  23371. for (var index = 0; index < this._LODLevels.length; index++) {
  23372. var level = this._LODLevels[index];
  23373. if (level.distance < distanceToCamera) {
  23374. if (level.mesh) {
  23375. level.mesh._preActivate();
  23376. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23377. }
  23378. if (this.onLODLevelSelection) {
  23379. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23380. }
  23381. return level.mesh;
  23382. }
  23383. }
  23384. if (this.onLODLevelSelection) {
  23385. this.onLODLevelSelection(distanceToCamera, this, this);
  23386. }
  23387. return this;
  23388. };
  23389. Object.defineProperty(Mesh.prototype, "geometry", {
  23390. /**
  23391. * Returns the mesh internal Geometry object.
  23392. */
  23393. get: function () {
  23394. return this._geometry;
  23395. },
  23396. enumerable: true,
  23397. configurable: true
  23398. });
  23399. /**
  23400. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23401. */
  23402. Mesh.prototype.getTotalVertices = function () {
  23403. if (!this._geometry) {
  23404. return 0;
  23405. }
  23406. return this._geometry.getTotalVertices();
  23407. };
  23408. /**
  23409. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23410. * 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.
  23411. * You can force the copy with forceCopy === true
  23412. * Returns null if the mesh has no geometry or no vertex buffer.
  23413. * Possible `kind` values :
  23414. * - BABYLON.VertexBuffer.PositionKind
  23415. * - BABYLON.VertexBuffer.UVKind
  23416. * - BABYLON.VertexBuffer.UV2Kind
  23417. * - BABYLON.VertexBuffer.UV3Kind
  23418. * - BABYLON.VertexBuffer.UV4Kind
  23419. * - BABYLON.VertexBuffer.UV5Kind
  23420. * - BABYLON.VertexBuffer.UV6Kind
  23421. * - BABYLON.VertexBuffer.ColorKind
  23422. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23423. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23424. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23425. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23426. */
  23427. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23428. if (!this._geometry) {
  23429. return null;
  23430. }
  23431. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23432. };
  23433. /**
  23434. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23435. * Returns `null` if the mesh has no geometry.
  23436. * Possible `kind` values :
  23437. * - BABYLON.VertexBuffer.PositionKind
  23438. * - BABYLON.VertexBuffer.UVKind
  23439. * - BABYLON.VertexBuffer.UV2Kind
  23440. * - BABYLON.VertexBuffer.UV3Kind
  23441. * - BABYLON.VertexBuffer.UV4Kind
  23442. * - BABYLON.VertexBuffer.UV5Kind
  23443. * - BABYLON.VertexBuffer.UV6Kind
  23444. * - BABYLON.VertexBuffer.ColorKind
  23445. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23446. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23447. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23448. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23449. */
  23450. Mesh.prototype.getVertexBuffer = function (kind) {
  23451. if (!this._geometry) {
  23452. return null;
  23453. }
  23454. return this._geometry.getVertexBuffer(kind);
  23455. };
  23456. /**
  23457. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23458. * Possible `kind` values :
  23459. * - BABYLON.VertexBuffer.PositionKind
  23460. * - BABYLON.VertexBuffer.UVKind
  23461. * - BABYLON.VertexBuffer.UV2Kind
  23462. * - BABYLON.VertexBuffer.UV3Kind
  23463. * - BABYLON.VertexBuffer.UV4Kind
  23464. * - BABYLON.VertexBuffer.UV5Kind
  23465. * - BABYLON.VertexBuffer.UV6Kind
  23466. * - BABYLON.VertexBuffer.ColorKind
  23467. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23468. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23469. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23470. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23471. */
  23472. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23473. if (!this._geometry) {
  23474. if (this._delayInfo) {
  23475. return this._delayInfo.indexOf(kind) !== -1;
  23476. }
  23477. return false;
  23478. }
  23479. return this._geometry.isVerticesDataPresent(kind);
  23480. };
  23481. /**
  23482. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23483. * Possible `kind` values :
  23484. * - BABYLON.VertexBuffer.PositionKind
  23485. * - BABYLON.VertexBuffer.UVKind
  23486. * - BABYLON.VertexBuffer.UV2Kind
  23487. * - BABYLON.VertexBuffer.UV3Kind
  23488. * - BABYLON.VertexBuffer.UV4Kind
  23489. * - BABYLON.VertexBuffer.UV5Kind
  23490. * - BABYLON.VertexBuffer.UV6Kind
  23491. * - BABYLON.VertexBuffer.ColorKind
  23492. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23493. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23494. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23495. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23496. */
  23497. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23498. if (!this._geometry) {
  23499. if (this._delayInfo) {
  23500. return this._delayInfo.indexOf(kind) !== -1;
  23501. }
  23502. return false;
  23503. }
  23504. return this._geometry.isVertexBufferUpdatable(kind);
  23505. };
  23506. /**
  23507. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23508. * Possible `kind` values :
  23509. * - BABYLON.VertexBuffer.PositionKind
  23510. * - BABYLON.VertexBuffer.UVKind
  23511. * - BABYLON.VertexBuffer.UV2Kind
  23512. * - BABYLON.VertexBuffer.UV3Kind
  23513. * - BABYLON.VertexBuffer.UV4Kind
  23514. * - BABYLON.VertexBuffer.UV5Kind
  23515. * - BABYLON.VertexBuffer.UV6Kind
  23516. * - BABYLON.VertexBuffer.ColorKind
  23517. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23518. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23519. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23520. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23521. */
  23522. Mesh.prototype.getVerticesDataKinds = function () {
  23523. if (!this._geometry) {
  23524. var result = new Array();
  23525. if (this._delayInfo) {
  23526. this._delayInfo.forEach(function (kind, index, array) {
  23527. result.push(kind);
  23528. });
  23529. }
  23530. return result;
  23531. }
  23532. return this._geometry.getVerticesDataKinds();
  23533. };
  23534. /**
  23535. * Returns a positive integer : the total number of indices in this mesh geometry.
  23536. * Returns zero if the mesh has no geometry.
  23537. */
  23538. Mesh.prototype.getTotalIndices = function () {
  23539. if (!this._geometry) {
  23540. return 0;
  23541. }
  23542. return this._geometry.getTotalIndices();
  23543. };
  23544. /**
  23545. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23546. * 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.
  23547. * Returns an empty array if the mesh has no geometry.
  23548. */
  23549. Mesh.prototype.getIndices = function (copyWhenShared) {
  23550. if (!this._geometry) {
  23551. return [];
  23552. }
  23553. return this._geometry.getIndices(copyWhenShared);
  23554. };
  23555. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23556. get: function () {
  23557. return this._masterMesh !== null && this._masterMesh !== undefined;
  23558. },
  23559. enumerable: true,
  23560. configurable: true
  23561. });
  23562. /**
  23563. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23564. */
  23565. Mesh.prototype.isReady = function () {
  23566. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23567. return false;
  23568. }
  23569. return _super.prototype.isReady.call(this);
  23570. };
  23571. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23572. /**
  23573. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23574. * This property is pertinent only for updatable parametric shapes.
  23575. */
  23576. get: function () {
  23577. return this._areNormalsFrozen;
  23578. },
  23579. enumerable: true,
  23580. configurable: true
  23581. });
  23582. /**
  23583. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23584. * It has no effect at all on other shapes.
  23585. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23586. * Returns the Mesh.
  23587. */
  23588. Mesh.prototype.freezeNormals = function () {
  23589. this._areNormalsFrozen = true;
  23590. return this;
  23591. };
  23592. /**
  23593. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23594. * It has no effect at all on other shapes.
  23595. * It reactivates the mesh normals computation if it was previously frozen.
  23596. * Returns the Mesh.
  23597. */
  23598. Mesh.prototype.unfreezeNormals = function () {
  23599. this._areNormalsFrozen = false;
  23600. return this;
  23601. };
  23602. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23603. /**
  23604. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23605. */
  23606. set: function (count) {
  23607. this._overridenInstanceCount = count;
  23608. },
  23609. enumerable: true,
  23610. configurable: true
  23611. });
  23612. // Methods
  23613. Mesh.prototype._preActivate = function () {
  23614. var sceneRenderId = this.getScene().getRenderId();
  23615. if (this._preActivateId === sceneRenderId) {
  23616. return this;
  23617. }
  23618. this._preActivateId = sceneRenderId;
  23619. this._visibleInstances = null;
  23620. return this;
  23621. };
  23622. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23623. if (this._visibleInstances) {
  23624. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23625. }
  23626. return this;
  23627. };
  23628. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23629. if (!this._visibleInstances) {
  23630. this._visibleInstances = {};
  23631. this._visibleInstances.defaultRenderId = renderId;
  23632. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23633. }
  23634. if (!this._visibleInstances[renderId]) {
  23635. this._visibleInstances[renderId] = new Array();
  23636. }
  23637. this._visibleInstances[renderId].push(instance);
  23638. return this;
  23639. };
  23640. /**
  23641. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23642. * This means the mesh underlying bounding box and sphere are recomputed.
  23643. * Returns the Mesh.
  23644. */
  23645. Mesh.prototype.refreshBoundingInfo = function () {
  23646. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23647. return this;
  23648. }
  23649. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23650. if (data) {
  23651. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23652. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23653. }
  23654. if (this.subMeshes) {
  23655. for (var index = 0; index < this.subMeshes.length; index++) {
  23656. this.subMeshes[index].refreshBoundingInfo();
  23657. }
  23658. }
  23659. this._updateBoundingInfo();
  23660. return this;
  23661. };
  23662. Mesh.prototype._createGlobalSubMesh = function (force) {
  23663. var totalVertices = this.getTotalVertices();
  23664. if (!totalVertices || !this.getIndices()) {
  23665. return null;
  23666. }
  23667. // Check if we need to recreate the submeshes
  23668. if (this.subMeshes && this.subMeshes.length > 0) {
  23669. var ib = this.getIndices();
  23670. if (!ib) {
  23671. return null;
  23672. }
  23673. var totalIndices = ib.length;
  23674. var needToRecreate = false;
  23675. if (force) {
  23676. needToRecreate = true;
  23677. }
  23678. else {
  23679. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23680. var submesh = _a[_i];
  23681. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23682. needToRecreate = true;
  23683. break;
  23684. }
  23685. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23686. needToRecreate = true;
  23687. break;
  23688. }
  23689. }
  23690. }
  23691. if (!needToRecreate) {
  23692. return this.subMeshes[0];
  23693. }
  23694. }
  23695. this.releaseSubMeshes();
  23696. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23697. };
  23698. Mesh.prototype.subdivide = function (count) {
  23699. if (count < 1) {
  23700. return;
  23701. }
  23702. var totalIndices = this.getTotalIndices();
  23703. var subdivisionSize = (totalIndices / count) | 0;
  23704. var offset = 0;
  23705. // Ensure that subdivisionSize is a multiple of 3
  23706. while (subdivisionSize % 3 !== 0) {
  23707. subdivisionSize++;
  23708. }
  23709. this.releaseSubMeshes();
  23710. for (var index = 0; index < count; index++) {
  23711. if (offset >= totalIndices) {
  23712. break;
  23713. }
  23714. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23715. offset += subdivisionSize;
  23716. }
  23717. this.synchronizeInstances();
  23718. };
  23719. /**
  23720. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23721. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23722. * The `data` are either a numeric array either a Float32Array.
  23723. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23724. * 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).
  23725. * Note that a new underlying VertexBuffer object is created each call.
  23726. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23727. *
  23728. * Possible `kind` values :
  23729. * - BABYLON.VertexBuffer.PositionKind
  23730. * - BABYLON.VertexBuffer.UVKind
  23731. * - BABYLON.VertexBuffer.UV2Kind
  23732. * - BABYLON.VertexBuffer.UV3Kind
  23733. * - BABYLON.VertexBuffer.UV4Kind
  23734. * - BABYLON.VertexBuffer.UV5Kind
  23735. * - BABYLON.VertexBuffer.UV6Kind
  23736. * - BABYLON.VertexBuffer.ColorKind
  23737. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23738. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23739. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23740. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23741. *
  23742. * Returns the Mesh.
  23743. */
  23744. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23745. if (updatable === void 0) { updatable = false; }
  23746. if (!this._geometry) {
  23747. var vertexData = new BABYLON.VertexData();
  23748. vertexData.set(data, kind);
  23749. var scene = this.getScene();
  23750. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23751. }
  23752. else {
  23753. this._geometry.setVerticesData(kind, data, updatable, stride);
  23754. }
  23755. return this;
  23756. };
  23757. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23758. if (updatable === void 0) { updatable = true; }
  23759. var vb = this.getVertexBuffer(kind);
  23760. if (!vb || vb.isUpdatable() === updatable) {
  23761. return;
  23762. }
  23763. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23764. };
  23765. /**
  23766. * Sets the mesh VertexBuffer.
  23767. * Returns the Mesh.
  23768. */
  23769. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23770. if (!this._geometry) {
  23771. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23772. }
  23773. this._geometry.setVerticesBuffer(buffer);
  23774. return this;
  23775. };
  23776. /**
  23777. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23778. * If the mesh has no geometry, it is simply returned as it is.
  23779. * The `data` are either a numeric array either a Float32Array.
  23780. * No new underlying VertexBuffer object is created.
  23781. * 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.
  23782. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23783. *
  23784. * Possible `kind` values :
  23785. * - BABYLON.VertexBuffer.PositionKind
  23786. * - BABYLON.VertexBuffer.UVKind
  23787. * - BABYLON.VertexBuffer.UV2Kind
  23788. * - BABYLON.VertexBuffer.UV3Kind
  23789. * - BABYLON.VertexBuffer.UV4Kind
  23790. * - BABYLON.VertexBuffer.UV5Kind
  23791. * - BABYLON.VertexBuffer.UV6Kind
  23792. * - BABYLON.VertexBuffer.ColorKind
  23793. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23794. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23795. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23796. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23797. *
  23798. * Returns the Mesh.
  23799. */
  23800. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23801. if (!this._geometry) {
  23802. return this;
  23803. }
  23804. if (!makeItUnique) {
  23805. this._geometry.updateVerticesData(kind, data, updateExtends);
  23806. }
  23807. else {
  23808. this.makeGeometryUnique();
  23809. this.updateVerticesData(kind, data, updateExtends, false);
  23810. }
  23811. return this;
  23812. };
  23813. /**
  23814. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23815. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23816. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23817. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23818. * Returns the Mesh.
  23819. */
  23820. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23821. if (computeNormals === void 0) { computeNormals = true; }
  23822. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23823. if (!positions) {
  23824. return this;
  23825. }
  23826. positionFunction(positions);
  23827. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23828. if (computeNormals) {
  23829. var indices = this.getIndices();
  23830. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23831. if (!normals) {
  23832. return this;
  23833. }
  23834. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23835. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23836. }
  23837. return this;
  23838. };
  23839. /**
  23840. * Creates a un-shared specific occurence of the geometry for the mesh.
  23841. * Returns the Mesh.
  23842. */
  23843. Mesh.prototype.makeGeometryUnique = function () {
  23844. if (!this._geometry) {
  23845. return this;
  23846. }
  23847. var oldGeometry = this._geometry;
  23848. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23849. oldGeometry.releaseForMesh(this, true);
  23850. geometry.applyToMesh(this);
  23851. return this;
  23852. };
  23853. /**
  23854. * Sets the mesh indices.
  23855. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23856. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  23857. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23858. * This method creates a new index buffer each call.
  23859. * Returns the Mesh.
  23860. */
  23861. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23862. if (totalVertices === void 0) { totalVertices = null; }
  23863. if (updatable === void 0) { updatable = false; }
  23864. if (!this._geometry) {
  23865. var vertexData = new BABYLON.VertexData();
  23866. vertexData.indices = indices;
  23867. var scene = this.getScene();
  23868. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23869. }
  23870. else {
  23871. this._geometry.setIndices(indices, totalVertices, updatable);
  23872. }
  23873. return this;
  23874. };
  23875. /**
  23876. * Update the current index buffer
  23877. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23878. * Returns the Mesh.
  23879. */
  23880. Mesh.prototype.updateIndices = function (indices, offset) {
  23881. if (!this._geometry) {
  23882. return this;
  23883. }
  23884. this._geometry.updateIndices(indices, offset);
  23885. return this;
  23886. };
  23887. /**
  23888. * Invert the geometry to move from a right handed system to a left handed one.
  23889. * Returns the Mesh.
  23890. */
  23891. Mesh.prototype.toLeftHanded = function () {
  23892. if (!this._geometry) {
  23893. return this;
  23894. }
  23895. this._geometry.toLeftHanded();
  23896. return this;
  23897. };
  23898. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23899. if (!this._geometry) {
  23900. return this;
  23901. }
  23902. var engine = this.getScene().getEngine();
  23903. // Wireframe
  23904. var indexToBind;
  23905. if (this._unIndexed) {
  23906. indexToBind = null;
  23907. }
  23908. else {
  23909. switch (fillMode) {
  23910. case BABYLON.Material.PointFillMode:
  23911. indexToBind = null;
  23912. break;
  23913. case BABYLON.Material.WireFrameFillMode:
  23914. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23915. break;
  23916. default:
  23917. case BABYLON.Material.TriangleFillMode:
  23918. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23919. break;
  23920. }
  23921. }
  23922. // VBOs
  23923. this._geometry._bind(effect, indexToBind);
  23924. return this;
  23925. };
  23926. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23927. if (alternate === void 0) { alternate = false; }
  23928. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23929. return this;
  23930. }
  23931. this.onBeforeDrawObservable.notifyObservers(this);
  23932. var scene = this.getScene();
  23933. var engine = scene.getEngine();
  23934. // Draw order
  23935. switch (fillMode) {
  23936. case BABYLON.Material.PointFillMode:
  23937. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23938. break;
  23939. case BABYLON.Material.WireFrameFillMode:
  23940. if (this._unIndexed) {
  23941. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23942. }
  23943. else {
  23944. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23945. }
  23946. break;
  23947. default:
  23948. if (this._unIndexed) {
  23949. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23950. }
  23951. else {
  23952. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23953. }
  23954. }
  23955. if (scene._isAlternateRenderingEnabled && !alternate) {
  23956. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23957. if (!effect || !scene.activeCamera) {
  23958. return this;
  23959. }
  23960. scene._switchToAlternateCameraConfiguration(true);
  23961. this._effectiveMaterial.bindView(effect);
  23962. this._effectiveMaterial.bindViewProjection(effect);
  23963. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23964. this._draw(subMesh, fillMode, instancesCount, true);
  23965. engine.setViewport(scene.activeCamera.viewport);
  23966. scene._switchToAlternateCameraConfiguration(false);
  23967. this._effectiveMaterial.bindView(effect);
  23968. this._effectiveMaterial.bindViewProjection(effect);
  23969. }
  23970. return this;
  23971. };
  23972. /**
  23973. * Registers for this mesh a javascript function called just before the rendering process.
  23974. * This function is passed the current mesh.
  23975. * Return the Mesh.
  23976. */
  23977. Mesh.prototype.registerBeforeRender = function (func) {
  23978. this.onBeforeRenderObservable.add(func);
  23979. return this;
  23980. };
  23981. /**
  23982. * Disposes a previously registered javascript function called before the rendering.
  23983. * This function is passed the current mesh.
  23984. * Returns the Mesh.
  23985. */
  23986. Mesh.prototype.unregisterBeforeRender = function (func) {
  23987. this.onBeforeRenderObservable.removeCallback(func);
  23988. return this;
  23989. };
  23990. /**
  23991. * Registers for this mesh a javascript function called just after the rendering is complete.
  23992. * This function is passed the current mesh.
  23993. * Returns the Mesh.
  23994. */
  23995. Mesh.prototype.registerAfterRender = function (func) {
  23996. this.onAfterRenderObservable.add(func);
  23997. return this;
  23998. };
  23999. /**
  24000. * Disposes a previously registered javascript function called after the rendering.
  24001. * This function is passed the current mesh.
  24002. * Return the Mesh.
  24003. */
  24004. Mesh.prototype.unregisterAfterRender = function (func) {
  24005. this.onAfterRenderObservable.removeCallback(func);
  24006. return this;
  24007. };
  24008. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24009. var scene = this.getScene();
  24010. this._batchCache.mustReturn = false;
  24011. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24012. this._batchCache.visibleInstances[subMeshId] = null;
  24013. if (this._visibleInstances) {
  24014. var currentRenderId = scene.getRenderId();
  24015. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24016. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24017. var selfRenderId = this._renderId;
  24018. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24019. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24020. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24021. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24022. }
  24023. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24024. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24025. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24026. this._batchCache.mustReturn = true;
  24027. return this._batchCache;
  24028. }
  24029. if (currentRenderId !== selfRenderId) {
  24030. this._batchCache.renderSelf[subMeshId] = false;
  24031. }
  24032. }
  24033. this._renderIdForInstances[subMeshId] = currentRenderId;
  24034. }
  24035. return this._batchCache;
  24036. };
  24037. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24038. var visibleInstances = batch.visibleInstances[subMesh._id];
  24039. if (!visibleInstances) {
  24040. return this;
  24041. }
  24042. var matricesCount = visibleInstances.length + 1;
  24043. var bufferSize = matricesCount * 16 * 4;
  24044. var currentInstancesBufferSize = this._instancesBufferSize;
  24045. var instancesBuffer = this._instancesBuffer;
  24046. while (this._instancesBufferSize < bufferSize) {
  24047. this._instancesBufferSize *= 2;
  24048. }
  24049. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24050. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24051. }
  24052. var offset = 0;
  24053. var instancesCount = 0;
  24054. var world = this.getWorldMatrix();
  24055. if (batch.renderSelf[subMesh._id]) {
  24056. world.copyToArray(this._instancesData, offset);
  24057. offset += 16;
  24058. instancesCount++;
  24059. }
  24060. if (visibleInstances) {
  24061. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24062. var instance = visibleInstances[instanceIndex];
  24063. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24064. offset += 16;
  24065. instancesCount++;
  24066. }
  24067. }
  24068. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24069. if (instancesBuffer) {
  24070. instancesBuffer.dispose();
  24071. }
  24072. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24073. this._instancesBuffer = instancesBuffer;
  24074. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24075. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24076. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24077. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24078. }
  24079. else {
  24080. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24081. }
  24082. this._bind(subMesh, effect, fillMode);
  24083. this._draw(subMesh, fillMode, instancesCount);
  24084. engine.unbindInstanceAttributes();
  24085. return this;
  24086. };
  24087. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24088. var scene = this.getScene();
  24089. var engine = scene.getEngine();
  24090. if (hardwareInstancedRendering) {
  24091. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24092. }
  24093. else {
  24094. if (batch.renderSelf[subMesh._id]) {
  24095. // Draw
  24096. if (onBeforeDraw) {
  24097. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24098. }
  24099. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24100. }
  24101. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24102. if (visibleInstancesForSubMesh) {
  24103. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24104. var instance = visibleInstancesForSubMesh[instanceIndex];
  24105. // World
  24106. var world = instance.getWorldMatrix();
  24107. if (onBeforeDraw) {
  24108. onBeforeDraw(true, world, effectiveMaterial);
  24109. }
  24110. // Draw
  24111. this._draw(subMesh, fillMode);
  24112. }
  24113. }
  24114. }
  24115. return this;
  24116. };
  24117. /**
  24118. * Triggers the draw call for the mesh.
  24119. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24120. * Returns the Mesh.
  24121. */
  24122. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24123. this.checkOcclusionQuery();
  24124. if (this._isOccluded) {
  24125. return this;
  24126. }
  24127. var scene = this.getScene();
  24128. // Managing instances
  24129. var batch = this._getInstancesRenderList(subMesh._id);
  24130. if (batch.mustReturn) {
  24131. return this;
  24132. }
  24133. // Checking geometry state
  24134. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24135. return this;
  24136. }
  24137. this.onBeforeRenderObservable.notifyObservers(this);
  24138. var engine = scene.getEngine();
  24139. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24140. // Material
  24141. var material = subMesh.getMaterial();
  24142. if (!material) {
  24143. return this;
  24144. }
  24145. this._effectiveMaterial = material;
  24146. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24147. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24148. return this;
  24149. }
  24150. }
  24151. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24152. return this;
  24153. }
  24154. // Alpha mode
  24155. if (enableAlphaMode) {
  24156. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24157. }
  24158. // Outline - step 1
  24159. var savedDepthWrite = engine.getDepthWrite();
  24160. if (this.renderOutline) {
  24161. engine.setDepthWrite(false);
  24162. scene.getOutlineRenderer().render(subMesh, batch);
  24163. engine.setDepthWrite(savedDepthWrite);
  24164. }
  24165. var effect;
  24166. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24167. effect = subMesh.effect;
  24168. }
  24169. else {
  24170. effect = this._effectiveMaterial.getEffect();
  24171. }
  24172. if (!effect) {
  24173. return this;
  24174. }
  24175. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24176. if (this._effectiveMaterial.forceDepthWrite) {
  24177. engine.setDepthWrite(true);
  24178. }
  24179. // Bind
  24180. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24181. if (!hardwareInstancedRendering) {
  24182. this._bind(subMesh, effect, fillMode);
  24183. }
  24184. var world = this.getWorldMatrix();
  24185. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24186. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24187. }
  24188. else {
  24189. this._effectiveMaterial.bind(world, this);
  24190. }
  24191. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24192. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24193. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24194. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24195. }
  24196. // Draw
  24197. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24198. // Unbind
  24199. this._effectiveMaterial.unbind();
  24200. // Outline - step 2
  24201. if (this.renderOutline && savedDepthWrite) {
  24202. engine.setDepthWrite(true);
  24203. engine.setColorWrite(false);
  24204. scene.getOutlineRenderer().render(subMesh, batch);
  24205. engine.setColorWrite(true);
  24206. }
  24207. // Overlay
  24208. if (this.renderOverlay) {
  24209. var currentMode = engine.getAlphaMode();
  24210. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24211. scene.getOutlineRenderer().render(subMesh, batch, true);
  24212. engine.setAlphaMode(currentMode);
  24213. }
  24214. this.onAfterRenderObservable.notifyObservers(this);
  24215. return this;
  24216. };
  24217. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24218. if (isInstance && effectiveMaterial) {
  24219. effectiveMaterial.bindOnlyWorldMatrix(world);
  24220. }
  24221. };
  24222. /**
  24223. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24224. */
  24225. Mesh.prototype.getEmittedParticleSystems = function () {
  24226. var results = new Array();
  24227. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24228. var particleSystem = this.getScene().particleSystems[index];
  24229. if (particleSystem.emitter === this) {
  24230. results.push(particleSystem);
  24231. }
  24232. }
  24233. return results;
  24234. };
  24235. /**
  24236. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24237. */
  24238. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24239. var results = new Array();
  24240. var descendants = this.getDescendants();
  24241. descendants.push(this);
  24242. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24243. var particleSystem = this.getScene().particleSystems[index];
  24244. var emitter = particleSystem.emitter;
  24245. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24246. results.push(particleSystem);
  24247. }
  24248. }
  24249. return results;
  24250. };
  24251. Mesh.prototype._checkDelayState = function () {
  24252. var scene = this.getScene();
  24253. if (this._geometry) {
  24254. this._geometry.load(scene);
  24255. }
  24256. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24258. this._queueLoad(this, scene);
  24259. }
  24260. return this;
  24261. };
  24262. Mesh.prototype._queueLoad = function (mesh, scene) {
  24263. var _this = this;
  24264. scene._addPendingData(mesh);
  24265. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24266. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24267. if (data instanceof ArrayBuffer) {
  24268. _this._delayLoadingFunction(data, _this);
  24269. }
  24270. else {
  24271. _this._delayLoadingFunction(JSON.parse(data), _this);
  24272. }
  24273. _this.instances.forEach(function (instance) {
  24274. instance._syncSubMeshes();
  24275. });
  24276. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24277. scene._removePendingData(_this);
  24278. }, function () { }, scene.database, getBinaryData);
  24279. return this;
  24280. };
  24281. /**
  24282. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24283. */
  24284. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24285. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24286. return false;
  24287. }
  24288. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24289. return false;
  24290. }
  24291. this._checkDelayState();
  24292. return true;
  24293. };
  24294. /**
  24295. * Sets the mesh material by the material or multiMaterial `id` property.
  24296. * The material `id` is a string identifying the material or the multiMaterial.
  24297. * This method returns the Mesh.
  24298. */
  24299. Mesh.prototype.setMaterialByID = function (id) {
  24300. var materials = this.getScene().materials;
  24301. var index;
  24302. for (index = materials.length - 1; index > -1; index--) {
  24303. if (materials[index].id === id) {
  24304. this.material = materials[index];
  24305. return this;
  24306. }
  24307. }
  24308. // Multi
  24309. var multiMaterials = this.getScene().multiMaterials;
  24310. for (index = multiMaterials.length - 1; index > -1; index--) {
  24311. if (multiMaterials[index].id === id) {
  24312. this.material = multiMaterials[index];
  24313. return this;
  24314. }
  24315. }
  24316. return this;
  24317. };
  24318. /**
  24319. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24320. */
  24321. Mesh.prototype.getAnimatables = function () {
  24322. var results = new Array();
  24323. if (this.material) {
  24324. results.push(this.material);
  24325. }
  24326. if (this.skeleton) {
  24327. results.push(this.skeleton);
  24328. }
  24329. return results;
  24330. };
  24331. /**
  24332. * Modifies the mesh geometry according to the passed transformation matrix.
  24333. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24334. * The mesh normals are modified accordingly the same transformation.
  24335. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24336. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24337. * Returns the Mesh.
  24338. */
  24339. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24340. // Position
  24341. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24342. return this;
  24343. }
  24344. var submeshes = this.subMeshes.splice(0);
  24345. this._resetPointsArrayCache();
  24346. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24347. var temp = new Array();
  24348. var index;
  24349. for (index = 0; index < data.length; index += 3) {
  24350. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24351. }
  24352. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24353. // Normals
  24354. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24355. return this;
  24356. }
  24357. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24358. temp = [];
  24359. for (index = 0; index < data.length; index += 3) {
  24360. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24361. }
  24362. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24363. // flip faces?
  24364. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24365. this.flipFaces();
  24366. }
  24367. // Restore submeshes
  24368. this.releaseSubMeshes();
  24369. this.subMeshes = submeshes;
  24370. return this;
  24371. };
  24372. /**
  24373. * Modifies the mesh geometry according to its own current World Matrix.
  24374. * The mesh World Matrix is then reset.
  24375. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24376. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24377. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24378. * Returns the Mesh.
  24379. */
  24380. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24381. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24382. this.scaling.copyFromFloats(1, 1, 1);
  24383. this.position.copyFromFloats(0, 0, 0);
  24384. this.rotation.copyFromFloats(0, 0, 0);
  24385. //only if quaternion is already set
  24386. if (this.rotationQuaternion) {
  24387. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24388. }
  24389. this._worldMatrix = BABYLON.Matrix.Identity();
  24390. return this;
  24391. };
  24392. Object.defineProperty(Mesh.prototype, "_positions", {
  24393. // Cache
  24394. get: function () {
  24395. if (this._geometry) {
  24396. return this._geometry._positions;
  24397. }
  24398. return null;
  24399. },
  24400. enumerable: true,
  24401. configurable: true
  24402. });
  24403. Mesh.prototype._resetPointsArrayCache = function () {
  24404. if (this._geometry) {
  24405. this._geometry._resetPointsArrayCache();
  24406. }
  24407. return this;
  24408. };
  24409. Mesh.prototype._generatePointsArray = function () {
  24410. if (this._geometry) {
  24411. return this._geometry._generatePointsArray();
  24412. }
  24413. return false;
  24414. };
  24415. /**
  24416. * Returns a new Mesh object generated from the current mesh properties.
  24417. * This method must not get confused with createInstance().
  24418. * The parameter `name` is a string, the name given to the new mesh.
  24419. * The optional parameter `newParent` can be any Node object (default `null`).
  24420. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24421. * 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.
  24422. */
  24423. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24424. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24425. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24426. };
  24427. /**
  24428. * Disposes the Mesh.
  24429. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24430. * Returns nothing.
  24431. */
  24432. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24433. var _this = this;
  24434. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24435. this.morphTargetManager = null;
  24436. if (this._geometry) {
  24437. this._geometry.releaseForMesh(this, true);
  24438. }
  24439. // Sources
  24440. var meshes = this.getScene().meshes;
  24441. meshes.forEach(function (abstractMesh) {
  24442. var mesh = abstractMesh;
  24443. if (mesh._source && mesh._source === _this) {
  24444. mesh._source = null;
  24445. }
  24446. });
  24447. this._source = null;
  24448. // Instances
  24449. if (this._instancesBuffer) {
  24450. this._instancesBuffer.dispose();
  24451. this._instancesBuffer = null;
  24452. }
  24453. while (this.instances.length) {
  24454. this.instances[0].dispose();
  24455. }
  24456. // Highlight layers.
  24457. var highlightLayers = this.getScene().highlightLayers;
  24458. for (var i = 0; i < highlightLayers.length; i++) {
  24459. var highlightLayer = highlightLayers[i];
  24460. if (highlightLayer) {
  24461. highlightLayer.removeMesh(this);
  24462. highlightLayer.removeExcludedMesh(this);
  24463. }
  24464. }
  24465. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24466. };
  24467. /**
  24468. * Modifies the mesh geometry according to a displacement map.
  24469. * 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.
  24470. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24471. * This method returns nothing.
  24472. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24473. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24474. * 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.
  24475. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24476. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24477. *
  24478. * Returns the Mesh.
  24479. */
  24480. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24481. var _this = this;
  24482. var scene = this.getScene();
  24483. var onload = function (img) {
  24484. // Getting height map data
  24485. var canvas = document.createElement("canvas");
  24486. var context = canvas.getContext("2d");
  24487. var heightMapWidth = img.width;
  24488. var heightMapHeight = img.height;
  24489. canvas.width = heightMapWidth;
  24490. canvas.height = heightMapHeight;
  24491. context.drawImage(img, 0, 0);
  24492. // Create VertexData from map data
  24493. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24494. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24495. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24496. //execute success callback, if set
  24497. if (onSuccess) {
  24498. onSuccess(_this);
  24499. }
  24500. };
  24501. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24502. return this;
  24503. };
  24504. /**
  24505. * Modifies the mesh geometry according to a displacementMap buffer.
  24506. * 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.
  24507. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24508. * This method returns nothing.
  24509. * 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.
  24510. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24511. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24512. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24513. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24514. *
  24515. * Returns the Mesh.
  24516. */
  24517. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24518. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24519. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24520. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24521. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24522. return this;
  24523. }
  24524. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24525. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24526. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24527. var position = BABYLON.Vector3.Zero();
  24528. var normal = BABYLON.Vector3.Zero();
  24529. var uv = BABYLON.Vector2.Zero();
  24530. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24531. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24532. for (var index = 0; index < positions.length; index += 3) {
  24533. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24534. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24535. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24536. // Compute height
  24537. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24538. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24539. var pos = (u + v * heightMapWidth) * 4;
  24540. var r = buffer[pos] / 255.0;
  24541. var g = buffer[pos + 1] / 255.0;
  24542. var b = buffer[pos + 2] / 255.0;
  24543. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24544. normal.normalize();
  24545. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24546. position = position.add(normal);
  24547. position.toArray(positions, index);
  24548. }
  24549. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24550. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24551. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24552. return this;
  24553. };
  24554. /**
  24555. * Modify the mesh to get a flat shading rendering.
  24556. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24557. * This method returns the Mesh.
  24558. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24559. */
  24560. Mesh.prototype.convertToFlatShadedMesh = function () {
  24561. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24562. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24563. var kinds = this.getVerticesDataKinds();
  24564. var vbs = {};
  24565. var data = {};
  24566. var newdata = {};
  24567. var updatableNormals = false;
  24568. var kindIndex;
  24569. var kind;
  24570. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24571. kind = kinds[kindIndex];
  24572. var vertexBuffer = this.getVertexBuffer(kind);
  24573. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24574. updatableNormals = vertexBuffer.isUpdatable();
  24575. kinds.splice(kindIndex, 1);
  24576. kindIndex--;
  24577. continue;
  24578. }
  24579. vbs[kind] = vertexBuffer;
  24580. data[kind] = vbs[kind].getData();
  24581. newdata[kind] = [];
  24582. }
  24583. // Save previous submeshes
  24584. var previousSubmeshes = this.subMeshes.slice(0);
  24585. var indices = this.getIndices();
  24586. var totalIndices = this.getTotalIndices();
  24587. // Generating unique vertices per face
  24588. var index;
  24589. for (index = 0; index < totalIndices; index++) {
  24590. var vertexIndex = indices[index];
  24591. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24592. kind = kinds[kindIndex];
  24593. var stride = vbs[kind].getStrideSize();
  24594. for (var offset = 0; offset < stride; offset++) {
  24595. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24596. }
  24597. }
  24598. }
  24599. // Updating faces & normal
  24600. var normals = [];
  24601. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24602. for (index = 0; index < totalIndices; index += 3) {
  24603. indices[index] = index;
  24604. indices[index + 1] = index + 1;
  24605. indices[index + 2] = index + 2;
  24606. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24607. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24608. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24609. var p1p2 = p1.subtract(p2);
  24610. var p3p2 = p3.subtract(p2);
  24611. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24612. // Store same normals for every vertex
  24613. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24614. normals.push(normal.x);
  24615. normals.push(normal.y);
  24616. normals.push(normal.z);
  24617. }
  24618. }
  24619. this.setIndices(indices);
  24620. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24621. // Updating vertex buffers
  24622. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24623. kind = kinds[kindIndex];
  24624. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24625. }
  24626. // Updating submeshes
  24627. this.releaseSubMeshes();
  24628. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24629. var previousOne = previousSubmeshes[submeshIndex];
  24630. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24631. }
  24632. this.synchronizeInstances();
  24633. return this;
  24634. };
  24635. /**
  24636. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24637. * In other words, more vertices, no more indices and a single bigger VBO.
  24638. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24639. * Returns the Mesh.
  24640. */
  24641. Mesh.prototype.convertToUnIndexedMesh = function () {
  24642. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24643. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24644. var kinds = this.getVerticesDataKinds();
  24645. var vbs = {};
  24646. var data = {};
  24647. var newdata = {};
  24648. var kindIndex;
  24649. var kind;
  24650. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24651. kind = kinds[kindIndex];
  24652. var vertexBuffer = this.getVertexBuffer(kind);
  24653. vbs[kind] = vertexBuffer;
  24654. data[kind] = vbs[kind].getData();
  24655. newdata[kind] = [];
  24656. }
  24657. // Save previous submeshes
  24658. var previousSubmeshes = this.subMeshes.slice(0);
  24659. var indices = this.getIndices();
  24660. var totalIndices = this.getTotalIndices();
  24661. // Generating unique vertices per face
  24662. var index;
  24663. for (index = 0; index < totalIndices; index++) {
  24664. var vertexIndex = indices[index];
  24665. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24666. kind = kinds[kindIndex];
  24667. var stride = vbs[kind].getStrideSize();
  24668. for (var offset = 0; offset < stride; offset++) {
  24669. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24670. }
  24671. }
  24672. }
  24673. // Updating indices
  24674. for (index = 0; index < totalIndices; index += 3) {
  24675. indices[index] = index;
  24676. indices[index + 1] = index + 1;
  24677. indices[index + 2] = index + 2;
  24678. }
  24679. this.setIndices(indices);
  24680. // Updating vertex buffers
  24681. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24682. kind = kinds[kindIndex];
  24683. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24684. }
  24685. // Updating submeshes
  24686. this.releaseSubMeshes();
  24687. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24688. var previousOne = previousSubmeshes[submeshIndex];
  24689. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24690. }
  24691. this._unIndexed = true;
  24692. this.synchronizeInstances();
  24693. return this;
  24694. };
  24695. /**
  24696. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24697. * This method returns the Mesh.
  24698. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24699. */
  24700. Mesh.prototype.flipFaces = function (flipNormals) {
  24701. if (flipNormals === void 0) { flipNormals = false; }
  24702. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24703. var i;
  24704. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24705. for (i = 0; i < vertex_data.normals.length; i++) {
  24706. vertex_data.normals[i] *= -1;
  24707. }
  24708. }
  24709. if (vertex_data.indices) {
  24710. var temp;
  24711. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24712. // reassign indices
  24713. temp = vertex_data.indices[i + 1];
  24714. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24715. vertex_data.indices[i + 2] = temp;
  24716. }
  24717. }
  24718. vertex_data.applyToMesh(this);
  24719. return this;
  24720. };
  24721. // Instances
  24722. /**
  24723. * Creates a new InstancedMesh object from the mesh model.
  24724. * An instance shares the same properties and the same material than its model.
  24725. * Only these properties of each instance can then be set individually :
  24726. * - position
  24727. * - rotation
  24728. * - rotationQuaternion
  24729. * - setPivotMatrix
  24730. * - scaling
  24731. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24732. * Warning : this method is not supported for Line mesh and LineSystem
  24733. */
  24734. Mesh.prototype.createInstance = function (name) {
  24735. return new BABYLON.InstancedMesh(name, this);
  24736. };
  24737. /**
  24738. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24739. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24740. * This method returns the Mesh.
  24741. */
  24742. Mesh.prototype.synchronizeInstances = function () {
  24743. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24744. var instance = this.instances[instanceIndex];
  24745. instance._syncSubMeshes();
  24746. }
  24747. return this;
  24748. };
  24749. /**
  24750. * Simplify the mesh according to the given array of settings.
  24751. * Function will return immediately and will simplify async. It returns the Mesh.
  24752. * @param settings a collection of simplification settings.
  24753. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24754. * @param type the type of simplification to run.
  24755. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24756. */
  24757. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24758. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24759. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24760. this.getScene().simplificationQueue.addTask({
  24761. settings: settings,
  24762. parallelProcessing: parallelProcessing,
  24763. mesh: this,
  24764. simplificationType: simplificationType,
  24765. successCallback: successCallback
  24766. });
  24767. return this;
  24768. };
  24769. /**
  24770. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24771. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24772. * This should be used together with the simplification to avoid disappearing triangles.
  24773. * Returns the Mesh.
  24774. * @param successCallback an optional success callback to be called after the optimization finished.
  24775. */
  24776. Mesh.prototype.optimizeIndices = function (successCallback) {
  24777. var _this = this;
  24778. var indices = this.getIndices();
  24779. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24780. if (!positions || !indices) {
  24781. return this;
  24782. }
  24783. var vectorPositions = new Array();
  24784. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24785. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24786. }
  24787. var dupes = new Array();
  24788. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24789. var realPos = vectorPositions.length - 1 - iteration;
  24790. var testedPosition = vectorPositions[realPos];
  24791. for (var j = 0; j < realPos; ++j) {
  24792. var againstPosition = vectorPositions[j];
  24793. if (testedPosition.equals(againstPosition)) {
  24794. dupes[realPos] = j;
  24795. break;
  24796. }
  24797. }
  24798. }, function () {
  24799. for (var i = 0; i < indices.length; ++i) {
  24800. indices[i] = dupes[indices[i]] || indices[i];
  24801. }
  24802. //indices are now reordered
  24803. var originalSubMeshes = _this.subMeshes.slice(0);
  24804. _this.setIndices(indices);
  24805. _this.subMeshes = originalSubMeshes;
  24806. if (successCallback) {
  24807. successCallback(_this);
  24808. }
  24809. });
  24810. return this;
  24811. };
  24812. Mesh.prototype.serialize = function (serializationObject) {
  24813. serializationObject.name = this.name;
  24814. serializationObject.id = this.id;
  24815. serializationObject.type = this.getClassName();
  24816. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24817. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24818. }
  24819. serializationObject.position = this.position.asArray();
  24820. if (this.rotationQuaternion) {
  24821. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24822. }
  24823. else if (this.rotation) {
  24824. serializationObject.rotation = this.rotation.asArray();
  24825. }
  24826. serializationObject.scaling = this.scaling.asArray();
  24827. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24828. serializationObject.isEnabled = this.isEnabled();
  24829. serializationObject.isVisible = this.isVisible;
  24830. serializationObject.infiniteDistance = this.infiniteDistance;
  24831. serializationObject.pickable = this.isPickable;
  24832. serializationObject.receiveShadows = this.receiveShadows;
  24833. serializationObject.billboardMode = this.billboardMode;
  24834. serializationObject.visibility = this.visibility;
  24835. serializationObject.checkCollisions = this.checkCollisions;
  24836. serializationObject.isBlocker = this.isBlocker;
  24837. // Parent
  24838. if (this.parent) {
  24839. serializationObject.parentId = this.parent.id;
  24840. }
  24841. // Geometry
  24842. var geometry = this._geometry;
  24843. if (geometry) {
  24844. var geometryId = geometry.id;
  24845. serializationObject.geometryId = geometryId;
  24846. // SubMeshes
  24847. serializationObject.subMeshes = [];
  24848. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24849. var subMesh = this.subMeshes[subIndex];
  24850. serializationObject.subMeshes.push({
  24851. materialIndex: subMesh.materialIndex,
  24852. verticesStart: subMesh.verticesStart,
  24853. verticesCount: subMesh.verticesCount,
  24854. indexStart: subMesh.indexStart,
  24855. indexCount: subMesh.indexCount
  24856. });
  24857. }
  24858. }
  24859. // Material
  24860. if (this.material) {
  24861. serializationObject.materialId = this.material.id;
  24862. }
  24863. else {
  24864. this.material = null;
  24865. }
  24866. // Morph targets
  24867. if (this.morphTargetManager) {
  24868. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24869. }
  24870. // Skeleton
  24871. if (this.skeleton) {
  24872. serializationObject.skeletonId = this.skeleton.id;
  24873. }
  24874. // Physics
  24875. //TODO implement correct serialization for physics impostors.
  24876. var impostor = this.getPhysicsImpostor();
  24877. if (impostor) {
  24878. serializationObject.physicsMass = impostor.getParam("mass");
  24879. serializationObject.physicsFriction = impostor.getParam("friction");
  24880. serializationObject.physicsRestitution = impostor.getParam("mass");
  24881. serializationObject.physicsImpostor = impostor.type;
  24882. }
  24883. // Metadata
  24884. if (this.metadata) {
  24885. serializationObject.metadata = this.metadata;
  24886. }
  24887. // Instances
  24888. serializationObject.instances = [];
  24889. for (var index = 0; index < this.instances.length; index++) {
  24890. var instance = this.instances[index];
  24891. var serializationInstance = {
  24892. name: instance.name,
  24893. position: instance.position.asArray(),
  24894. scaling: instance.scaling.asArray()
  24895. };
  24896. if (instance.rotationQuaternion) {
  24897. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24898. }
  24899. else if (instance.rotation) {
  24900. serializationInstance.rotation = instance.rotation.asArray();
  24901. }
  24902. serializationObject.instances.push(serializationInstance);
  24903. // Animations
  24904. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24905. serializationInstance.ranges = instance.serializeAnimationRanges();
  24906. }
  24907. //
  24908. // Animations
  24909. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24910. serializationObject.ranges = this.serializeAnimationRanges();
  24911. // Layer mask
  24912. serializationObject.layerMask = this.layerMask;
  24913. // Alpha
  24914. serializationObject.alphaIndex = this.alphaIndex;
  24915. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24916. // Overlay
  24917. serializationObject.overlayAlpha = this.overlayAlpha;
  24918. serializationObject.overlayColor = this.overlayColor.asArray();
  24919. serializationObject.renderOverlay = this.renderOverlay;
  24920. // Fog
  24921. serializationObject.applyFog = this.applyFog;
  24922. // Action Manager
  24923. if (this.actionManager) {
  24924. serializationObject.actions = this.actionManager.serialize(this.name);
  24925. }
  24926. };
  24927. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24928. if (!this.geometry) {
  24929. return;
  24930. }
  24931. this._markSubMeshesAsAttributesDirty();
  24932. var morphTargetManager = this._morphTargetManager;
  24933. if (morphTargetManager && morphTargetManager.vertexCount) {
  24934. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24935. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24936. this.morphTargetManager = null;
  24937. return;
  24938. }
  24939. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24940. var morphTarget = morphTargetManager.getActiveTarget(index);
  24941. var positions = morphTarget.getPositions();
  24942. if (!positions) {
  24943. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24944. return;
  24945. }
  24946. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24947. var normals = morphTarget.getNormals();
  24948. if (normals) {
  24949. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24950. }
  24951. var tangents = morphTarget.getTangents();
  24952. if (tangents) {
  24953. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24954. }
  24955. }
  24956. }
  24957. else {
  24958. var index = 0;
  24959. // Positions
  24960. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24961. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24962. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24963. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24964. }
  24965. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24966. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24967. }
  24968. index++;
  24969. }
  24970. }
  24971. };
  24972. // Statics
  24973. /**
  24974. * Returns a new Mesh object parsed from the source provided.
  24975. * The parameter `parsedMesh` is the source.
  24976. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24977. */
  24978. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24979. var mesh;
  24980. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24981. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24982. }
  24983. else {
  24984. mesh = new Mesh(parsedMesh.name, scene);
  24985. }
  24986. mesh.id = parsedMesh.id;
  24987. if (BABYLON.Tags) {
  24988. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24989. }
  24990. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24991. if (parsedMesh.metadata !== undefined) {
  24992. mesh.metadata = parsedMesh.metadata;
  24993. }
  24994. if (parsedMesh.rotationQuaternion) {
  24995. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24996. }
  24997. else if (parsedMesh.rotation) {
  24998. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24999. }
  25000. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25001. if (parsedMesh.localMatrix) {
  25002. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25003. }
  25004. else if (parsedMesh.pivotMatrix) {
  25005. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25006. }
  25007. mesh.setEnabled(parsedMesh.isEnabled);
  25008. mesh.isVisible = parsedMesh.isVisible;
  25009. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25010. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25011. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25012. if (parsedMesh.applyFog !== undefined) {
  25013. mesh.applyFog = parsedMesh.applyFog;
  25014. }
  25015. if (parsedMesh.pickable !== undefined) {
  25016. mesh.isPickable = parsedMesh.pickable;
  25017. }
  25018. if (parsedMesh.alphaIndex !== undefined) {
  25019. mesh.alphaIndex = parsedMesh.alphaIndex;
  25020. }
  25021. mesh.receiveShadows = parsedMesh.receiveShadows;
  25022. mesh.billboardMode = parsedMesh.billboardMode;
  25023. if (parsedMesh.visibility !== undefined) {
  25024. mesh.visibility = parsedMesh.visibility;
  25025. }
  25026. mesh.checkCollisions = parsedMesh.checkCollisions;
  25027. if (parsedMesh.isBlocker !== undefined) {
  25028. mesh.isBlocker = parsedMesh.isBlocker;
  25029. }
  25030. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25031. // freezeWorldMatrix
  25032. if (parsedMesh.freezeWorldMatrix) {
  25033. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25034. }
  25035. // Parent
  25036. if (parsedMesh.parentId) {
  25037. mesh._waitingParentId = parsedMesh.parentId;
  25038. }
  25039. // Actions
  25040. if (parsedMesh.actions !== undefined) {
  25041. mesh._waitingActions = parsedMesh.actions;
  25042. }
  25043. // Overlay
  25044. if (parsedMesh.overlayAlpha !== undefined) {
  25045. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25046. }
  25047. if (parsedMesh.overlayColor !== undefined) {
  25048. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25049. }
  25050. if (parsedMesh.renderOverlay !== undefined) {
  25051. mesh.renderOverlay = parsedMesh.renderOverlay;
  25052. }
  25053. // Geometry
  25054. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25055. if (parsedMesh.delayLoadingFile) {
  25056. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25057. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25058. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25059. if (parsedMesh._binaryInfo) {
  25060. mesh._binaryInfo = parsedMesh._binaryInfo;
  25061. }
  25062. mesh._delayInfo = [];
  25063. if (parsedMesh.hasUVs) {
  25064. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25065. }
  25066. if (parsedMesh.hasUVs2) {
  25067. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25068. }
  25069. if (parsedMesh.hasUVs3) {
  25070. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25071. }
  25072. if (parsedMesh.hasUVs4) {
  25073. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25074. }
  25075. if (parsedMesh.hasUVs5) {
  25076. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25077. }
  25078. if (parsedMesh.hasUVs6) {
  25079. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25080. }
  25081. if (parsedMesh.hasColors) {
  25082. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25083. }
  25084. if (parsedMesh.hasMatricesIndices) {
  25085. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25086. }
  25087. if (parsedMesh.hasMatricesWeights) {
  25088. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25089. }
  25090. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25091. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25092. mesh._checkDelayState();
  25093. }
  25094. }
  25095. else {
  25096. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25097. }
  25098. // Material
  25099. if (parsedMesh.materialId) {
  25100. mesh.setMaterialByID(parsedMesh.materialId);
  25101. }
  25102. else {
  25103. mesh.material = null;
  25104. }
  25105. // Morph targets
  25106. if (parsedMesh.morphTargetManagerId > -1) {
  25107. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25108. }
  25109. // Skeleton
  25110. if (parsedMesh.skeletonId > -1) {
  25111. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25112. if (parsedMesh.numBoneInfluencers) {
  25113. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25114. }
  25115. }
  25116. // Animations
  25117. if (parsedMesh.animations) {
  25118. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25119. var parsedAnimation = parsedMesh.animations[animationIndex];
  25120. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25121. }
  25122. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25123. }
  25124. if (parsedMesh.autoAnimate) {
  25125. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25126. }
  25127. // Layer Mask
  25128. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25129. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25130. }
  25131. else {
  25132. mesh.layerMask = 0x0FFFFFFF;
  25133. }
  25134. // Physics
  25135. if (parsedMesh.physicsImpostor) {
  25136. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25137. mass: parsedMesh.physicsMass,
  25138. friction: parsedMesh.physicsFriction,
  25139. restitution: parsedMesh.physicsRestitution
  25140. }, scene);
  25141. }
  25142. // Instances
  25143. if (parsedMesh.instances) {
  25144. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25145. var parsedInstance = parsedMesh.instances[index];
  25146. var instance = mesh.createInstance(parsedInstance.name);
  25147. if (BABYLON.Tags) {
  25148. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25149. }
  25150. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25151. if (parsedInstance.parentId) {
  25152. instance._waitingParentId = parsedInstance.parentId;
  25153. }
  25154. if (parsedInstance.rotationQuaternion) {
  25155. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25156. }
  25157. else if (parsedInstance.rotation) {
  25158. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25159. }
  25160. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25161. instance.checkCollisions = mesh.checkCollisions;
  25162. if (parsedMesh.animations) {
  25163. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25164. parsedAnimation = parsedMesh.animations[animationIndex];
  25165. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25166. }
  25167. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25168. }
  25169. }
  25170. }
  25171. return mesh;
  25172. };
  25173. /**
  25174. * Creates a ribbon mesh.
  25175. * Please consider using the same method from the MeshBuilder class instead.
  25176. * 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.
  25177. *
  25178. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25179. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25180. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25181. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25182. * 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.
  25183. * 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.
  25184. * 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
  25185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25186. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25188. */
  25189. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25190. if (closeArray === void 0) { closeArray = false; }
  25191. if (updatable === void 0) { updatable = false; }
  25192. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25193. pathArray: pathArray,
  25194. closeArray: closeArray,
  25195. closePath: closePath,
  25196. offset: offset,
  25197. updatable: updatable,
  25198. sideOrientation: sideOrientation,
  25199. instance: instance
  25200. }, scene);
  25201. };
  25202. /**
  25203. * Creates a plane polygonal mesh. By default, this is a disc.
  25204. * Please consider using the same method from the MeshBuilder class instead.
  25205. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25206. * 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.
  25207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25210. */
  25211. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25212. if (scene === void 0) { scene = null; }
  25213. var options = {
  25214. radius: radius,
  25215. tessellation: tessellation,
  25216. sideOrientation: sideOrientation,
  25217. updatable: updatable
  25218. };
  25219. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25220. };
  25221. /**
  25222. * Creates a box mesh.
  25223. * Please consider using the same method from the MeshBuilder class instead.
  25224. * The parameter `size` sets the size (float) of each box side (default 1).
  25225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25226. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25228. */
  25229. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25230. if (scene === void 0) { scene = null; }
  25231. var options = {
  25232. size: size,
  25233. sideOrientation: sideOrientation,
  25234. updatable: updatable
  25235. };
  25236. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25237. };
  25238. /**
  25239. * Creates a sphere mesh.
  25240. * Please consider using the same method from the MeshBuilder class instead.
  25241. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25242. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25246. */
  25247. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25248. var options = {
  25249. segments: segments,
  25250. diameterX: diameter,
  25251. diameterY: diameter,
  25252. diameterZ: diameter,
  25253. sideOrientation: sideOrientation,
  25254. updatable: updatable
  25255. };
  25256. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25257. };
  25258. /**
  25259. * Creates a cylinder or a cone mesh.
  25260. * Please consider using the same method from the MeshBuilder class instead.
  25261. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25262. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25263. * 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.
  25264. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25265. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25266. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25269. */
  25270. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25271. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25272. if (scene !== undefined) {
  25273. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25274. updatable = scene;
  25275. }
  25276. scene = subdivisions;
  25277. subdivisions = 1;
  25278. }
  25279. var options = {
  25280. height: height,
  25281. diameterTop: diameterTop,
  25282. diameterBottom: diameterBottom,
  25283. tessellation: tessellation,
  25284. subdivisions: subdivisions,
  25285. sideOrientation: sideOrientation,
  25286. updatable: updatable
  25287. };
  25288. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25289. };
  25290. // Torus (Code from SharpDX.org)
  25291. /**
  25292. * Creates a torus mesh.
  25293. * Please consider using the same method from the MeshBuilder class instead.
  25294. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25295. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25296. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25298. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25300. */
  25301. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25302. var options = {
  25303. diameter: diameter,
  25304. thickness: thickness,
  25305. tessellation: tessellation,
  25306. sideOrientation: sideOrientation,
  25307. updatable: updatable
  25308. };
  25309. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25310. };
  25311. /**
  25312. * Creates a torus knot mesh.
  25313. * Please consider using the same method from the MeshBuilder class instead.
  25314. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25315. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25316. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25317. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25321. */
  25322. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25323. var options = {
  25324. radius: radius,
  25325. tube: tube,
  25326. radialSegments: radialSegments,
  25327. tubularSegments: tubularSegments,
  25328. p: p,
  25329. q: q,
  25330. sideOrientation: sideOrientation,
  25331. updatable: updatable
  25332. };
  25333. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25334. };
  25335. /**
  25336. * Creates a line mesh.
  25337. * Please consider using the same method from the MeshBuilder class instead.
  25338. * 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.
  25339. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25340. * The parameter `points` is an array successive Vector3.
  25341. * 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
  25342. * When updating an instance, remember that only point positions can change, not the number of points.
  25343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25344. */
  25345. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25346. if (scene === void 0) { scene = null; }
  25347. if (updatable === void 0) { updatable = false; }
  25348. if (instance === void 0) { instance = null; }
  25349. var options = {
  25350. points: points,
  25351. updatable: updatable,
  25352. instance: instance
  25353. };
  25354. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25355. };
  25356. /**
  25357. * Creates a dashed line mesh.
  25358. * Please consider using the same method from the MeshBuilder class instead.
  25359. * 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.
  25360. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25361. * The parameter `points` is an array successive Vector3.
  25362. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25363. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25364. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25365. * 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
  25366. * When updating an instance, remember that only point positions can change, not the number of points.
  25367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25368. */
  25369. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25370. if (scene === void 0) { scene = null; }
  25371. var options = {
  25372. points: points,
  25373. dashSize: dashSize,
  25374. gapSize: gapSize,
  25375. dashNb: dashNb,
  25376. updatable: updatable,
  25377. instance: instance
  25378. };
  25379. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25380. };
  25381. /**
  25382. * Creates a polygon mesh.
  25383. * Please consider using the same method from the MeshBuilder class instead.
  25384. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25385. * 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.
  25386. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25388. * Remember you can only change the shape positions, not their number when updating a polygon.
  25389. */
  25390. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25391. var options = {
  25392. shape: shape,
  25393. holes: holes,
  25394. updatable: updatable,
  25395. sideOrientation: sideOrientation
  25396. };
  25397. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25398. };
  25399. /**
  25400. * Creates an extruded polygon mesh, with depth in the Y direction.
  25401. * Please consider using the same method from the MeshBuilder class instead.
  25402. */
  25403. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25404. var options = {
  25405. shape: shape,
  25406. holes: holes,
  25407. depth: depth,
  25408. updatable: updatable,
  25409. sideOrientation: sideOrientation
  25410. };
  25411. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25412. };
  25413. /**
  25414. * Creates an extruded shape mesh.
  25415. * 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.
  25416. * Please consider using the same method from the MeshBuilder class instead.
  25417. *
  25418. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25419. * 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
  25420. * extruded along the Z axis.
  25421. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25422. * 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.
  25423. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25424. * 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
  25425. * 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
  25426. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25430. */
  25431. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25432. if (scene === void 0) { scene = null; }
  25433. var options = {
  25434. shape: shape,
  25435. path: path,
  25436. scale: scale,
  25437. rotation: rotation,
  25438. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25439. sideOrientation: sideOrientation,
  25440. instance: instance,
  25441. updatable: updatable
  25442. };
  25443. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25444. };
  25445. /**
  25446. * Creates an custom extruded shape mesh.
  25447. * 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.
  25448. * Please consider using the same method from the MeshBuilder class instead.
  25449. *
  25450. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25451. * 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
  25452. * extruded along the Z axis.
  25453. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25454. * 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
  25455. * and the distance of this point from the begining of the path :
  25456. * ```javascript
  25457. * var rotationFunction = function(i, distance) {
  25458. * // do things
  25459. * return rotationValue; }
  25460. * ```
  25461. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25462. * 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
  25463. * and the distance of this point from the begining of the path :
  25464. * ```javascript
  25465. * var scaleFunction = function(i, distance) {
  25466. * // do things
  25467. * return scaleValue;}
  25468. * ```
  25469. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25470. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25471. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25472. * 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
  25473. * 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
  25474. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25476. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25478. */
  25479. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25480. var options = {
  25481. shape: shape,
  25482. path: path,
  25483. scaleFunction: scaleFunction,
  25484. rotationFunction: rotationFunction,
  25485. ribbonCloseArray: ribbonCloseArray,
  25486. ribbonClosePath: ribbonClosePath,
  25487. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25488. sideOrientation: sideOrientation,
  25489. instance: instance,
  25490. updatable: updatable
  25491. };
  25492. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25493. };
  25494. /**
  25495. * Creates lathe mesh.
  25496. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25497. * Please consider using the same method from the MeshBuilder class instead.
  25498. * 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
  25499. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25500. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25501. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25505. */
  25506. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25507. var options = {
  25508. shape: shape,
  25509. radius: radius,
  25510. tessellation: tessellation,
  25511. sideOrientation: sideOrientation,
  25512. updatable: updatable
  25513. };
  25514. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25515. };
  25516. /**
  25517. * Creates a plane mesh.
  25518. * Please consider using the same method from the MeshBuilder class instead.
  25519. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25523. */
  25524. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25525. var options = {
  25526. size: size,
  25527. width: size,
  25528. height: size,
  25529. sideOrientation: sideOrientation,
  25530. updatable: updatable
  25531. };
  25532. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25533. };
  25534. /**
  25535. * Creates a ground mesh.
  25536. * Please consider using the same method from the MeshBuilder class instead.
  25537. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25538. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25540. */
  25541. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25542. var options = {
  25543. width: width,
  25544. height: height,
  25545. subdivisions: subdivisions,
  25546. updatable: updatable
  25547. };
  25548. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25549. };
  25550. /**
  25551. * Creates a tiled ground mesh.
  25552. * Please consider using the same method from the MeshBuilder class instead.
  25553. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25554. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25555. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25556. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25557. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25558. * numbers of subdivisions on the ground width and height of each tile.
  25559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25560. */
  25561. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25562. var options = {
  25563. xmin: xmin,
  25564. zmin: zmin,
  25565. xmax: xmax,
  25566. zmax: zmax,
  25567. subdivisions: subdivisions,
  25568. precision: precision,
  25569. updatable: updatable
  25570. };
  25571. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25572. };
  25573. /**
  25574. * Creates a ground mesh from a height map.
  25575. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25576. * Please consider using the same method from the MeshBuilder class instead.
  25577. * The parameter `url` sets the URL of the height map image resource.
  25578. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25579. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25580. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25581. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25582. * 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).
  25583. * This function is passed the newly built mesh :
  25584. * ```javascript
  25585. * function(mesh) { // do things
  25586. * return; }
  25587. * ```
  25588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25589. */
  25590. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25591. var options = {
  25592. width: width,
  25593. height: height,
  25594. subdivisions: subdivisions,
  25595. minHeight: minHeight,
  25596. maxHeight: maxHeight,
  25597. updatable: updatable,
  25598. onReady: onReady
  25599. };
  25600. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25601. };
  25602. /**
  25603. * Creates a tube mesh.
  25604. * 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.
  25605. * Please consider using the same method from the MeshBuilder class instead.
  25606. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25607. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25608. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25609. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25610. * 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.
  25611. * It must return a radius value (positive float) :
  25612. * ```javascript
  25613. * var radiusFunction = function(i, distance) {
  25614. * // do things
  25615. * return radius; }
  25616. * ```
  25617. * 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
  25618. * 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
  25619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25622. */
  25623. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25624. var options = {
  25625. path: path,
  25626. radius: radius,
  25627. tessellation: tessellation,
  25628. radiusFunction: radiusFunction,
  25629. arc: 1,
  25630. cap: cap,
  25631. updatable: updatable,
  25632. sideOrientation: sideOrientation,
  25633. instance: instance
  25634. };
  25635. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25636. };
  25637. /**
  25638. * Creates a polyhedron mesh.
  25639. * Please consider using the same method from the MeshBuilder class instead.
  25640. * 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
  25641. * to choose the wanted type.
  25642. * The parameter `size` (positive float, default 1) sets the polygon size.
  25643. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25644. * 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`.
  25645. * 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
  25646. * 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)`).
  25647. * 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
  25648. * 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.
  25649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25652. */
  25653. Mesh.CreatePolyhedron = function (name, options, scene) {
  25654. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25655. };
  25656. /**
  25657. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25658. * Please consider using the same method from the MeshBuilder class instead.
  25659. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25660. * 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`).
  25661. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25662. * 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.
  25663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25666. */
  25667. Mesh.CreateIcoSphere = function (name, options, scene) {
  25668. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25669. };
  25670. /**
  25671. * Creates a decal mesh.
  25672. * Please consider using the same method from the MeshBuilder class instead.
  25673. * 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.
  25674. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25675. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25676. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25677. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25678. */
  25679. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25680. var options = {
  25681. position: position,
  25682. normal: normal,
  25683. size: size,
  25684. angle: angle
  25685. };
  25686. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25687. };
  25688. // Skeletons
  25689. /**
  25690. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25691. */
  25692. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25693. if (!this._sourcePositions) {
  25694. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25695. if (!source) {
  25696. return this._sourcePositions;
  25697. }
  25698. this._sourcePositions = new Float32Array(source);
  25699. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25701. }
  25702. }
  25703. return this._sourcePositions;
  25704. };
  25705. /**
  25706. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25707. */
  25708. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25709. if (!this._sourceNormals) {
  25710. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25711. if (!source) {
  25712. return this._sourceNormals;
  25713. }
  25714. this._sourceNormals = new Float32Array(source);
  25715. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25717. }
  25718. }
  25719. return this._sourceNormals;
  25720. };
  25721. /**
  25722. * Updates the vertex buffer by applying transformation from the bones.
  25723. * Returns the Mesh.
  25724. *
  25725. * @param {skeleton} skeleton to apply
  25726. */
  25727. Mesh.prototype.applySkeleton = function (skeleton) {
  25728. if (!this.geometry) {
  25729. return this;
  25730. }
  25731. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25732. return this;
  25733. }
  25734. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25735. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25736. return this;
  25737. }
  25738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25739. return this;
  25740. }
  25741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25742. return this;
  25743. }
  25744. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25745. return this;
  25746. }
  25747. if (!this._sourcePositions) {
  25748. var submeshes = this.subMeshes.slice();
  25749. this.setPositionsForCPUSkinning();
  25750. this.subMeshes = submeshes;
  25751. }
  25752. if (!this._sourceNormals) {
  25753. this.setNormalsForCPUSkinning();
  25754. }
  25755. // positionsData checks for not being Float32Array will only pass at most once
  25756. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25757. if (!positionsData) {
  25758. return this;
  25759. }
  25760. if (!(positionsData instanceof Float32Array)) {
  25761. positionsData = new Float32Array(positionsData);
  25762. }
  25763. // normalsData checks for not being Float32Array will only pass at most once
  25764. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25765. if (!normalsData) {
  25766. return this;
  25767. }
  25768. if (!(normalsData instanceof Float32Array)) {
  25769. normalsData = new Float32Array(normalsData);
  25770. }
  25771. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25772. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25773. if (!matricesWeightsData || !matricesIndicesData) {
  25774. return this;
  25775. }
  25776. var needExtras = this.numBoneInfluencers > 4;
  25777. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25778. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25779. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25780. return this;
  25781. }
  25782. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25783. var tempVector3 = BABYLON.Vector3.Zero();
  25784. var finalMatrix = new BABYLON.Matrix();
  25785. var tempMatrix = new BABYLON.Matrix();
  25786. var matWeightIdx = 0;
  25787. var inf;
  25788. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25789. var weight;
  25790. for (inf = 0; inf < 4; inf++) {
  25791. weight = matricesWeightsData[matWeightIdx + inf];
  25792. if (weight > 0) {
  25793. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25794. finalMatrix.addToSelf(tempMatrix);
  25795. }
  25796. else
  25797. break;
  25798. }
  25799. if (needExtras) {
  25800. for (inf = 0; inf < 4; inf++) {
  25801. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25802. if (weight > 0) {
  25803. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25804. finalMatrix.addToSelf(tempMatrix);
  25805. }
  25806. else
  25807. break;
  25808. }
  25809. }
  25810. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25811. tempVector3.toArray(positionsData, index);
  25812. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25813. tempVector3.toArray(normalsData, index);
  25814. finalMatrix.reset();
  25815. }
  25816. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25817. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25818. return this;
  25819. };
  25820. // Tools
  25821. /**
  25822. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25823. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25824. */
  25825. Mesh.MinMax = function (meshes) {
  25826. var minVector = null;
  25827. var maxVector = null;
  25828. meshes.forEach(function (mesh, index, array) {
  25829. var boundingInfo = mesh.getBoundingInfo();
  25830. var boundingBox = boundingInfo.boundingBox;
  25831. if (!minVector || !maxVector) {
  25832. minVector = boundingBox.minimumWorld;
  25833. maxVector = boundingBox.maximumWorld;
  25834. }
  25835. else {
  25836. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25837. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25838. }
  25839. });
  25840. if (!minVector || !maxVector) {
  25841. return {
  25842. min: BABYLON.Vector3.Zero(),
  25843. max: BABYLON.Vector3.Zero()
  25844. };
  25845. }
  25846. return {
  25847. min: minVector,
  25848. max: maxVector
  25849. };
  25850. };
  25851. /**
  25852. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25853. */
  25854. Mesh.Center = function (meshesOrMinMaxVector) {
  25855. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25856. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25857. };
  25858. /**
  25859. * Merge the array of meshes into a single mesh for performance reasons.
  25860. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25861. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25862. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25863. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25864. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25865. */
  25866. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25867. if (disposeSource === void 0) { disposeSource = true; }
  25868. var index;
  25869. if (!allow32BitsIndices) {
  25870. var totalVertices = 0;
  25871. // Counting vertices
  25872. for (index = 0; index < meshes.length; index++) {
  25873. if (meshes[index]) {
  25874. totalVertices += meshes[index].getTotalVertices();
  25875. if (totalVertices > 65536) {
  25876. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25877. return null;
  25878. }
  25879. }
  25880. }
  25881. }
  25882. // Merge
  25883. var vertexData = null;
  25884. var otherVertexData;
  25885. var indiceArray = new Array();
  25886. var source = null;
  25887. for (index = 0; index < meshes.length; index++) {
  25888. if (meshes[index]) {
  25889. meshes[index].computeWorldMatrix(true);
  25890. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25891. otherVertexData.transform(meshes[index].getWorldMatrix());
  25892. if (vertexData) {
  25893. vertexData.merge(otherVertexData);
  25894. }
  25895. else {
  25896. vertexData = otherVertexData;
  25897. source = meshes[index];
  25898. }
  25899. if (subdivideWithSubMeshes) {
  25900. indiceArray.push(meshes[index].getTotalIndices());
  25901. }
  25902. }
  25903. }
  25904. source = source;
  25905. if (!meshSubclass) {
  25906. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25907. }
  25908. vertexData.applyToMesh(meshSubclass);
  25909. // Setting properties
  25910. meshSubclass.material = source.material;
  25911. meshSubclass.checkCollisions = source.checkCollisions;
  25912. // Cleaning
  25913. if (disposeSource) {
  25914. for (index = 0; index < meshes.length; index++) {
  25915. if (meshes[index]) {
  25916. meshes[index].dispose();
  25917. }
  25918. }
  25919. }
  25920. // Subdivide
  25921. if (subdivideWithSubMeshes) {
  25922. //-- Suppresions du submesh global
  25923. meshSubclass.releaseSubMeshes();
  25924. index = 0;
  25925. var offset = 0;
  25926. //-- aplique la subdivision en fonction du tableau d'indices
  25927. while (index < indiceArray.length) {
  25928. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25929. offset += indiceArray[index];
  25930. index++;
  25931. }
  25932. }
  25933. return meshSubclass;
  25934. };
  25935. // Consts
  25936. Mesh._FRONTSIDE = 0;
  25937. Mesh._BACKSIDE = 1;
  25938. Mesh._DOUBLESIDE = 2;
  25939. Mesh._DEFAULTSIDE = 0;
  25940. Mesh._NO_CAP = 0;
  25941. Mesh._CAP_START = 1;
  25942. Mesh._CAP_END = 2;
  25943. Mesh._CAP_ALL = 3;
  25944. return Mesh;
  25945. }(BABYLON.AbstractMesh));
  25946. BABYLON.Mesh = Mesh;
  25947. })(BABYLON || (BABYLON = {}));
  25948. //# sourceMappingURL=babylon.mesh.js.map
  25949. var BABYLON;
  25950. (function (BABYLON) {
  25951. var BaseSubMesh = /** @class */ (function () {
  25952. function BaseSubMesh() {
  25953. }
  25954. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25955. get: function () {
  25956. return this._materialEffect;
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25962. if (defines === void 0) { defines = null; }
  25963. if (this._materialEffect === effect) {
  25964. if (!effect) {
  25965. this._materialDefines = null;
  25966. }
  25967. return;
  25968. }
  25969. this._materialDefines = defines;
  25970. this._materialEffect = effect;
  25971. };
  25972. return BaseSubMesh;
  25973. }());
  25974. BABYLON.BaseSubMesh = BaseSubMesh;
  25975. var SubMesh = /** @class */ (function (_super) {
  25976. __extends(SubMesh, _super);
  25977. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25978. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25979. var _this = _super.call(this) || this;
  25980. _this.materialIndex = materialIndex;
  25981. _this.verticesStart = verticesStart;
  25982. _this.verticesCount = verticesCount;
  25983. _this.indexStart = indexStart;
  25984. _this.indexCount = indexCount;
  25985. _this._renderId = 0;
  25986. _this._mesh = mesh;
  25987. _this._renderingMesh = renderingMesh || mesh;
  25988. mesh.subMeshes.push(_this);
  25989. _this._trianglePlanes = [];
  25990. _this._id = mesh.subMeshes.length - 1;
  25991. if (createBoundingBox) {
  25992. _this.refreshBoundingInfo();
  25993. mesh.computeWorldMatrix(true);
  25994. }
  25995. return _this;
  25996. }
  25997. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25998. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25999. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26000. };
  26001. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26002. get: function () {
  26003. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. /**
  26009. * Returns the submesh BoudingInfo object.
  26010. */
  26011. SubMesh.prototype.getBoundingInfo = function () {
  26012. if (this.IsGlobal) {
  26013. return this._mesh.getBoundingInfo();
  26014. }
  26015. return this._boundingInfo;
  26016. };
  26017. /**
  26018. * Sets the submesh BoundingInfo.
  26019. * Return the SubMesh.
  26020. */
  26021. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26022. this._boundingInfo = boundingInfo;
  26023. return this;
  26024. };
  26025. /**
  26026. * Returns the mesh of the current submesh.
  26027. */
  26028. SubMesh.prototype.getMesh = function () {
  26029. return this._mesh;
  26030. };
  26031. /**
  26032. * Returns the rendering mesh of the submesh.
  26033. */
  26034. SubMesh.prototype.getRenderingMesh = function () {
  26035. return this._renderingMesh;
  26036. };
  26037. /**
  26038. * Returns the submesh material.
  26039. */
  26040. SubMesh.prototype.getMaterial = function () {
  26041. var rootMaterial = this._renderingMesh.material;
  26042. if (rootMaterial && rootMaterial.getSubMaterial) {
  26043. var multiMaterial = rootMaterial;
  26044. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26045. if (this._currentMaterial !== effectiveMaterial) {
  26046. this._currentMaterial = effectiveMaterial;
  26047. this._materialDefines = null;
  26048. }
  26049. return effectiveMaterial;
  26050. }
  26051. if (!rootMaterial) {
  26052. return this._mesh.getScene().defaultMaterial;
  26053. }
  26054. return rootMaterial;
  26055. };
  26056. // Methods
  26057. /**
  26058. * Sets a new updated BoundingInfo object to the submesh.
  26059. * Returns the SubMesh.
  26060. */
  26061. SubMesh.prototype.refreshBoundingInfo = function () {
  26062. this._lastColliderWorldVertices = null;
  26063. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26064. return this;
  26065. }
  26066. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26067. if (!data) {
  26068. this._boundingInfo = this._mesh.getBoundingInfo();
  26069. return this;
  26070. }
  26071. var indices = this._renderingMesh.getIndices();
  26072. var extend;
  26073. //is this the only submesh?
  26074. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26075. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26076. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26077. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26078. }
  26079. else {
  26080. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26081. }
  26082. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26083. return this;
  26084. };
  26085. SubMesh.prototype._checkCollision = function (collider) {
  26086. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26087. return boundingInfo._checkCollision(collider);
  26088. };
  26089. /**
  26090. * Updates the submesh BoundingInfo.
  26091. * Returns the Submesh.
  26092. */
  26093. SubMesh.prototype.updateBoundingInfo = function (world) {
  26094. var boundingInfo = this.getBoundingInfo();
  26095. if (!boundingInfo) {
  26096. this.refreshBoundingInfo();
  26097. boundingInfo = this.getBoundingInfo();
  26098. }
  26099. boundingInfo.update(world);
  26100. return this;
  26101. };
  26102. /**
  26103. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26104. * Boolean returned.
  26105. */
  26106. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26107. var boundingInfo = this.getBoundingInfo();
  26108. if (!boundingInfo) {
  26109. return false;
  26110. }
  26111. return boundingInfo.isInFrustum(frustumPlanes);
  26112. };
  26113. /**
  26114. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26115. * Boolean returned.
  26116. */
  26117. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26118. var boundingInfo = this.getBoundingInfo();
  26119. if (!boundingInfo) {
  26120. return false;
  26121. }
  26122. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26123. };
  26124. /**
  26125. * Renders the submesh.
  26126. * Returns it.
  26127. */
  26128. SubMesh.prototype.render = function (enableAlphaMode) {
  26129. this._renderingMesh.render(this, enableAlphaMode);
  26130. return this;
  26131. };
  26132. /**
  26133. * Returns a new Index Buffer.
  26134. * Type returned : WebGLBuffer.
  26135. */
  26136. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26137. if (!this._linesIndexBuffer) {
  26138. var linesIndices = [];
  26139. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26140. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26141. }
  26142. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26143. this.linesIndexCount = linesIndices.length;
  26144. }
  26145. return this._linesIndexBuffer;
  26146. };
  26147. /**
  26148. * True is the passed Ray intersects the submesh bounding box.
  26149. * Boolean returned.
  26150. */
  26151. SubMesh.prototype.canIntersects = function (ray) {
  26152. var boundingInfo = this.getBoundingInfo();
  26153. if (!boundingInfo) {
  26154. return false;
  26155. }
  26156. return ray.intersectsBox(boundingInfo.boundingBox);
  26157. };
  26158. /**
  26159. * Returns an object IntersectionInfo.
  26160. */
  26161. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26162. var intersectInfo = null;
  26163. // LineMesh first as it's also a Mesh...
  26164. if (this._mesh instanceof BABYLON.LinesMesh) {
  26165. var lineMesh = this._mesh;
  26166. // Line test
  26167. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26168. var p0 = positions[indices[index]];
  26169. var p1 = positions[indices[index + 1]];
  26170. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26171. if (length < 0) {
  26172. continue;
  26173. }
  26174. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26175. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26176. if (fastCheck) {
  26177. break;
  26178. }
  26179. }
  26180. }
  26181. }
  26182. else {
  26183. // Triangles test
  26184. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26185. var p0 = positions[indices[index]];
  26186. var p1 = positions[indices[index + 1]];
  26187. var p2 = positions[indices[index + 2]];
  26188. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26189. if (currentIntersectInfo) {
  26190. if (currentIntersectInfo.distance < 0) {
  26191. continue;
  26192. }
  26193. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26194. intersectInfo = currentIntersectInfo;
  26195. intersectInfo.faceId = index / 3;
  26196. if (fastCheck) {
  26197. break;
  26198. }
  26199. }
  26200. }
  26201. }
  26202. }
  26203. return intersectInfo;
  26204. };
  26205. SubMesh.prototype._rebuild = function () {
  26206. if (this._linesIndexBuffer) {
  26207. this._linesIndexBuffer = null;
  26208. }
  26209. };
  26210. // Clone
  26211. /**
  26212. * Creates a new Submesh from the passed Mesh.
  26213. */
  26214. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26215. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26216. if (!this.IsGlobal) {
  26217. var boundingInfo = this.getBoundingInfo();
  26218. if (!boundingInfo) {
  26219. return result;
  26220. }
  26221. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26222. }
  26223. return result;
  26224. };
  26225. // Dispose
  26226. /**
  26227. * Disposes the Submesh.
  26228. * Returns nothing.
  26229. */
  26230. SubMesh.prototype.dispose = function () {
  26231. if (this._linesIndexBuffer) {
  26232. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26233. this._linesIndexBuffer = null;
  26234. }
  26235. // Remove from mesh
  26236. var index = this._mesh.subMeshes.indexOf(this);
  26237. this._mesh.subMeshes.splice(index, 1);
  26238. };
  26239. // Statics
  26240. /**
  26241. * Creates a new Submesh from the passed parameters :
  26242. * - materialIndex (integer) : the index of the main mesh material.
  26243. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26244. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26245. * - mesh (Mesh) : the main mesh to create the submesh from.
  26246. * - renderingMesh (optional Mesh) : rendering mesh.
  26247. */
  26248. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26249. var minVertexIndex = Number.MAX_VALUE;
  26250. var maxVertexIndex = -Number.MAX_VALUE;
  26251. renderingMesh = (renderingMesh || mesh);
  26252. var indices = renderingMesh.getIndices();
  26253. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26254. var vertexIndex = indices[index];
  26255. if (vertexIndex < minVertexIndex)
  26256. minVertexIndex = vertexIndex;
  26257. if (vertexIndex > maxVertexIndex)
  26258. maxVertexIndex = vertexIndex;
  26259. }
  26260. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26261. };
  26262. return SubMesh;
  26263. }(BaseSubMesh));
  26264. BABYLON.SubMesh = SubMesh;
  26265. })(BABYLON || (BABYLON = {}));
  26266. //# sourceMappingURL=babylon.subMesh.js.map
  26267. var BABYLON;
  26268. (function (BABYLON) {
  26269. var EffectFallbacks = /** @class */ (function () {
  26270. function EffectFallbacks() {
  26271. this._defines = {};
  26272. this._currentRank = 32;
  26273. this._maxRank = -1;
  26274. }
  26275. EffectFallbacks.prototype.unBindMesh = function () {
  26276. this._mesh = null;
  26277. };
  26278. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26279. if (!this._defines[rank]) {
  26280. if (rank < this._currentRank) {
  26281. this._currentRank = rank;
  26282. }
  26283. if (rank > this._maxRank) {
  26284. this._maxRank = rank;
  26285. }
  26286. this._defines[rank] = new Array();
  26287. }
  26288. this._defines[rank].push(define);
  26289. };
  26290. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26291. this._mesh = mesh;
  26292. if (rank < this._currentRank) {
  26293. this._currentRank = rank;
  26294. }
  26295. if (rank > this._maxRank) {
  26296. this._maxRank = rank;
  26297. }
  26298. };
  26299. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26300. get: function () {
  26301. return this._currentRank <= this._maxRank;
  26302. },
  26303. enumerable: true,
  26304. configurable: true
  26305. });
  26306. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26307. // First we try to switch to CPU skinning
  26308. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26309. this._mesh.computeBonesUsingShaders = false;
  26310. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26311. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26312. var scene = this._mesh.getScene();
  26313. for (var index = 0; index < scene.meshes.length; index++) {
  26314. var otherMesh = scene.meshes[index];
  26315. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26316. otherMesh.computeBonesUsingShaders = false;
  26317. }
  26318. }
  26319. }
  26320. else {
  26321. var currentFallbacks = this._defines[this._currentRank];
  26322. if (currentFallbacks) {
  26323. for (var index = 0; index < currentFallbacks.length; index++) {
  26324. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26325. }
  26326. }
  26327. this._currentRank++;
  26328. }
  26329. return currentDefines;
  26330. };
  26331. return EffectFallbacks;
  26332. }());
  26333. BABYLON.EffectFallbacks = EffectFallbacks;
  26334. var EffectCreationOptions = /** @class */ (function () {
  26335. function EffectCreationOptions() {
  26336. }
  26337. return EffectCreationOptions;
  26338. }());
  26339. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26340. var Effect = /** @class */ (function () {
  26341. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26342. if (samplers === void 0) { samplers = null; }
  26343. if (defines === void 0) { defines = null; }
  26344. if (fallbacks === void 0) { fallbacks = null; }
  26345. if (onCompiled === void 0) { onCompiled = null; }
  26346. if (onError === void 0) { onError = null; }
  26347. var _this = this;
  26348. this.uniqueId = 0;
  26349. this.onCompileObservable = new BABYLON.Observable();
  26350. this.onErrorObservable = new BABYLON.Observable();
  26351. this.onBindObservable = new BABYLON.Observable();
  26352. this._uniformBuffersNames = {};
  26353. this._isReady = false;
  26354. this._compilationError = "";
  26355. this.name = baseName;
  26356. if (attributesNamesOrOptions.attributes) {
  26357. var options = attributesNamesOrOptions;
  26358. this._engine = uniformsNamesOrEngine;
  26359. this._attributesNames = options.attributes;
  26360. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26361. this._samplers = options.samplers;
  26362. this.defines = options.defines;
  26363. this.onError = options.onError;
  26364. this.onCompiled = options.onCompiled;
  26365. this._fallbacks = options.fallbacks;
  26366. this._indexParameters = options.indexParameters;
  26367. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26368. if (options.uniformBuffersNames) {
  26369. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26370. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26371. }
  26372. }
  26373. }
  26374. else {
  26375. this._engine = engine;
  26376. this.defines = defines;
  26377. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26378. this._samplers = samplers;
  26379. this._attributesNames = attributesNamesOrOptions;
  26380. this.onError = onError;
  26381. this.onCompiled = onCompiled;
  26382. this._indexParameters = indexParameters;
  26383. this._fallbacks = fallbacks;
  26384. }
  26385. this.uniqueId = Effect._uniqueIdSeed++;
  26386. var vertexSource;
  26387. var fragmentSource;
  26388. if (baseName.vertexElement) {
  26389. vertexSource = document.getElementById(baseName.vertexElement);
  26390. if (!vertexSource) {
  26391. vertexSource = baseName.vertexElement;
  26392. }
  26393. }
  26394. else {
  26395. vertexSource = baseName.vertex || baseName;
  26396. }
  26397. if (baseName.fragmentElement) {
  26398. fragmentSource = document.getElementById(baseName.fragmentElement);
  26399. if (!fragmentSource) {
  26400. fragmentSource = baseName.fragmentElement;
  26401. }
  26402. }
  26403. else {
  26404. fragmentSource = baseName.fragment || baseName;
  26405. }
  26406. this._loadVertexShader(vertexSource, function (vertexCode) {
  26407. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26408. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26409. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26410. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26411. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26412. if (baseName) {
  26413. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26414. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26415. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26416. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26417. }
  26418. else {
  26419. _this._vertexSourceCode = migratedVertexCode;
  26420. _this._fragmentSourceCode = migratedFragmentCode;
  26421. }
  26422. _this._prepareEffect();
  26423. });
  26424. });
  26425. });
  26426. });
  26427. });
  26428. });
  26429. }
  26430. Object.defineProperty(Effect.prototype, "key", {
  26431. get: function () {
  26432. return this._key;
  26433. },
  26434. enumerable: true,
  26435. configurable: true
  26436. });
  26437. // Properties
  26438. Effect.prototype.isReady = function () {
  26439. return this._isReady;
  26440. };
  26441. Effect.prototype.getEngine = function () {
  26442. return this._engine;
  26443. };
  26444. Effect.prototype.getProgram = function () {
  26445. return this._program;
  26446. };
  26447. Effect.prototype.getAttributesNames = function () {
  26448. return this._attributesNames;
  26449. };
  26450. Effect.prototype.getAttributeLocation = function (index) {
  26451. return this._attributes[index];
  26452. };
  26453. Effect.prototype.getAttributeLocationByName = function (name) {
  26454. var index = this._attributesNames.indexOf(name);
  26455. return this._attributes[index];
  26456. };
  26457. Effect.prototype.getAttributesCount = function () {
  26458. return this._attributes.length;
  26459. };
  26460. Effect.prototype.getUniformIndex = function (uniformName) {
  26461. return this._uniformsNames.indexOf(uniformName);
  26462. };
  26463. Effect.prototype.getUniform = function (uniformName) {
  26464. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26465. };
  26466. Effect.prototype.getSamplers = function () {
  26467. return this._samplers;
  26468. };
  26469. Effect.prototype.getCompilationError = function () {
  26470. return this._compilationError;
  26471. };
  26472. // Methods
  26473. Effect.prototype.executeWhenCompiled = function (func) {
  26474. if (this.isReady()) {
  26475. func(this);
  26476. return;
  26477. }
  26478. this.onCompileObservable.add(function (effect) {
  26479. func(effect);
  26480. });
  26481. };
  26482. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26483. if (BABYLON.Tools.IsWindowObjectExist()) {
  26484. // DOM element ?
  26485. if (vertex instanceof HTMLElement) {
  26486. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26487. callback(vertexCode);
  26488. return;
  26489. }
  26490. }
  26491. // Base64 encoded ?
  26492. if (vertex.substr(0, 7) === "base64:") {
  26493. var vertexBinary = window.atob(vertex.substr(7));
  26494. callback(vertexBinary);
  26495. return;
  26496. }
  26497. // Is in local store ?
  26498. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26499. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26500. return;
  26501. }
  26502. var vertexShaderUrl;
  26503. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26504. vertexShaderUrl = vertex;
  26505. }
  26506. else {
  26507. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26508. }
  26509. // Vertex shader
  26510. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26511. };
  26512. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26513. if (BABYLON.Tools.IsWindowObjectExist()) {
  26514. // DOM element ?
  26515. if (fragment instanceof HTMLElement) {
  26516. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26517. callback(fragmentCode);
  26518. return;
  26519. }
  26520. }
  26521. // Base64 encoded ?
  26522. if (fragment.substr(0, 7) === "base64:") {
  26523. var fragmentBinary = window.atob(fragment.substr(7));
  26524. callback(fragmentBinary);
  26525. return;
  26526. }
  26527. // Is in local store ?
  26528. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26529. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26530. return;
  26531. }
  26532. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26533. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26534. return;
  26535. }
  26536. var fragmentShaderUrl;
  26537. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26538. fragmentShaderUrl = fragment;
  26539. }
  26540. else {
  26541. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26542. }
  26543. // Fragment shader
  26544. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26545. };
  26546. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26547. // Rebuild shaders source code
  26548. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26549. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26550. vertexCode = prefix + vertexCode;
  26551. fragmentCode = prefix + fragmentCode;
  26552. // Number lines of shaders source code
  26553. var i = 2;
  26554. var regex = /\n/gm;
  26555. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26556. i = 2;
  26557. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26558. // Dump shaders name and formatted source code
  26559. if (this.name.vertexElement) {
  26560. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26561. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26562. }
  26563. else if (this.name.vertex) {
  26564. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26565. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26566. }
  26567. else {
  26568. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26569. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26570. }
  26571. };
  26572. ;
  26573. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26574. var preparedSourceCode = this._processPrecision(sourceCode);
  26575. if (this._engine.webGLVersion == 1) {
  26576. callback(preparedSourceCode);
  26577. return;
  26578. }
  26579. // Already converted
  26580. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26581. callback(preparedSourceCode.replace("#version 300 es", ""));
  26582. return;
  26583. }
  26584. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26585. // Remove extensions
  26586. // #extension GL_OES_standard_derivatives : enable
  26587. // #extension GL_EXT_shader_texture_lod : enable
  26588. // #extension GL_EXT_frag_depth : enable
  26589. // #extension GL_EXT_draw_buffers : require
  26590. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26591. var result = preparedSourceCode.replace(regex, "");
  26592. // Migrate to GLSL v300
  26593. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26594. result = result.replace(/attribute[ \t]/g, "in ");
  26595. result = result.replace(/[ \t]attribute/g, " in");
  26596. if (isFragment) {
  26597. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26598. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26599. result = result.replace(/texture2D\s*\(/g, "texture(");
  26600. result = result.replace(/textureCube\s*\(/g, "texture(");
  26601. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26602. result = result.replace(/gl_FragColor/g, "glFragColor");
  26603. result = result.replace(/gl_FragData/g, "glFragData");
  26604. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26605. }
  26606. callback(result);
  26607. };
  26608. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26609. var _this = this;
  26610. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26611. var match = regex.exec(sourceCode);
  26612. var returnValue = new String(sourceCode);
  26613. while (match != null) {
  26614. var includeFile = match[1];
  26615. // Uniform declaration
  26616. if (includeFile.indexOf("__decl__") !== -1) {
  26617. includeFile = includeFile.replace(/__decl__/, "");
  26618. if (this._engine.supportsUniformBuffers) {
  26619. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26620. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26621. }
  26622. includeFile = includeFile + "Declaration";
  26623. }
  26624. if (Effect.IncludesShadersStore[includeFile]) {
  26625. // Substitution
  26626. var includeContent = Effect.IncludesShadersStore[includeFile];
  26627. if (match[2]) {
  26628. var splits = match[3].split(",");
  26629. for (var index = 0; index < splits.length; index += 2) {
  26630. var source = new RegExp(splits[index], "g");
  26631. var dest = splits[index + 1];
  26632. includeContent = includeContent.replace(source, dest);
  26633. }
  26634. }
  26635. if (match[4]) {
  26636. var indexString = match[5];
  26637. if (indexString.indexOf("..") !== -1) {
  26638. var indexSplits = indexString.split("..");
  26639. var minIndex = parseInt(indexSplits[0]);
  26640. var maxIndex = parseInt(indexSplits[1]);
  26641. var sourceIncludeContent = includeContent.slice(0);
  26642. includeContent = "";
  26643. if (isNaN(maxIndex)) {
  26644. maxIndex = this._indexParameters[indexSplits[1]];
  26645. }
  26646. for (var i = minIndex; i < maxIndex; i++) {
  26647. if (!this._engine.supportsUniformBuffers) {
  26648. // Ubo replacement
  26649. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26650. return p1 + "{X}";
  26651. });
  26652. }
  26653. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26654. }
  26655. }
  26656. else {
  26657. if (!this._engine.supportsUniformBuffers) {
  26658. // Ubo replacement
  26659. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26660. return p1 + "{X}";
  26661. });
  26662. }
  26663. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26664. }
  26665. }
  26666. // Replace
  26667. returnValue = returnValue.replace(match[0], includeContent);
  26668. }
  26669. else {
  26670. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26671. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26672. Effect.IncludesShadersStore[includeFile] = fileContent;
  26673. _this._processIncludes(returnValue, callback);
  26674. });
  26675. return;
  26676. }
  26677. match = regex.exec(sourceCode);
  26678. }
  26679. callback(returnValue);
  26680. };
  26681. Effect.prototype._processPrecision = function (source) {
  26682. if (source.indexOf("precision highp float") === -1) {
  26683. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26684. source = "precision mediump float;\n" + source;
  26685. }
  26686. else {
  26687. source = "precision highp float;\n" + source;
  26688. }
  26689. }
  26690. else {
  26691. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26692. source = source.replace("precision highp float", "precision mediump float");
  26693. }
  26694. }
  26695. return source;
  26696. };
  26697. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26698. var _this = this;
  26699. this._isReady = false;
  26700. this._vertexSourceCodeOverride = vertexSourceCode;
  26701. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26702. this.onError = function (effect, error) {
  26703. if (onError) {
  26704. onError(error);
  26705. }
  26706. };
  26707. this.onCompiled = function () {
  26708. var scenes = _this.getEngine().scenes;
  26709. for (var i = 0; i < scenes.length; i++) {
  26710. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26711. }
  26712. if (onCompiled) {
  26713. onCompiled(_this._program);
  26714. }
  26715. };
  26716. this._fallbacks = null;
  26717. this._prepareEffect();
  26718. };
  26719. Effect.prototype._prepareEffect = function () {
  26720. var attributesNames = this._attributesNames;
  26721. var defines = this.defines;
  26722. var fallbacks = this._fallbacks;
  26723. this._valueCache = {};
  26724. var previousProgram = this._program;
  26725. try {
  26726. var engine = this._engine;
  26727. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26728. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26729. }
  26730. else {
  26731. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26732. }
  26733. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26734. if (engine.webGLVersion > 1) {
  26735. for (var name in this._uniformBuffersNames) {
  26736. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26737. }
  26738. }
  26739. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26740. this._attributes = engine.getAttributes(this._program, attributesNames);
  26741. var index;
  26742. for (index = 0; index < this._samplers.length; index++) {
  26743. var sampler = this.getUniform(this._samplers[index]);
  26744. if (sampler == null) {
  26745. this._samplers.splice(index, 1);
  26746. index--;
  26747. }
  26748. }
  26749. engine.bindSamplers(this);
  26750. this._compilationError = "";
  26751. this._isReady = true;
  26752. if (this.onCompiled) {
  26753. this.onCompiled(this);
  26754. }
  26755. this.onCompileObservable.notifyObservers(this);
  26756. this.onCompileObservable.clear();
  26757. // Unbind mesh reference in fallbacks
  26758. if (this._fallbacks) {
  26759. this._fallbacks.unBindMesh();
  26760. }
  26761. if (previousProgram) {
  26762. this.getEngine()._deleteProgram(previousProgram);
  26763. }
  26764. }
  26765. catch (e) {
  26766. this._compilationError = e.message;
  26767. // Let's go through fallbacks then
  26768. BABYLON.Tools.Error("Unable to compile effect:");
  26769. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26770. return " " + uniform;
  26771. }));
  26772. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26773. return " " + attribute;
  26774. }));
  26775. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26776. BABYLON.Tools.Error("Error: " + this._compilationError);
  26777. if (previousProgram) {
  26778. this._program = previousProgram;
  26779. this._isReady = true;
  26780. if (this.onError) {
  26781. this.onError(this, this._compilationError);
  26782. }
  26783. this.onErrorObservable.notifyObservers(this);
  26784. }
  26785. if (fallbacks && fallbacks.isMoreFallbacks) {
  26786. BABYLON.Tools.Error("Trying next fallback.");
  26787. this.defines = fallbacks.reduce(this.defines);
  26788. this._prepareEffect();
  26789. }
  26790. else {
  26791. if (this.onError) {
  26792. this.onError(this, this._compilationError);
  26793. }
  26794. this.onErrorObservable.notifyObservers(this);
  26795. this.onErrorObservable.clear();
  26796. // Unbind mesh reference in fallbacks
  26797. if (this._fallbacks) {
  26798. this._fallbacks.unBindMesh();
  26799. }
  26800. }
  26801. }
  26802. };
  26803. Object.defineProperty(Effect.prototype, "isSupported", {
  26804. get: function () {
  26805. return this._compilationError === "";
  26806. },
  26807. enumerable: true,
  26808. configurable: true
  26809. });
  26810. Effect.prototype._bindTexture = function (channel, texture) {
  26811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26812. };
  26813. Effect.prototype.setTexture = function (channel, texture) {
  26814. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26815. };
  26816. Effect.prototype.setTextureArray = function (channel, textures) {
  26817. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26818. var initialPos = this._samplers.indexOf(channel);
  26819. for (var index = 1; index < textures.length; index++) {
  26820. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26821. }
  26822. }
  26823. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26824. };
  26825. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26826. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26827. };
  26828. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26829. var cache = this._valueCache[uniformName];
  26830. var flag = matrix.updateFlag;
  26831. if (cache !== undefined && cache === flag) {
  26832. return false;
  26833. }
  26834. this._valueCache[uniformName] = flag;
  26835. return true;
  26836. };
  26837. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26838. var cache = this._valueCache[uniformName];
  26839. if (!cache) {
  26840. cache = [x, y];
  26841. this._valueCache[uniformName] = cache;
  26842. return true;
  26843. }
  26844. var changed = false;
  26845. if (cache[0] !== x) {
  26846. cache[0] = x;
  26847. changed = true;
  26848. }
  26849. if (cache[1] !== y) {
  26850. cache[1] = y;
  26851. changed = true;
  26852. }
  26853. return changed;
  26854. };
  26855. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26856. var cache = this._valueCache[uniformName];
  26857. if (!cache) {
  26858. cache = [x, y, z];
  26859. this._valueCache[uniformName] = cache;
  26860. return true;
  26861. }
  26862. var changed = false;
  26863. if (cache[0] !== x) {
  26864. cache[0] = x;
  26865. changed = true;
  26866. }
  26867. if (cache[1] !== y) {
  26868. cache[1] = y;
  26869. changed = true;
  26870. }
  26871. if (cache[2] !== z) {
  26872. cache[2] = z;
  26873. changed = true;
  26874. }
  26875. return changed;
  26876. };
  26877. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26878. var cache = this._valueCache[uniformName];
  26879. if (!cache) {
  26880. cache = [x, y, z, w];
  26881. this._valueCache[uniformName] = cache;
  26882. return true;
  26883. }
  26884. var changed = false;
  26885. if (cache[0] !== x) {
  26886. cache[0] = x;
  26887. changed = true;
  26888. }
  26889. if (cache[1] !== y) {
  26890. cache[1] = y;
  26891. changed = true;
  26892. }
  26893. if (cache[2] !== z) {
  26894. cache[2] = z;
  26895. changed = true;
  26896. }
  26897. if (cache[3] !== w) {
  26898. cache[3] = w;
  26899. changed = true;
  26900. }
  26901. return changed;
  26902. };
  26903. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26904. var bufferName = this._uniformBuffersNames[name];
  26905. if (Effect._baseCache[bufferName] === buffer) {
  26906. return;
  26907. }
  26908. Effect._baseCache[bufferName] = buffer;
  26909. this._engine.bindUniformBufferBase(buffer, bufferName);
  26910. };
  26911. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26912. this._engine.bindUniformBlock(this._program, blockName, index);
  26913. };
  26914. Effect.prototype.setIntArray = function (uniformName, array) {
  26915. this._valueCache[uniformName] = null;
  26916. this._engine.setIntArray(this.getUniform(uniformName), array);
  26917. return this;
  26918. };
  26919. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26920. this._valueCache[uniformName] = null;
  26921. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26922. return this;
  26923. };
  26924. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26925. this._valueCache[uniformName] = null;
  26926. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26927. return this;
  26928. };
  26929. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26930. this._valueCache[uniformName] = null;
  26931. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26932. return this;
  26933. };
  26934. Effect.prototype.setFloatArray = function (uniformName, array) {
  26935. this._valueCache[uniformName] = null;
  26936. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26937. return this;
  26938. };
  26939. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26940. this._valueCache[uniformName] = null;
  26941. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26942. return this;
  26943. };
  26944. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26945. this._valueCache[uniformName] = null;
  26946. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26947. return this;
  26948. };
  26949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26950. this._valueCache[uniformName] = null;
  26951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26952. return this;
  26953. };
  26954. Effect.prototype.setArray = function (uniformName, array) {
  26955. this._valueCache[uniformName] = null;
  26956. this._engine.setArray(this.getUniform(uniformName), array);
  26957. return this;
  26958. };
  26959. Effect.prototype.setArray2 = function (uniformName, array) {
  26960. this._valueCache[uniformName] = null;
  26961. this._engine.setArray2(this.getUniform(uniformName), array);
  26962. return this;
  26963. };
  26964. Effect.prototype.setArray3 = function (uniformName, array) {
  26965. this._valueCache[uniformName] = null;
  26966. this._engine.setArray3(this.getUniform(uniformName), array);
  26967. return this;
  26968. };
  26969. Effect.prototype.setArray4 = function (uniformName, array) {
  26970. this._valueCache[uniformName] = null;
  26971. this._engine.setArray4(this.getUniform(uniformName), array);
  26972. return this;
  26973. };
  26974. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26975. if (!matrices) {
  26976. return this;
  26977. }
  26978. this._valueCache[uniformName] = null;
  26979. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26980. return this;
  26981. };
  26982. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26983. if (this._cacheMatrix(uniformName, matrix)) {
  26984. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26985. }
  26986. return this;
  26987. };
  26988. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26989. this._valueCache[uniformName] = null;
  26990. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26991. return this;
  26992. };
  26993. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26994. this._valueCache[uniformName] = null;
  26995. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26996. return this;
  26997. };
  26998. Effect.prototype.setFloat = function (uniformName, value) {
  26999. var cache = this._valueCache[uniformName];
  27000. if (cache !== undefined && cache === value)
  27001. return this;
  27002. this._valueCache[uniformName] = value;
  27003. this._engine.setFloat(this.getUniform(uniformName), value);
  27004. return this;
  27005. };
  27006. Effect.prototype.setBool = function (uniformName, bool) {
  27007. var cache = this._valueCache[uniformName];
  27008. if (cache !== undefined && cache === bool)
  27009. return this;
  27010. this._valueCache[uniformName] = bool;
  27011. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27012. return this;
  27013. };
  27014. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27015. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27016. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27017. }
  27018. return this;
  27019. };
  27020. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27021. if (this._cacheFloat2(uniformName, x, y)) {
  27022. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27023. }
  27024. return this;
  27025. };
  27026. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27027. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27028. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27029. }
  27030. return this;
  27031. };
  27032. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27033. if (this._cacheFloat3(uniformName, x, y, z)) {
  27034. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27035. }
  27036. return this;
  27037. };
  27038. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27039. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27040. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27041. }
  27042. return this;
  27043. };
  27044. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27045. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27046. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27047. }
  27048. return this;
  27049. };
  27050. Effect.prototype.setColor3 = function (uniformName, color3) {
  27051. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27052. this._engine.setColor3(this.getUniform(uniformName), color3);
  27053. }
  27054. return this;
  27055. };
  27056. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27057. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27058. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27059. }
  27060. return this;
  27061. };
  27062. Effect.ResetCache = function () {
  27063. Effect._baseCache = {};
  27064. };
  27065. Effect._uniqueIdSeed = 0;
  27066. Effect._baseCache = {};
  27067. // Statics
  27068. Effect.ShadersStore = {};
  27069. Effect.IncludesShadersStore = {};
  27070. return Effect;
  27071. }());
  27072. BABYLON.Effect = Effect;
  27073. })(BABYLON || (BABYLON = {}));
  27074. //# sourceMappingURL=babylon.effect.js.map
  27075. var BABYLON;
  27076. (function (BABYLON) {
  27077. var MaterialHelper = /** @class */ (function () {
  27078. function MaterialHelper() {
  27079. }
  27080. MaterialHelper.BindEyePosition = function (effect, scene) {
  27081. if (scene._forcedViewPosition) {
  27082. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  27083. return;
  27084. }
  27085. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  27086. };
  27087. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  27088. defines._needUVs = true;
  27089. defines[key] = true;
  27090. if (texture.getTextureMatrix().isIdentity(true)) {
  27091. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  27092. if (texture.coordinatesIndex === 0) {
  27093. defines["MAINUV1"] = true;
  27094. }
  27095. else {
  27096. defines["MAINUV2"] = true;
  27097. }
  27098. }
  27099. else {
  27100. defines[key + "DIRECTUV"] = 0;
  27101. }
  27102. };
  27103. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  27104. var matrix = texture.getTextureMatrix();
  27105. if (!matrix.isIdentity(true)) {
  27106. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  27107. }
  27108. };
  27109. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  27110. if (defines._areMiscDirty) {
  27111. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  27112. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  27113. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  27114. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  27115. }
  27116. };
  27117. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  27118. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  27119. var changed = false;
  27120. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  27121. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  27122. changed = true;
  27123. }
  27124. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  27125. defines["ALPHATEST"] = !defines["ALPHATEST"];
  27126. changed = true;
  27127. }
  27128. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  27129. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  27130. changed = true;
  27131. }
  27132. if (defines["INSTANCES"] !== useInstances) {
  27133. defines["INSTANCES"] = useInstances;
  27134. changed = true;
  27135. }
  27136. if (changed) {
  27137. defines.markAsUnprocessed();
  27138. }
  27139. };
  27140. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  27141. if (useMorphTargets === void 0) { useMorphTargets = false; }
  27142. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  27143. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  27144. return false;
  27145. }
  27146. defines._normals = defines._needNormals;
  27147. defines._uvs = defines._needUVs;
  27148. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  27149. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27150. defines["TANGENT"] = true;
  27151. }
  27152. if (defines._needUVs) {
  27153. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  27154. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  27155. }
  27156. else {
  27157. defines["UV1"] = false;
  27158. defines["UV2"] = false;
  27159. }
  27160. if (useVertexColor) {
  27161. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  27162. defines["VERTEXCOLOR"] = hasVertexColors;
  27163. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  27164. }
  27165. if (useBones) {
  27166. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27167. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  27168. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  27169. }
  27170. else {
  27171. defines["NUM_BONE_INFLUENCERS"] = 0;
  27172. defines["BonesPerMesh"] = 0;
  27173. }
  27174. }
  27175. if (useMorphTargets) {
  27176. var manager = mesh.morphTargetManager;
  27177. if (manager) {
  27178. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  27179. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  27180. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  27181. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  27182. }
  27183. else {
  27184. defines["MORPHTARGETS_TANGENT"] = false;
  27185. defines["MORPHTARGETS_NORMAL"] = false;
  27186. defines["MORPHTARGETS"] = false;
  27187. defines["NUM_MORPH_INFLUENCERS"] = 0;
  27188. }
  27189. }
  27190. return true;
  27191. };
  27192. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  27193. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27194. if (disableLighting === void 0) { disableLighting = false; }
  27195. if (!defines._areLightsDirty) {
  27196. return defines._needNormals;
  27197. }
  27198. var lightIndex = 0;
  27199. var needNormals = false;
  27200. var needRebuild = false;
  27201. var lightmapMode = false;
  27202. var shadowEnabled = false;
  27203. var specularEnabled = false;
  27204. if (scene.lightsEnabled && !disableLighting) {
  27205. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27206. var light = _a[_i];
  27207. needNormals = true;
  27208. if (defines["LIGHT" + lightIndex] === undefined) {
  27209. needRebuild = true;
  27210. }
  27211. defines["LIGHT" + lightIndex] = true;
  27212. defines["SPOTLIGHT" + lightIndex] = false;
  27213. defines["HEMILIGHT" + lightIndex] = false;
  27214. defines["POINTLIGHT" + lightIndex] = false;
  27215. defines["DIRLIGHT" + lightIndex] = false;
  27216. var type;
  27217. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  27218. type = "SPOTLIGHT" + lightIndex;
  27219. }
  27220. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  27221. type = "HEMILIGHT" + lightIndex;
  27222. }
  27223. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  27224. type = "POINTLIGHT" + lightIndex;
  27225. }
  27226. else {
  27227. type = "DIRLIGHT" + lightIndex;
  27228. }
  27229. defines[type] = true;
  27230. // Specular
  27231. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  27232. specularEnabled = true;
  27233. }
  27234. // Shadows
  27235. defines["SHADOW" + lightIndex] = false;
  27236. defines["SHADOWPCF" + lightIndex] = false;
  27237. defines["SHADOWESM" + lightIndex] = false;
  27238. defines["SHADOWCUBE" + lightIndex] = false;
  27239. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  27240. var shadowGenerator = light.getShadowGenerator();
  27241. if (shadowGenerator) {
  27242. shadowEnabled = true;
  27243. shadowGenerator.prepareDefines(defines, lightIndex);
  27244. }
  27245. }
  27246. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  27247. lightmapMode = true;
  27248. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  27249. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  27250. }
  27251. else {
  27252. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  27253. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  27254. }
  27255. lightIndex++;
  27256. if (lightIndex === maxSimultaneousLights)
  27257. break;
  27258. }
  27259. }
  27260. defines["SPECULARTERM"] = specularEnabled;
  27261. defines["SHADOWS"] = shadowEnabled;
  27262. // Resetting all other lights if any
  27263. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  27264. if (defines["LIGHT" + index] !== undefined) {
  27265. defines["LIGHT" + index] = false;
  27266. defines["HEMILIGHT" + lightIndex] = false;
  27267. defines["POINTLIGHT" + lightIndex] = false;
  27268. defines["DIRLIGHT" + lightIndex] = false;
  27269. defines["SPOTLIGHT" + lightIndex] = false;
  27270. defines["SHADOW" + lightIndex] = false;
  27271. }
  27272. }
  27273. var caps = scene.getEngine().getCaps();
  27274. if (defines["SHADOWFLOAT"] === undefined) {
  27275. needRebuild = true;
  27276. }
  27277. defines["SHADOWFLOAT"] = shadowEnabled &&
  27278. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  27279. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  27280. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  27281. if (needRebuild) {
  27282. defines.rebuild();
  27283. }
  27284. return needNormals;
  27285. };
  27286. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  27287. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27288. var uniformsList;
  27289. var uniformBuffersList = null;
  27290. if (uniformsListOrOptions.uniformsNames) {
  27291. var options = uniformsListOrOptions;
  27292. uniformsList = options.uniformsNames;
  27293. uniformBuffersList = options.uniformBuffersNames;
  27294. samplersList = options.samplers;
  27295. defines = options.defines;
  27296. maxSimultaneousLights = options.maxSimultaneousLights;
  27297. }
  27298. else {
  27299. uniformsList = uniformsListOrOptions;
  27300. if (!samplersList) {
  27301. samplersList = [];
  27302. }
  27303. }
  27304. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27305. if (!defines["LIGHT" + lightIndex]) {
  27306. break;
  27307. }
  27308. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  27309. if (uniformBuffersList) {
  27310. uniformBuffersList.push("Light" + lightIndex);
  27311. }
  27312. samplersList.push("shadowSampler" + lightIndex);
  27313. }
  27314. if (defines["NUM_MORPH_INFLUENCERS"]) {
  27315. uniformsList.push("morphTargetInfluences");
  27316. }
  27317. };
  27318. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  27319. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27320. if (rank === void 0) { rank = 0; }
  27321. var lightFallbackRank = 0;
  27322. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27323. if (!defines["LIGHT" + lightIndex]) {
  27324. break;
  27325. }
  27326. if (lightIndex > 0) {
  27327. lightFallbackRank = rank + lightIndex;
  27328. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  27329. }
  27330. if (!defines["SHADOWS"]) {
  27331. if (defines["SHADOW" + lightIndex]) {
  27332. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  27333. }
  27334. if (defines["SHADOWPCF" + lightIndex]) {
  27335. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  27336. }
  27337. if (defines["SHADOWESM" + lightIndex]) {
  27338. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  27339. }
  27340. }
  27341. }
  27342. return lightFallbackRank++;
  27343. };
  27344. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  27345. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  27346. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  27347. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  27348. var manager = mesh.morphTargetManager;
  27349. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  27350. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  27351. for (var index = 0; index < influencers; index++) {
  27352. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  27353. if (normal) {
  27354. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  27355. }
  27356. if (tangent) {
  27357. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  27358. }
  27359. if (attribs.length > maxAttributesCount) {
  27360. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  27361. }
  27362. }
  27363. }
  27364. };
  27365. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  27366. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  27367. fallbacks.addCPUSkinningFallback(0, mesh);
  27368. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27369. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27370. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  27371. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  27372. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  27373. }
  27374. }
  27375. };
  27376. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  27377. if (defines["INSTANCES"]) {
  27378. attribs.push("world0");
  27379. attribs.push("world1");
  27380. attribs.push("world2");
  27381. attribs.push("world3");
  27382. }
  27383. };
  27384. // Bindings
  27385. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  27386. if (light.shadowEnabled && mesh.receiveShadows) {
  27387. var shadowGenerator = light.getShadowGenerator();
  27388. if (shadowGenerator) {
  27389. shadowGenerator.bindShadowLight(lightIndex, effect);
  27390. }
  27391. }
  27392. };
  27393. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  27394. light.transferToEffect(effect, lightIndex + "");
  27395. };
  27396. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  27397. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27398. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  27399. var lightIndex = 0;
  27400. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27401. var light = _a[_i];
  27402. var scaledIntensity = light.getScaledIntensity();
  27403. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  27404. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27405. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  27406. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  27407. if (defines["SPECULARTERM"]) {
  27408. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  27409. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  27410. }
  27411. // Shadows
  27412. if (scene.shadowsEnabled) {
  27413. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  27414. }
  27415. light._uniformBuffer.update();
  27416. lightIndex++;
  27417. if (lightIndex === maxSimultaneousLights)
  27418. break;
  27419. }
  27420. };
  27421. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  27422. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  27423. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  27424. effect.setColor3("vFogColor", scene.fogColor);
  27425. }
  27426. };
  27427. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  27428. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27429. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  27430. if (matrices && effect) {
  27431. effect.setMatrices("mBones", matrices);
  27432. }
  27433. }
  27434. };
  27435. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  27436. var manager = abstractMesh.morphTargetManager;
  27437. if (!abstractMesh || !manager) {
  27438. return;
  27439. }
  27440. effect.setFloatArray("morphTargetInfluences", manager.influences);
  27441. };
  27442. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  27443. if (defines["LOGARITHMICDEPTH"]) {
  27444. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  27445. }
  27446. };
  27447. MaterialHelper.BindClipPlane = function (effect, scene) {
  27448. if (scene.clipPlane) {
  27449. var clipPlane = scene.clipPlane;
  27450. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27451. }
  27452. };
  27453. return MaterialHelper;
  27454. }());
  27455. BABYLON.MaterialHelper = MaterialHelper;
  27456. })(BABYLON || (BABYLON = {}));
  27457. //# sourceMappingURL=babylon.materialHelper.js.map
  27458. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27459. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27460. s = arguments[i];
  27461. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27462. t[p] = s[p];
  27463. }
  27464. return t;
  27465. };
  27466. var BABYLON;
  27467. (function (BABYLON) {
  27468. var MaterialDefines = /** @class */ (function () {
  27469. function MaterialDefines() {
  27470. this._isDirty = true;
  27471. this._areLightsDirty = true;
  27472. this._areAttributesDirty = true;
  27473. this._areTexturesDirty = true;
  27474. this._areFresnelDirty = true;
  27475. this._areMiscDirty = true;
  27476. this._areImageProcessingDirty = true;
  27477. this._normals = false;
  27478. this._uvs = false;
  27479. this._needNormals = false;
  27480. this._needUVs = false;
  27481. }
  27482. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27483. get: function () {
  27484. return this._isDirty;
  27485. },
  27486. enumerable: true,
  27487. configurable: true
  27488. });
  27489. MaterialDefines.prototype.markAsProcessed = function () {
  27490. this._isDirty = false;
  27491. this._areAttributesDirty = false;
  27492. this._areTexturesDirty = false;
  27493. this._areFresnelDirty = false;
  27494. this._areLightsDirty = false;
  27495. this._areMiscDirty = false;
  27496. this._areImageProcessingDirty = false;
  27497. };
  27498. MaterialDefines.prototype.markAsUnprocessed = function () {
  27499. this._isDirty = true;
  27500. };
  27501. MaterialDefines.prototype.markAllAsDirty = function () {
  27502. this._areTexturesDirty = true;
  27503. this._areAttributesDirty = true;
  27504. this._areLightsDirty = true;
  27505. this._areFresnelDirty = true;
  27506. this._areMiscDirty = true;
  27507. this._areImageProcessingDirty = true;
  27508. this._isDirty = true;
  27509. };
  27510. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27511. this._areImageProcessingDirty = true;
  27512. this._isDirty = true;
  27513. };
  27514. MaterialDefines.prototype.markAsLightDirty = function () {
  27515. this._areLightsDirty = true;
  27516. this._isDirty = true;
  27517. };
  27518. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27519. this._areAttributesDirty = true;
  27520. this._isDirty = true;
  27521. };
  27522. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27523. this._areTexturesDirty = true;
  27524. this._isDirty = true;
  27525. };
  27526. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27527. this._areFresnelDirty = true;
  27528. this._isDirty = true;
  27529. };
  27530. MaterialDefines.prototype.markAsMiscDirty = function () {
  27531. this._areMiscDirty = true;
  27532. this._isDirty = true;
  27533. };
  27534. MaterialDefines.prototype.rebuild = function () {
  27535. if (this._keys) {
  27536. delete this._keys;
  27537. }
  27538. this._keys = [];
  27539. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27540. var key = _a[_i];
  27541. if (key[0] === "_") {
  27542. continue;
  27543. }
  27544. this._keys.push(key);
  27545. }
  27546. };
  27547. MaterialDefines.prototype.isEqual = function (other) {
  27548. if (this._keys.length !== other._keys.length) {
  27549. return false;
  27550. }
  27551. for (var index = 0; index < this._keys.length; index++) {
  27552. var prop = this._keys[index];
  27553. if (this[prop] !== other[prop]) {
  27554. return false;
  27555. }
  27556. }
  27557. return true;
  27558. };
  27559. MaterialDefines.prototype.cloneTo = function (other) {
  27560. if (this._keys.length !== other._keys.length) {
  27561. other._keys = this._keys.slice(0);
  27562. }
  27563. for (var index = 0; index < this._keys.length; index++) {
  27564. var prop = this._keys[index];
  27565. other[prop] = this[prop];
  27566. }
  27567. };
  27568. MaterialDefines.prototype.reset = function () {
  27569. for (var index = 0; index < this._keys.length; index++) {
  27570. var prop = this._keys[index];
  27571. if (typeof (this[prop]) === "number") {
  27572. this[prop] = 0;
  27573. }
  27574. else {
  27575. this[prop] = false;
  27576. }
  27577. }
  27578. };
  27579. MaterialDefines.prototype.toString = function () {
  27580. var result = "";
  27581. for (var index = 0; index < this._keys.length; index++) {
  27582. var prop = this._keys[index];
  27583. var value = this[prop];
  27584. if (typeof (value) === "number") {
  27585. result += "#define " + prop + " " + this[prop] + "\n";
  27586. }
  27587. else if (value) {
  27588. result += "#define " + prop + "\n";
  27589. }
  27590. }
  27591. return result;
  27592. };
  27593. return MaterialDefines;
  27594. }());
  27595. BABYLON.MaterialDefines = MaterialDefines;
  27596. var Material = /** @class */ (function () {
  27597. function Material(name, scene, doNotAdd) {
  27598. this.checkReadyOnEveryCall = false;
  27599. this.checkReadyOnlyOnce = false;
  27600. this.state = "";
  27601. this.alpha = 1.0;
  27602. this._backFaceCulling = true;
  27603. this.doNotSerialize = false;
  27604. this.storeEffectOnSubMeshes = false;
  27605. /**
  27606. * An event triggered when the material is disposed.
  27607. * @type {BABYLON.Observable}
  27608. */
  27609. this.onDisposeObservable = new BABYLON.Observable();
  27610. /**
  27611. * An event triggered when the material is bound.
  27612. * @type {BABYLON.Observable}
  27613. */
  27614. this.onBindObservable = new BABYLON.Observable();
  27615. /**
  27616. * An event triggered when the material is unbound.
  27617. * @type {BABYLON.Observable}
  27618. */
  27619. this.onUnBindObservable = new BABYLON.Observable();
  27620. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27621. this._needDepthPrePass = false;
  27622. this.disableDepthWrite = false;
  27623. this.forceDepthWrite = false;
  27624. this.separateCullingPass = false;
  27625. this._fogEnabled = true;
  27626. this.pointSize = 1.0;
  27627. this.zOffset = 0;
  27628. this._wasPreviouslyReady = false;
  27629. this._fillMode = Material.TriangleFillMode;
  27630. this.name = name;
  27631. this.id = name || BABYLON.Tools.RandomId();
  27632. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27633. if (this._scene.useRightHandedSystem) {
  27634. this.sideOrientation = Material.ClockWiseSideOrientation;
  27635. }
  27636. else {
  27637. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27638. }
  27639. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27640. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27641. if (!doNotAdd) {
  27642. this._scene.materials.push(this);
  27643. }
  27644. }
  27645. Object.defineProperty(Material, "TriangleFillMode", {
  27646. get: function () {
  27647. return Material._TriangleFillMode;
  27648. },
  27649. enumerable: true,
  27650. configurable: true
  27651. });
  27652. Object.defineProperty(Material, "WireFrameFillMode", {
  27653. get: function () {
  27654. return Material._WireFrameFillMode;
  27655. },
  27656. enumerable: true,
  27657. configurable: true
  27658. });
  27659. Object.defineProperty(Material, "PointFillMode", {
  27660. get: function () {
  27661. return Material._PointFillMode;
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27667. get: function () {
  27668. return Material._ClockWiseSideOrientation;
  27669. },
  27670. enumerable: true,
  27671. configurable: true
  27672. });
  27673. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27674. get: function () {
  27675. return Material._CounterClockWiseSideOrientation;
  27676. },
  27677. enumerable: true,
  27678. configurable: true
  27679. });
  27680. Object.defineProperty(Material, "TextureDirtyFlag", {
  27681. get: function () {
  27682. return Material._TextureDirtyFlag;
  27683. },
  27684. enumerable: true,
  27685. configurable: true
  27686. });
  27687. Object.defineProperty(Material, "LightDirtyFlag", {
  27688. get: function () {
  27689. return Material._LightDirtyFlag;
  27690. },
  27691. enumerable: true,
  27692. configurable: true
  27693. });
  27694. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27695. get: function () {
  27696. return Material._FresnelDirtyFlag;
  27697. },
  27698. enumerable: true,
  27699. configurable: true
  27700. });
  27701. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27702. get: function () {
  27703. return Material._AttributesDirtyFlag;
  27704. },
  27705. enumerable: true,
  27706. configurable: true
  27707. });
  27708. Object.defineProperty(Material, "MiscDirtyFlag", {
  27709. get: function () {
  27710. return Material._MiscDirtyFlag;
  27711. },
  27712. enumerable: true,
  27713. configurable: true
  27714. });
  27715. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27716. get: function () {
  27717. return this._backFaceCulling;
  27718. },
  27719. set: function (value) {
  27720. if (this._backFaceCulling === value) {
  27721. return;
  27722. }
  27723. this._backFaceCulling = value;
  27724. this.markAsDirty(Material.TextureDirtyFlag);
  27725. },
  27726. enumerable: true,
  27727. configurable: true
  27728. });
  27729. Object.defineProperty(Material.prototype, "onDispose", {
  27730. set: function (callback) {
  27731. if (this._onDisposeObserver) {
  27732. this.onDisposeObservable.remove(this._onDisposeObserver);
  27733. }
  27734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27735. },
  27736. enumerable: true,
  27737. configurable: true
  27738. });
  27739. Object.defineProperty(Material.prototype, "onBind", {
  27740. set: function (callback) {
  27741. if (this._onBindObserver) {
  27742. this.onBindObservable.remove(this._onBindObserver);
  27743. }
  27744. this._onBindObserver = this.onBindObservable.add(callback);
  27745. },
  27746. enumerable: true,
  27747. configurable: true
  27748. });
  27749. Object.defineProperty(Material.prototype, "alphaMode", {
  27750. get: function () {
  27751. return this._alphaMode;
  27752. },
  27753. set: function (value) {
  27754. if (this._alphaMode === value) {
  27755. return;
  27756. }
  27757. this._alphaMode = value;
  27758. this.markAsDirty(Material.TextureDirtyFlag);
  27759. },
  27760. enumerable: true,
  27761. configurable: true
  27762. });
  27763. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27764. get: function () {
  27765. return this._needDepthPrePass;
  27766. },
  27767. set: function (value) {
  27768. if (this._needDepthPrePass === value) {
  27769. return;
  27770. }
  27771. this._needDepthPrePass = value;
  27772. if (this._needDepthPrePass) {
  27773. this.checkReadyOnEveryCall = true;
  27774. }
  27775. },
  27776. enumerable: true,
  27777. configurable: true
  27778. });
  27779. Object.defineProperty(Material.prototype, "fogEnabled", {
  27780. get: function () {
  27781. return this._fogEnabled;
  27782. },
  27783. set: function (value) {
  27784. if (this._fogEnabled === value) {
  27785. return;
  27786. }
  27787. this._fogEnabled = value;
  27788. this.markAsDirty(Material.MiscDirtyFlag);
  27789. },
  27790. enumerable: true,
  27791. configurable: true
  27792. });
  27793. Object.defineProperty(Material.prototype, "wireframe", {
  27794. get: function () {
  27795. return this._fillMode === Material.WireFrameFillMode;
  27796. },
  27797. set: function (value) {
  27798. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27799. },
  27800. enumerable: true,
  27801. configurable: true
  27802. });
  27803. Object.defineProperty(Material.prototype, "pointsCloud", {
  27804. get: function () {
  27805. return this._fillMode === Material.PointFillMode;
  27806. },
  27807. set: function (value) {
  27808. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27809. },
  27810. enumerable: true,
  27811. configurable: true
  27812. });
  27813. Object.defineProperty(Material.prototype, "fillMode", {
  27814. get: function () {
  27815. return this._fillMode;
  27816. },
  27817. set: function (value) {
  27818. if (this._fillMode === value) {
  27819. return;
  27820. }
  27821. this._fillMode = value;
  27822. this.markAsDirty(Material.MiscDirtyFlag);
  27823. },
  27824. enumerable: true,
  27825. configurable: true
  27826. });
  27827. /**
  27828. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27829. * subclasses should override adding information pertainent to themselves
  27830. */
  27831. Material.prototype.toString = function (fullDetails) {
  27832. var ret = "Name: " + this.name;
  27833. if (fullDetails) {
  27834. }
  27835. return ret;
  27836. };
  27837. /**
  27838. * Child classes can use it to update shaders
  27839. */
  27840. Material.prototype.getClassName = function () {
  27841. return "Material";
  27842. };
  27843. Object.defineProperty(Material.prototype, "isFrozen", {
  27844. get: function () {
  27845. return this.checkReadyOnlyOnce;
  27846. },
  27847. enumerable: true,
  27848. configurable: true
  27849. });
  27850. Material.prototype.freeze = function () {
  27851. this.checkReadyOnlyOnce = true;
  27852. };
  27853. Material.prototype.unfreeze = function () {
  27854. this.checkReadyOnlyOnce = false;
  27855. };
  27856. Material.prototype.isReady = function (mesh, useInstances) {
  27857. return true;
  27858. };
  27859. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27860. return false;
  27861. };
  27862. Material.prototype.getEffect = function () {
  27863. return this._effect;
  27864. };
  27865. Material.prototype.getScene = function () {
  27866. return this._scene;
  27867. };
  27868. Material.prototype.needAlphaBlending = function () {
  27869. return (this.alpha < 1.0);
  27870. };
  27871. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27872. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27873. };
  27874. Material.prototype.needAlphaTesting = function () {
  27875. return false;
  27876. };
  27877. Material.prototype.getAlphaTestTexture = function () {
  27878. return null;
  27879. };
  27880. Material.prototype.markDirty = function () {
  27881. this._wasPreviouslyReady = false;
  27882. };
  27883. Material.prototype._preBind = function (effect, overrideOrientation) {
  27884. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27885. var engine = this._scene.getEngine();
  27886. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27887. var reverse = orientation === Material.ClockWiseSideOrientation;
  27888. engine.enableEffect(effect ? effect : this._effect);
  27889. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27890. return reverse;
  27891. };
  27892. Material.prototype.bind = function (world, mesh) {
  27893. };
  27894. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27895. };
  27896. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27897. };
  27898. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27899. sceneUbo.bindToEffect(effect, "Scene");
  27900. };
  27901. Material.prototype.bindView = function (effect) {
  27902. if (!this._useUBO) {
  27903. effect.setMatrix("view", this.getScene().getViewMatrix());
  27904. }
  27905. else {
  27906. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27907. }
  27908. };
  27909. Material.prototype.bindViewProjection = function (effect) {
  27910. if (!this._useUBO) {
  27911. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27912. }
  27913. else {
  27914. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27915. }
  27916. };
  27917. Material.prototype._afterBind = function (mesh) {
  27918. this._scene._cachedMaterial = this;
  27919. if (mesh) {
  27920. this._scene._cachedVisibility = mesh.visibility;
  27921. }
  27922. else {
  27923. this._scene._cachedVisibility = 1;
  27924. }
  27925. if (mesh) {
  27926. this.onBindObservable.notifyObservers(mesh);
  27927. }
  27928. if (this.disableDepthWrite) {
  27929. var engine = this._scene.getEngine();
  27930. this._cachedDepthWriteState = engine.getDepthWrite();
  27931. engine.setDepthWrite(false);
  27932. }
  27933. };
  27934. Material.prototype.unbind = function () {
  27935. this.onUnBindObservable.notifyObservers(this);
  27936. if (this.disableDepthWrite) {
  27937. var engine = this._scene.getEngine();
  27938. engine.setDepthWrite(this._cachedDepthWriteState);
  27939. }
  27940. };
  27941. Material.prototype.getActiveTextures = function () {
  27942. return [];
  27943. };
  27944. Material.prototype.hasTexture = function (texture) {
  27945. return false;
  27946. };
  27947. Material.prototype.clone = function (name) {
  27948. return null;
  27949. };
  27950. Material.prototype.getBindedMeshes = function () {
  27951. var result = new Array();
  27952. for (var index = 0; index < this._scene.meshes.length; index++) {
  27953. var mesh = this._scene.meshes[index];
  27954. if (mesh.material === this) {
  27955. result.push(mesh);
  27956. }
  27957. }
  27958. return result;
  27959. };
  27960. /**
  27961. * Force shader compilation including textures ready check
  27962. */
  27963. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27964. var _this = this;
  27965. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27966. var subMesh = new BABYLON.BaseSubMesh();
  27967. var scene = this.getScene();
  27968. var engine = scene.getEngine();
  27969. var checkReady = function () {
  27970. if (!_this._scene || !_this._scene.getEngine()) {
  27971. return;
  27972. }
  27973. if (subMesh._materialDefines) {
  27974. subMesh._materialDefines._renderId = -1;
  27975. }
  27976. var alphaTestState = engine.getAlphaTesting();
  27977. var clipPlaneState = scene.clipPlane;
  27978. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27979. if (localOptions.clipPlane) {
  27980. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27981. }
  27982. if (_this.storeEffectOnSubMeshes) {
  27983. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27984. if (onCompiled) {
  27985. onCompiled(_this);
  27986. }
  27987. }
  27988. else {
  27989. setTimeout(checkReady, 16);
  27990. }
  27991. }
  27992. else {
  27993. if (_this.isReady(mesh)) {
  27994. if (onCompiled) {
  27995. onCompiled(_this);
  27996. }
  27997. }
  27998. else {
  27999. setTimeout(checkReady, 16);
  28000. }
  28001. }
  28002. engine.setAlphaTesting(alphaTestState);
  28003. if (options && options.clipPlane) {
  28004. scene.clipPlane = clipPlaneState;
  28005. }
  28006. };
  28007. checkReady();
  28008. };
  28009. Material.prototype.markAsDirty = function (flag) {
  28010. if (flag & Material.TextureDirtyFlag) {
  28011. this._markAllSubMeshesAsTexturesDirty();
  28012. }
  28013. if (flag & Material.LightDirtyFlag) {
  28014. this._markAllSubMeshesAsLightsDirty();
  28015. }
  28016. if (flag & Material.FresnelDirtyFlag) {
  28017. this._markAllSubMeshesAsFresnelDirty();
  28018. }
  28019. if (flag & Material.AttributesDirtyFlag) {
  28020. this._markAllSubMeshesAsAttributesDirty();
  28021. }
  28022. if (flag & Material.MiscDirtyFlag) {
  28023. this._markAllSubMeshesAsMiscDirty();
  28024. }
  28025. this.getScene().resetCachedMaterial();
  28026. };
  28027. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28028. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28029. var mesh = _a[_i];
  28030. if (!mesh.subMeshes) {
  28031. continue;
  28032. }
  28033. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28034. var subMesh = _c[_b];
  28035. if (subMesh.getMaterial() !== this) {
  28036. continue;
  28037. }
  28038. if (!subMesh._materialDefines) {
  28039. continue;
  28040. }
  28041. func(subMesh._materialDefines);
  28042. }
  28043. }
  28044. };
  28045. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28046. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28047. };
  28048. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28049. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28050. };
  28051. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28052. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28053. };
  28054. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28055. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28056. };
  28057. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28058. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28059. };
  28060. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28061. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28062. };
  28063. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28064. // Animations
  28065. this.getScene().stopAnimation(this);
  28066. // Remove from scene
  28067. var index = this._scene.materials.indexOf(this);
  28068. if (index >= 0) {
  28069. this._scene.materials.splice(index, 1);
  28070. }
  28071. // Remove from meshes
  28072. for (index = 0; index < this._scene.meshes.length; index++) {
  28073. var mesh = this._scene.meshes[index];
  28074. if (mesh.material === this) {
  28075. mesh.material = null;
  28076. if (mesh.geometry) {
  28077. var geometry = (mesh.geometry);
  28078. if (this.storeEffectOnSubMeshes) {
  28079. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28080. var subMesh = _a[_i];
  28081. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28082. if (forceDisposeEffect && subMesh._materialEffect) {
  28083. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28084. }
  28085. }
  28086. }
  28087. else {
  28088. geometry._releaseVertexArrayObject(this._effect);
  28089. }
  28090. }
  28091. }
  28092. }
  28093. this._uniformBuffer.dispose();
  28094. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28095. if (forceDisposeEffect && this._effect) {
  28096. if (!this.storeEffectOnSubMeshes) {
  28097. this._scene.getEngine()._releaseEffect(this._effect);
  28098. }
  28099. this._effect = null;
  28100. }
  28101. // Callback
  28102. this.onDisposeObservable.notifyObservers(this);
  28103. this.onDisposeObservable.clear();
  28104. this.onBindObservable.clear();
  28105. this.onUnBindObservable.clear();
  28106. };
  28107. Material.prototype.serialize = function () {
  28108. return BABYLON.SerializationHelper.Serialize(this);
  28109. };
  28110. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28111. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28112. multiMaterial.id = parsedMultiMaterial.id;
  28113. if (BABYLON.Tags) {
  28114. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28115. }
  28116. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28117. var subMatId = parsedMultiMaterial.materials[matIndex];
  28118. if (subMatId) {
  28119. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28120. }
  28121. else {
  28122. multiMaterial.subMaterials.push(null);
  28123. }
  28124. }
  28125. return multiMaterial;
  28126. };
  28127. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28128. if (!parsedMaterial.customType) {
  28129. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28130. }
  28131. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28132. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28133. if (!BABYLON.LegacyPBRMaterial) {
  28134. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28135. return;
  28136. }
  28137. }
  28138. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28139. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28140. ;
  28141. };
  28142. Material._TriangleFillMode = 0;
  28143. Material._WireFrameFillMode = 1;
  28144. Material._PointFillMode = 2;
  28145. Material._ClockWiseSideOrientation = 0;
  28146. Material._CounterClockWiseSideOrientation = 1;
  28147. Material._TextureDirtyFlag = 1;
  28148. Material._LightDirtyFlag = 2;
  28149. Material._FresnelDirtyFlag = 4;
  28150. Material._AttributesDirtyFlag = 8;
  28151. Material._MiscDirtyFlag = 16;
  28152. __decorate([
  28153. BABYLON.serialize()
  28154. ], Material.prototype, "id", void 0);
  28155. __decorate([
  28156. BABYLON.serialize()
  28157. ], Material.prototype, "name", void 0);
  28158. __decorate([
  28159. BABYLON.serialize()
  28160. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28161. __decorate([
  28162. BABYLON.serialize()
  28163. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28164. __decorate([
  28165. BABYLON.serialize()
  28166. ], Material.prototype, "state", void 0);
  28167. __decorate([
  28168. BABYLON.serialize()
  28169. ], Material.prototype, "alpha", void 0);
  28170. __decorate([
  28171. BABYLON.serialize("backFaceCulling")
  28172. ], Material.prototype, "_backFaceCulling", void 0);
  28173. __decorate([
  28174. BABYLON.serialize()
  28175. ], Material.prototype, "sideOrientation", void 0);
  28176. __decorate([
  28177. BABYLON.serialize("alphaMode")
  28178. ], Material.prototype, "_alphaMode", void 0);
  28179. __decorate([
  28180. BABYLON.serialize()
  28181. ], Material.prototype, "_needDepthPrePass", void 0);
  28182. __decorate([
  28183. BABYLON.serialize()
  28184. ], Material.prototype, "disableDepthWrite", void 0);
  28185. __decorate([
  28186. BABYLON.serialize()
  28187. ], Material.prototype, "forceDepthWrite", void 0);
  28188. __decorate([
  28189. BABYLON.serialize()
  28190. ], Material.prototype, "separateCullingPass", void 0);
  28191. __decorate([
  28192. BABYLON.serialize("fogEnabled")
  28193. ], Material.prototype, "_fogEnabled", void 0);
  28194. __decorate([
  28195. BABYLON.serialize()
  28196. ], Material.prototype, "pointSize", void 0);
  28197. __decorate([
  28198. BABYLON.serialize()
  28199. ], Material.prototype, "zOffset", void 0);
  28200. __decorate([
  28201. BABYLON.serialize()
  28202. ], Material.prototype, "wireframe", null);
  28203. __decorate([
  28204. BABYLON.serialize()
  28205. ], Material.prototype, "pointsCloud", null);
  28206. __decorate([
  28207. BABYLON.serialize()
  28208. ], Material.prototype, "fillMode", null);
  28209. return Material;
  28210. }());
  28211. BABYLON.Material = Material;
  28212. })(BABYLON || (BABYLON = {}));
  28213. //# sourceMappingURL=babylon.material.js.map
  28214. var BABYLON;
  28215. (function (BABYLON) {
  28216. var UniformBuffer = /** @class */ (function () {
  28217. /**
  28218. * Uniform buffer objects.
  28219. *
  28220. * Handles blocks of uniform on the GPU.
  28221. *
  28222. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28223. *
  28224. * For more information, please refer to :
  28225. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28226. */
  28227. function UniformBuffer(engine, data, dynamic) {
  28228. this._engine = engine;
  28229. this._noUBO = !engine.supportsUniformBuffers;
  28230. this._dynamic = dynamic;
  28231. this._data = data || [];
  28232. this._uniformLocations = {};
  28233. this._uniformSizes = {};
  28234. this._uniformLocationPointer = 0;
  28235. this._needSync = false;
  28236. if (this._noUBO) {
  28237. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28238. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28239. this.updateFloat = this._updateFloatForEffect;
  28240. this.updateFloat2 = this._updateFloat2ForEffect;
  28241. this.updateFloat3 = this._updateFloat3ForEffect;
  28242. this.updateFloat4 = this._updateFloat4ForEffect;
  28243. this.updateMatrix = this._updateMatrixForEffect;
  28244. this.updateVector3 = this._updateVector3ForEffect;
  28245. this.updateVector4 = this._updateVector4ForEffect;
  28246. this.updateColor3 = this._updateColor3ForEffect;
  28247. this.updateColor4 = this._updateColor4ForEffect;
  28248. }
  28249. else {
  28250. this._engine._uniformBuffers.push(this);
  28251. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28252. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28253. this.updateFloat = this._updateFloatForUniform;
  28254. this.updateFloat2 = this._updateFloat2ForUniform;
  28255. this.updateFloat3 = this._updateFloat3ForUniform;
  28256. this.updateFloat4 = this._updateFloat4ForUniform;
  28257. this.updateMatrix = this._updateMatrixForUniform;
  28258. this.updateVector3 = this._updateVector3ForUniform;
  28259. this.updateVector4 = this._updateVector4ForUniform;
  28260. this.updateColor3 = this._updateColor3ForUniform;
  28261. this.updateColor4 = this._updateColor4ForUniform;
  28262. }
  28263. }
  28264. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28265. // Properties
  28266. /**
  28267. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28268. * or just falling back on setUniformXXX calls.
  28269. */
  28270. get: function () {
  28271. return !this._noUBO;
  28272. },
  28273. enumerable: true,
  28274. configurable: true
  28275. });
  28276. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28277. /**
  28278. * Indicates if the WebGL underlying uniform buffer is in sync
  28279. * with the javascript cache data.
  28280. */
  28281. get: function () {
  28282. return !this._needSync;
  28283. },
  28284. enumerable: true,
  28285. configurable: true
  28286. });
  28287. /**
  28288. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28289. * Also, a dynamic UniformBuffer will disable cache verification and always
  28290. * update the underlying WebGL uniform buffer to the GPU.
  28291. */
  28292. UniformBuffer.prototype.isDynamic = function () {
  28293. return this._dynamic !== undefined;
  28294. };
  28295. /**
  28296. * The data cache on JS side.
  28297. */
  28298. UniformBuffer.prototype.getData = function () {
  28299. return this._bufferData;
  28300. };
  28301. /**
  28302. * The underlying WebGL Uniform buffer.
  28303. */
  28304. UniformBuffer.prototype.getBuffer = function () {
  28305. return this._buffer;
  28306. };
  28307. /**
  28308. * std140 layout specifies how to align data within an UBO structure.
  28309. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28310. * for specs.
  28311. */
  28312. UniformBuffer.prototype._fillAlignment = function (size) {
  28313. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28314. // and 4x4 matrices
  28315. // TODO : change if other types are used
  28316. var alignment;
  28317. if (size <= 2) {
  28318. alignment = size;
  28319. }
  28320. else {
  28321. alignment = 4;
  28322. }
  28323. if ((this._uniformLocationPointer % alignment) !== 0) {
  28324. var oldPointer = this._uniformLocationPointer;
  28325. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28326. var diff = this._uniformLocationPointer - oldPointer;
  28327. for (var i = 0; i < diff; i++) {
  28328. this._data.push(0);
  28329. }
  28330. }
  28331. };
  28332. /**
  28333. * Adds an uniform in the buffer.
  28334. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28335. * for the layout to be correct !
  28336. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28337. * @param {number|number[]} size Data size, or data directly.
  28338. */
  28339. UniformBuffer.prototype.addUniform = function (name, size) {
  28340. if (this._noUBO) {
  28341. return;
  28342. }
  28343. if (this._uniformLocations[name] !== undefined) {
  28344. // Already existing uniform
  28345. return;
  28346. }
  28347. // This function must be called in the order of the shader layout !
  28348. // size can be the size of the uniform, or data directly
  28349. var data;
  28350. if (size instanceof Array) {
  28351. data = size;
  28352. size = data.length;
  28353. }
  28354. else {
  28355. size = size;
  28356. data = [];
  28357. // Fill with zeros
  28358. for (var i = 0; i < size; i++) {
  28359. data.push(0);
  28360. }
  28361. }
  28362. this._fillAlignment(size);
  28363. this._uniformSizes[name] = size;
  28364. this._uniformLocations[name] = this._uniformLocationPointer;
  28365. this._uniformLocationPointer += size;
  28366. for (var i = 0; i < size; i++) {
  28367. this._data.push(data[i]);
  28368. }
  28369. this._needSync = true;
  28370. };
  28371. /**
  28372. * Wrapper for addUniform.
  28373. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28374. * @param {Matrix} mat A 4x4 matrix.
  28375. */
  28376. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28377. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28378. };
  28379. /**
  28380. * Wrapper for addUniform.
  28381. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28382. * @param {number} x
  28383. * @param {number} y
  28384. */
  28385. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28386. var temp = [x, y];
  28387. this.addUniform(name, temp);
  28388. };
  28389. /**
  28390. * Wrapper for addUniform.
  28391. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28392. * @param {number} x
  28393. * @param {number} y
  28394. * @param {number} z
  28395. */
  28396. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28397. var temp = [x, y, z];
  28398. this.addUniform(name, temp);
  28399. };
  28400. /**
  28401. * Wrapper for addUniform.
  28402. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28403. * @param {Color3} color
  28404. */
  28405. UniformBuffer.prototype.addColor3 = function (name, color) {
  28406. var temp = new Array();
  28407. color.toArray(temp);
  28408. this.addUniform(name, temp);
  28409. };
  28410. /**
  28411. * Wrapper for addUniform.
  28412. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28413. * @param {Color3} color
  28414. * @param {number} alpha
  28415. */
  28416. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28417. var temp = new Array();
  28418. color.toArray(temp);
  28419. temp.push(alpha);
  28420. this.addUniform(name, temp);
  28421. };
  28422. /**
  28423. * Wrapper for addUniform.
  28424. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28425. * @param {Vector3} vector
  28426. */
  28427. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28428. var temp = new Array();
  28429. vector.toArray(temp);
  28430. this.addUniform(name, temp);
  28431. };
  28432. /**
  28433. * Wrapper for addUniform.
  28434. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28435. */
  28436. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28437. this.addUniform(name, 12);
  28438. };
  28439. /**
  28440. * Wrapper for addUniform.
  28441. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28442. */
  28443. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28444. this.addUniform(name, 8);
  28445. };
  28446. /**
  28447. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28448. */
  28449. UniformBuffer.prototype.create = function () {
  28450. if (this._noUBO) {
  28451. return;
  28452. }
  28453. if (this._buffer) {
  28454. return; // nothing to do
  28455. }
  28456. // See spec, alignment must be filled as a vec4
  28457. this._fillAlignment(4);
  28458. this._bufferData = new Float32Array(this._data);
  28459. this._rebuild();
  28460. this._needSync = true;
  28461. };
  28462. UniformBuffer.prototype._rebuild = function () {
  28463. if (this._noUBO) {
  28464. return;
  28465. }
  28466. if (this._dynamic) {
  28467. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28468. }
  28469. else {
  28470. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28471. }
  28472. };
  28473. /**
  28474. * Updates the WebGL Uniform Buffer on the GPU.
  28475. * If the `dynamic` flag is set to true, no cache comparison is done.
  28476. * Otherwise, the buffer will be updated only if the cache differs.
  28477. */
  28478. UniformBuffer.prototype.update = function () {
  28479. if (!this._buffer) {
  28480. this.create();
  28481. return;
  28482. }
  28483. if (!this._dynamic && !this._needSync) {
  28484. return;
  28485. }
  28486. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28487. this._needSync = false;
  28488. };
  28489. /**
  28490. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28491. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28492. * @param {number[]|Float32Array} data Flattened data
  28493. * @param {number} size Size of the data.
  28494. */
  28495. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28496. var location = this._uniformLocations[uniformName];
  28497. if (location === undefined) {
  28498. if (this._buffer) {
  28499. // Cannot add an uniform if the buffer is already created
  28500. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28501. return;
  28502. }
  28503. this.addUniform(uniformName, size);
  28504. location = this._uniformLocations[uniformName];
  28505. }
  28506. if (!this._buffer) {
  28507. this.create();
  28508. }
  28509. if (!this._dynamic) {
  28510. // Cache for static uniform buffers
  28511. var changed = false;
  28512. for (var i = 0; i < size; i++) {
  28513. if (this._bufferData[location + i] !== data[i]) {
  28514. changed = true;
  28515. this._bufferData[location + i] = data[i];
  28516. }
  28517. }
  28518. this._needSync = this._needSync || changed;
  28519. }
  28520. else {
  28521. // No cache for dynamic
  28522. for (var i = 0; i < size; i++) {
  28523. this._bufferData[location + i] = data[i];
  28524. }
  28525. }
  28526. };
  28527. // Update methods
  28528. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28529. // To match std140, matrix must be realigned
  28530. for (var i = 0; i < 3; i++) {
  28531. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28532. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28533. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28534. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28535. }
  28536. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28537. };
  28538. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28539. this._currentEffect.setMatrix3x3(name, matrix);
  28540. };
  28541. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28542. this._currentEffect.setMatrix2x2(name, matrix);
  28543. };
  28544. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28545. // To match std140, matrix must be realigned
  28546. for (var i = 0; i < 2; i++) {
  28547. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28548. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28549. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28550. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28551. }
  28552. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28553. };
  28554. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28555. this._currentEffect.setFloat(name, x);
  28556. };
  28557. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28558. UniformBuffer._tempBuffer[0] = x;
  28559. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28560. };
  28561. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28562. if (suffix === void 0) { suffix = ""; }
  28563. this._currentEffect.setFloat2(name + suffix, x, y);
  28564. };
  28565. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28566. if (suffix === void 0) { suffix = ""; }
  28567. UniformBuffer._tempBuffer[0] = x;
  28568. UniformBuffer._tempBuffer[1] = y;
  28569. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28570. };
  28571. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28572. if (suffix === void 0) { suffix = ""; }
  28573. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28574. };
  28575. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28576. if (suffix === void 0) { suffix = ""; }
  28577. UniformBuffer._tempBuffer[0] = x;
  28578. UniformBuffer._tempBuffer[1] = y;
  28579. UniformBuffer._tempBuffer[2] = z;
  28580. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28581. };
  28582. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28583. if (suffix === void 0) { suffix = ""; }
  28584. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28585. };
  28586. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28587. if (suffix === void 0) { suffix = ""; }
  28588. UniformBuffer._tempBuffer[0] = x;
  28589. UniformBuffer._tempBuffer[1] = y;
  28590. UniformBuffer._tempBuffer[2] = z;
  28591. UniformBuffer._tempBuffer[3] = w;
  28592. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28593. };
  28594. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28595. this._currentEffect.setMatrix(name, mat);
  28596. };
  28597. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28598. this.updateUniform(name, mat.toArray(), 16);
  28599. };
  28600. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28601. this._currentEffect.setVector3(name, vector);
  28602. };
  28603. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28604. vector.toArray(UniformBuffer._tempBuffer);
  28605. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28606. };
  28607. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28608. this._currentEffect.setVector4(name, vector);
  28609. };
  28610. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28611. vector.toArray(UniformBuffer._tempBuffer);
  28612. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28613. };
  28614. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28615. if (suffix === void 0) { suffix = ""; }
  28616. this._currentEffect.setColor3(name + suffix, color);
  28617. };
  28618. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28619. if (suffix === void 0) { suffix = ""; }
  28620. color.toArray(UniformBuffer._tempBuffer);
  28621. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28622. };
  28623. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28624. if (suffix === void 0) { suffix = ""; }
  28625. this._currentEffect.setColor4(name + suffix, color, alpha);
  28626. };
  28627. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28628. if (suffix === void 0) { suffix = ""; }
  28629. color.toArray(UniformBuffer._tempBuffer);
  28630. UniformBuffer._tempBuffer[3] = alpha;
  28631. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28632. };
  28633. /**
  28634. * Sets a sampler uniform on the effect.
  28635. * @param {string} name Name of the sampler.
  28636. * @param {Texture} texture
  28637. */
  28638. UniformBuffer.prototype.setTexture = function (name, texture) {
  28639. this._currentEffect.setTexture(name, texture);
  28640. };
  28641. /**
  28642. * Directly updates the value of the uniform in the cache AND on the GPU.
  28643. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28644. * @param {number[]|Float32Array} data Flattened data
  28645. */
  28646. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28647. this.updateUniform(uniformName, data, data.length);
  28648. this.update();
  28649. };
  28650. /**
  28651. * Binds this uniform buffer to an effect.
  28652. * @param {Effect} effect
  28653. * @param {string} name Name of the uniform block in the shader.
  28654. */
  28655. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28656. this._currentEffect = effect;
  28657. if (this._noUBO || !this._buffer) {
  28658. return;
  28659. }
  28660. effect.bindUniformBuffer(this._buffer, name);
  28661. };
  28662. /**
  28663. * Disposes the uniform buffer.
  28664. */
  28665. UniformBuffer.prototype.dispose = function () {
  28666. if (this._noUBO) {
  28667. return;
  28668. }
  28669. var index = this._engine._uniformBuffers.indexOf(this);
  28670. if (index !== -1) {
  28671. this._engine._uniformBuffers.splice(index, 1);
  28672. }
  28673. if (!this._buffer) {
  28674. return;
  28675. }
  28676. if (this._engine._releaseBuffer(this._buffer)) {
  28677. this._buffer = null;
  28678. }
  28679. };
  28680. // Pool for avoiding memory leaks
  28681. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28682. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28683. return UniformBuffer;
  28684. }());
  28685. BABYLON.UniformBuffer = UniformBuffer;
  28686. })(BABYLON || (BABYLON = {}));
  28687. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28688. var BABYLON;
  28689. (function (BABYLON) {
  28690. var PushMaterial = /** @class */ (function (_super) {
  28691. __extends(PushMaterial, _super);
  28692. function PushMaterial(name, scene) {
  28693. var _this = _super.call(this, name, scene) || this;
  28694. _this.storeEffectOnSubMeshes = true;
  28695. return _this;
  28696. }
  28697. PushMaterial.prototype.getEffect = function () {
  28698. return this._activeEffect;
  28699. };
  28700. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28701. if (!mesh) {
  28702. return false;
  28703. }
  28704. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28705. return true;
  28706. }
  28707. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28708. };
  28709. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28710. this._activeEffect.setMatrix("world", world);
  28711. };
  28712. PushMaterial.prototype.bind = function (world, mesh) {
  28713. if (!mesh) {
  28714. return;
  28715. }
  28716. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28717. };
  28718. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28719. if (effect === void 0) { effect = null; }
  28720. _super.prototype._afterBind.call(this, mesh);
  28721. this.getScene()._cachedEffect = effect;
  28722. };
  28723. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28724. if (visibility === void 0) { visibility = 1; }
  28725. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28726. };
  28727. return PushMaterial;
  28728. }(BABYLON.Material));
  28729. BABYLON.PushMaterial = PushMaterial;
  28730. })(BABYLON || (BABYLON = {}));
  28731. //# sourceMappingURL=babylon.pushMaterial.js.map
  28732. var BABYLON;
  28733. (function (BABYLON) {
  28734. var VertexData = /** @class */ (function () {
  28735. function VertexData() {
  28736. }
  28737. VertexData.prototype.set = function (data, kind) {
  28738. switch (kind) {
  28739. case BABYLON.VertexBuffer.PositionKind:
  28740. this.positions = data;
  28741. break;
  28742. case BABYLON.VertexBuffer.NormalKind:
  28743. this.normals = data;
  28744. break;
  28745. case BABYLON.VertexBuffer.TangentKind:
  28746. this.tangents = data;
  28747. break;
  28748. case BABYLON.VertexBuffer.UVKind:
  28749. this.uvs = data;
  28750. break;
  28751. case BABYLON.VertexBuffer.UV2Kind:
  28752. this.uvs2 = data;
  28753. break;
  28754. case BABYLON.VertexBuffer.UV3Kind:
  28755. this.uvs3 = data;
  28756. break;
  28757. case BABYLON.VertexBuffer.UV4Kind:
  28758. this.uvs4 = data;
  28759. break;
  28760. case BABYLON.VertexBuffer.UV5Kind:
  28761. this.uvs5 = data;
  28762. break;
  28763. case BABYLON.VertexBuffer.UV6Kind:
  28764. this.uvs6 = data;
  28765. break;
  28766. case BABYLON.VertexBuffer.ColorKind:
  28767. this.colors = data;
  28768. break;
  28769. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28770. this.matricesIndices = data;
  28771. break;
  28772. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28773. this.matricesWeights = data;
  28774. break;
  28775. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28776. this.matricesIndicesExtra = data;
  28777. break;
  28778. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28779. this.matricesWeightsExtra = data;
  28780. break;
  28781. }
  28782. };
  28783. /**
  28784. * Associates the vertexData to the passed Mesh.
  28785. * Sets it as updatable or not (default `false`).
  28786. * Returns the VertexData.
  28787. */
  28788. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28789. this._applyTo(mesh, updatable);
  28790. return this;
  28791. };
  28792. /**
  28793. * Associates the vertexData to the passed Geometry.
  28794. * Sets it as updatable or not (default `false`).
  28795. * Returns the VertexData.
  28796. */
  28797. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28798. this._applyTo(geometry, updatable);
  28799. return this;
  28800. };
  28801. /**
  28802. * Updates the associated mesh.
  28803. * Returns the VertexData.
  28804. */
  28805. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28806. this._update(mesh);
  28807. return this;
  28808. };
  28809. /**
  28810. * Updates the associated geometry.
  28811. * Returns the VertexData.
  28812. */
  28813. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28814. this._update(geometry);
  28815. return this;
  28816. };
  28817. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28818. if (updatable === void 0) { updatable = false; }
  28819. if (this.positions) {
  28820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28821. }
  28822. if (this.normals) {
  28823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28824. }
  28825. if (this.tangents) {
  28826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28827. }
  28828. if (this.uvs) {
  28829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28830. }
  28831. if (this.uvs2) {
  28832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28833. }
  28834. if (this.uvs3) {
  28835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28836. }
  28837. if (this.uvs4) {
  28838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28839. }
  28840. if (this.uvs5) {
  28841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28842. }
  28843. if (this.uvs6) {
  28844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28845. }
  28846. if (this.colors) {
  28847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28848. }
  28849. if (this.matricesIndices) {
  28850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28851. }
  28852. if (this.matricesWeights) {
  28853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28854. }
  28855. if (this.matricesIndicesExtra) {
  28856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28857. }
  28858. if (this.matricesWeightsExtra) {
  28859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28860. }
  28861. if (this.indices) {
  28862. meshOrGeometry.setIndices(this.indices, null, updatable);
  28863. }
  28864. return this;
  28865. };
  28866. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28867. if (this.positions) {
  28868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28869. }
  28870. if (this.normals) {
  28871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28872. }
  28873. if (this.tangents) {
  28874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28875. }
  28876. if (this.uvs) {
  28877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28878. }
  28879. if (this.uvs2) {
  28880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28881. }
  28882. if (this.uvs3) {
  28883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28884. }
  28885. if (this.uvs4) {
  28886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28887. }
  28888. if (this.uvs5) {
  28889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28890. }
  28891. if (this.uvs6) {
  28892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28893. }
  28894. if (this.colors) {
  28895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28896. }
  28897. if (this.matricesIndices) {
  28898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28899. }
  28900. if (this.matricesWeights) {
  28901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28902. }
  28903. if (this.matricesIndicesExtra) {
  28904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28905. }
  28906. if (this.matricesWeightsExtra) {
  28907. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28908. }
  28909. if (this.indices) {
  28910. meshOrGeometry.setIndices(this.indices, null);
  28911. }
  28912. return this;
  28913. };
  28914. /**
  28915. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28916. * Returns the VertexData.
  28917. */
  28918. VertexData.prototype.transform = function (matrix) {
  28919. var transformed = BABYLON.Vector3.Zero();
  28920. var index;
  28921. if (this.positions) {
  28922. var position = BABYLON.Vector3.Zero();
  28923. for (index = 0; index < this.positions.length; index += 3) {
  28924. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28925. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28926. this.positions[index] = transformed.x;
  28927. this.positions[index + 1] = transformed.y;
  28928. this.positions[index + 2] = transformed.z;
  28929. }
  28930. }
  28931. if (this.normals) {
  28932. var normal = BABYLON.Vector3.Zero();
  28933. for (index = 0; index < this.normals.length; index += 3) {
  28934. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28935. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28936. this.normals[index] = transformed.x;
  28937. this.normals[index + 1] = transformed.y;
  28938. this.normals[index + 2] = transformed.z;
  28939. }
  28940. }
  28941. if (this.tangents) {
  28942. var tangent = BABYLON.Vector4.Zero();
  28943. var tangentTransformed = BABYLON.Vector4.Zero();
  28944. for (index = 0; index < this.tangents.length; index += 4) {
  28945. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28946. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28947. this.tangents[index] = tangentTransformed.x;
  28948. this.tangents[index + 1] = tangentTransformed.y;
  28949. this.tangents[index + 2] = tangentTransformed.z;
  28950. this.tangents[index + 3] = tangentTransformed.w;
  28951. }
  28952. }
  28953. return this;
  28954. };
  28955. /**
  28956. * Merges the passed VertexData into the current one.
  28957. * Returns the modified VertexData.
  28958. */
  28959. VertexData.prototype.merge = function (other, options) {
  28960. options = options || {};
  28961. if (other.indices) {
  28962. if (!this.indices) {
  28963. this.indices = [];
  28964. }
  28965. var offset = this.positions ? this.positions.length / 3 : 0;
  28966. for (var index = 0; index < other.indices.length; index++) {
  28967. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28968. this.indices.push(other.indices[index] + offset);
  28969. }
  28970. }
  28971. this.positions = this._mergeElement(this.positions, other.positions);
  28972. if (!this.positions) {
  28973. return this;
  28974. }
  28975. var count = this.positions.length / 3;
  28976. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28977. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28978. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28979. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28980. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28981. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28982. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28983. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28984. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28985. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28986. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28987. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28988. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28989. return this;
  28990. };
  28991. VertexData.prototype._mergeElement = function (source, other, length) {
  28992. if (length === void 0) { length = 0; }
  28993. if (!other && !source) {
  28994. return null;
  28995. }
  28996. if (!other) {
  28997. return this._mergeElement(source, new Float32Array(source.length), length);
  28998. }
  28999. if (!source) {
  29000. if (length === 0 || length === other.length) {
  29001. return other;
  29002. }
  29003. return this._mergeElement(new Float32Array(length - other.length), other, length);
  29004. }
  29005. var len = other.length + source.length;
  29006. var isSrcTypedArray = source instanceof Float32Array;
  29007. var isOthTypedArray = other instanceof Float32Array;
  29008. // use non-loop method when the source is Float32Array
  29009. if (isSrcTypedArray) {
  29010. var ret32 = new Float32Array(len);
  29011. ret32.set(source);
  29012. ret32.set(other, source.length);
  29013. return ret32;
  29014. // source is number[], when other is also use concat
  29015. }
  29016. else if (!isOthTypedArray) {
  29017. return source.concat(other);
  29018. // source is a number[], but other is a Float32Array, loop required
  29019. }
  29020. else {
  29021. var ret = source.slice(0); // copy source to a separate array
  29022. for (var i = 0, len = other.length; i < len; i++) {
  29023. ret.push(other[i]);
  29024. }
  29025. return ret;
  29026. }
  29027. };
  29028. /**
  29029. * Serializes the VertexData.
  29030. * Returns a serialized object.
  29031. */
  29032. VertexData.prototype.serialize = function () {
  29033. var serializationObject = this.serialize();
  29034. if (this.positions) {
  29035. serializationObject.positions = this.positions;
  29036. }
  29037. if (this.normals) {
  29038. serializationObject.normals = this.normals;
  29039. }
  29040. if (this.tangents) {
  29041. serializationObject.tangents = this.tangents;
  29042. }
  29043. if (this.uvs) {
  29044. serializationObject.uvs = this.uvs;
  29045. }
  29046. if (this.uvs2) {
  29047. serializationObject.uvs2 = this.uvs2;
  29048. }
  29049. if (this.uvs3) {
  29050. serializationObject.uvs3 = this.uvs3;
  29051. }
  29052. if (this.uvs4) {
  29053. serializationObject.uvs4 = this.uvs4;
  29054. }
  29055. if (this.uvs5) {
  29056. serializationObject.uvs5 = this.uvs5;
  29057. }
  29058. if (this.uvs6) {
  29059. serializationObject.uvs6 = this.uvs6;
  29060. }
  29061. if (this.colors) {
  29062. serializationObject.colors = this.colors;
  29063. }
  29064. if (this.matricesIndices) {
  29065. serializationObject.matricesIndices = this.matricesIndices;
  29066. serializationObject.matricesIndices._isExpanded = true;
  29067. }
  29068. if (this.matricesWeights) {
  29069. serializationObject.matricesWeights = this.matricesWeights;
  29070. }
  29071. if (this.matricesIndicesExtra) {
  29072. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29073. serializationObject.matricesIndicesExtra._isExpanded = true;
  29074. }
  29075. if (this.matricesWeightsExtra) {
  29076. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29077. }
  29078. serializationObject.indices = this.indices;
  29079. return serializationObject;
  29080. };
  29081. // Statics
  29082. /**
  29083. * Returns the object VertexData associated to the passed mesh.
  29084. */
  29085. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29086. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29087. };
  29088. /**
  29089. * Returns the object VertexData associated to the passed geometry.
  29090. */
  29091. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29092. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29093. };
  29094. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29095. var result = new VertexData();
  29096. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29097. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29098. }
  29099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29100. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29101. }
  29102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29103. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29104. }
  29105. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29106. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29107. }
  29108. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29109. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29110. }
  29111. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29112. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29113. }
  29114. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29115. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29116. }
  29117. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29118. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29119. }
  29120. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29121. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29122. }
  29123. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29124. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29125. }
  29126. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29127. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29128. }
  29129. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29130. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29131. }
  29132. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29133. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29134. }
  29135. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29136. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29137. }
  29138. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29139. return result;
  29140. };
  29141. /**
  29142. * Creates the vertexData of the Ribbon.
  29143. */
  29144. VertexData.CreateRibbon = function (options) {
  29145. var pathArray = options.pathArray;
  29146. var closeArray = options.closeArray || false;
  29147. var closePath = options.closePath || false;
  29148. var invertUV = options.invertUV || false;
  29149. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29150. var offset = options.offset || defaultOffset;
  29151. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29152. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29153. var customUV = options.uvs;
  29154. var customColors = options.colors;
  29155. var positions = [];
  29156. var indices = [];
  29157. var normals = [];
  29158. var uvs = [];
  29159. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29160. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29161. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29162. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29163. var minlg; // minimal length among all paths from pathArray
  29164. var lg = []; // array of path lengths : nb of vertex per path
  29165. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29166. var p; // path iterator
  29167. var i; // point iterator
  29168. var j; // point iterator
  29169. // if single path in pathArray
  29170. if (pathArray.length < 2) {
  29171. var ar1 = [];
  29172. var ar2 = [];
  29173. for (i = 0; i < pathArray[0].length - offset; i++) {
  29174. ar1.push(pathArray[0][i]);
  29175. ar2.push(pathArray[0][i + offset]);
  29176. }
  29177. pathArray = [ar1, ar2];
  29178. }
  29179. // positions and horizontal distances (u)
  29180. var idc = 0;
  29181. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29182. var path;
  29183. var l;
  29184. minlg = pathArray[0].length;
  29185. var vectlg;
  29186. var dist;
  29187. for (p = 0; p < pathArray.length; p++) {
  29188. uTotalDistance[p] = 0;
  29189. us[p] = [0];
  29190. path = pathArray[p];
  29191. l = path.length;
  29192. minlg = (minlg < l) ? minlg : l;
  29193. j = 0;
  29194. while (j < l) {
  29195. positions.push(path[j].x, path[j].y, path[j].z);
  29196. if (j > 0) {
  29197. vectlg = path[j].subtract(path[j - 1]).length();
  29198. dist = vectlg + uTotalDistance[p];
  29199. us[p].push(dist);
  29200. uTotalDistance[p] = dist;
  29201. }
  29202. j++;
  29203. }
  29204. if (closePath) {
  29205. j--;
  29206. positions.push(path[0].x, path[0].y, path[0].z);
  29207. vectlg = path[j].subtract(path[0]).length();
  29208. dist = vectlg + uTotalDistance[p];
  29209. us[p].push(dist);
  29210. uTotalDistance[p] = dist;
  29211. }
  29212. lg[p] = l + closePathCorr;
  29213. idx[p] = idc;
  29214. idc += (l + closePathCorr);
  29215. }
  29216. // vertical distances (v)
  29217. var path1;
  29218. var path2;
  29219. var vertex1 = null;
  29220. var vertex2 = null;
  29221. for (i = 0; i < minlg + closePathCorr; i++) {
  29222. vTotalDistance[i] = 0;
  29223. vs[i] = [0];
  29224. for (p = 0; p < pathArray.length - 1; p++) {
  29225. path1 = pathArray[p];
  29226. path2 = pathArray[p + 1];
  29227. if (i === minlg) {
  29228. vertex1 = path1[0];
  29229. vertex2 = path2[0];
  29230. }
  29231. else {
  29232. vertex1 = path1[i];
  29233. vertex2 = path2[i];
  29234. }
  29235. vectlg = vertex2.subtract(vertex1).length();
  29236. dist = vectlg + vTotalDistance[i];
  29237. vs[i].push(dist);
  29238. vTotalDistance[i] = dist;
  29239. }
  29240. if (closeArray && vertex2 && vertex1) {
  29241. path1 = pathArray[p];
  29242. path2 = pathArray[0];
  29243. if (i === minlg) {
  29244. vertex2 = path2[0];
  29245. }
  29246. vectlg = vertex2.subtract(vertex1).length();
  29247. dist = vectlg + vTotalDistance[i];
  29248. vTotalDistance[i] = dist;
  29249. }
  29250. }
  29251. // uvs
  29252. var u;
  29253. var v;
  29254. if (customUV) {
  29255. for (p = 0; p < customUV.length; p++) {
  29256. uvs.push(customUV[p].x, customUV[p].y);
  29257. }
  29258. }
  29259. else {
  29260. for (p = 0; p < pathArray.length; p++) {
  29261. for (i = 0; i < minlg + closePathCorr; i++) {
  29262. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29263. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29264. if (invertUV) {
  29265. uvs.push(v, u);
  29266. }
  29267. else {
  29268. uvs.push(u, v);
  29269. }
  29270. }
  29271. }
  29272. }
  29273. // indices
  29274. p = 0; // path index
  29275. var pi = 0; // positions array index
  29276. var l1 = lg[p] - 1; // path1 length
  29277. var l2 = lg[p + 1] - 1; // path2 length
  29278. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29279. var shft = idx[1] - idx[0]; // shift
  29280. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29281. while (pi <= min && p < path1nb) {
  29282. // 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
  29283. indices.push(pi, pi + shft, pi + 1);
  29284. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29285. pi += 1;
  29286. if (pi === min) {
  29287. p++;
  29288. if (p === lg.length - 1) {
  29289. shft = idx[0] - idx[p];
  29290. l1 = lg[p] - 1;
  29291. l2 = lg[0] - 1;
  29292. }
  29293. else {
  29294. shft = idx[p + 1] - idx[p];
  29295. l1 = lg[p] - 1;
  29296. l2 = lg[p + 1] - 1;
  29297. }
  29298. pi = idx[p];
  29299. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29300. }
  29301. }
  29302. // normals
  29303. VertexData.ComputeNormals(positions, indices, normals);
  29304. if (closePath) {
  29305. var indexFirst = 0;
  29306. var indexLast = 0;
  29307. for (p = 0; p < pathArray.length; p++) {
  29308. indexFirst = idx[p] * 3;
  29309. if (p + 1 < pathArray.length) {
  29310. indexLast = (idx[p + 1] - 1) * 3;
  29311. }
  29312. else {
  29313. indexLast = normals.length - 3;
  29314. }
  29315. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29316. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29317. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29318. normals[indexLast] = normals[indexFirst];
  29319. normals[indexLast + 1] = normals[indexFirst + 1];
  29320. normals[indexLast + 2] = normals[indexFirst + 2];
  29321. }
  29322. }
  29323. // sides
  29324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29325. // Colors
  29326. var colors = null;
  29327. if (customColors) {
  29328. colors = new Float32Array(customColors.length * 4);
  29329. for (var c = 0; c < customColors.length; c++) {
  29330. colors[c * 4] = customColors[c].r;
  29331. colors[c * 4 + 1] = customColors[c].g;
  29332. colors[c * 4 + 2] = customColors[c].b;
  29333. colors[c * 4 + 3] = customColors[c].a;
  29334. }
  29335. }
  29336. // Result
  29337. var vertexData = new VertexData();
  29338. var positions32 = new Float32Array(positions);
  29339. var normals32 = new Float32Array(normals);
  29340. var uvs32 = new Float32Array(uvs);
  29341. vertexData.indices = indices;
  29342. vertexData.positions = positions32;
  29343. vertexData.normals = normals32;
  29344. vertexData.uvs = uvs32;
  29345. if (colors) {
  29346. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29347. }
  29348. if (closePath) {
  29349. vertexData._idx = idx;
  29350. }
  29351. return vertexData;
  29352. };
  29353. /**
  29354. * Creates the VertexData of the Box.
  29355. */
  29356. VertexData.CreateBox = function (options) {
  29357. var normalsSource = [
  29358. new BABYLON.Vector3(0, 0, 1),
  29359. new BABYLON.Vector3(0, 0, -1),
  29360. new BABYLON.Vector3(1, 0, 0),
  29361. new BABYLON.Vector3(-1, 0, 0),
  29362. new BABYLON.Vector3(0, 1, 0),
  29363. new BABYLON.Vector3(0, -1, 0)
  29364. ];
  29365. var indices = [];
  29366. var positions = [];
  29367. var normals = [];
  29368. var uvs = [];
  29369. var width = options.width || options.size || 1;
  29370. var height = options.height || options.size || 1;
  29371. var depth = options.depth || options.size || 1;
  29372. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29373. var faceUV = options.faceUV || new Array(6);
  29374. var faceColors = options.faceColors;
  29375. var colors = [];
  29376. // default face colors and UV if undefined
  29377. for (var f = 0; f < 6; f++) {
  29378. if (faceUV[f] === undefined) {
  29379. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29380. }
  29381. if (faceColors && faceColors[f] === undefined) {
  29382. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29383. }
  29384. }
  29385. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29386. // Create each face in turn.
  29387. for (var index = 0; index < normalsSource.length; index++) {
  29388. var normal = normalsSource[index];
  29389. // Get two vectors perpendicular to the face normal and to each other.
  29390. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29391. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29392. // Six indices (two triangles) per face.
  29393. var verticesLength = positions.length / 3;
  29394. indices.push(verticesLength);
  29395. indices.push(verticesLength + 1);
  29396. indices.push(verticesLength + 2);
  29397. indices.push(verticesLength);
  29398. indices.push(verticesLength + 2);
  29399. indices.push(verticesLength + 3);
  29400. // Four vertices per face.
  29401. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29402. positions.push(vertex.x, vertex.y, vertex.z);
  29403. normals.push(normal.x, normal.y, normal.z);
  29404. uvs.push(faceUV[index].z, faceUV[index].w);
  29405. if (faceColors) {
  29406. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29407. }
  29408. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29409. positions.push(vertex.x, vertex.y, vertex.z);
  29410. normals.push(normal.x, normal.y, normal.z);
  29411. uvs.push(faceUV[index].x, faceUV[index].w);
  29412. if (faceColors) {
  29413. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29414. }
  29415. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29416. positions.push(vertex.x, vertex.y, vertex.z);
  29417. normals.push(normal.x, normal.y, normal.z);
  29418. uvs.push(faceUV[index].x, faceUV[index].y);
  29419. if (faceColors) {
  29420. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29421. }
  29422. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29423. positions.push(vertex.x, vertex.y, vertex.z);
  29424. normals.push(normal.x, normal.y, normal.z);
  29425. uvs.push(faceUV[index].z, faceUV[index].y);
  29426. if (faceColors) {
  29427. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29428. }
  29429. }
  29430. // sides
  29431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29432. // Result
  29433. var vertexData = new VertexData();
  29434. vertexData.indices = indices;
  29435. vertexData.positions = positions;
  29436. vertexData.normals = normals;
  29437. vertexData.uvs = uvs;
  29438. if (faceColors) {
  29439. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29440. vertexData.colors = totalColors;
  29441. }
  29442. return vertexData;
  29443. };
  29444. /**
  29445. * Creates the VertexData of the Sphere.
  29446. */
  29447. VertexData.CreateSphere = function (options) {
  29448. var segments = options.segments || 32;
  29449. var diameterX = options.diameterX || options.diameter || 1;
  29450. var diameterY = options.diameterY || options.diameter || 1;
  29451. var diameterZ = options.diameterZ || options.diameter || 1;
  29452. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29453. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29454. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29455. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29456. var totalZRotationSteps = 2 + segments;
  29457. var totalYRotationSteps = 2 * totalZRotationSteps;
  29458. var indices = [];
  29459. var positions = [];
  29460. var normals = [];
  29461. var uvs = [];
  29462. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29463. var normalizedZ = zRotationStep / totalZRotationSteps;
  29464. var angleZ = normalizedZ * Math.PI * slice;
  29465. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29466. var normalizedY = yRotationStep / totalYRotationSteps;
  29467. var angleY = normalizedY * Math.PI * 2 * arc;
  29468. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29469. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29470. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29471. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29472. var vertex = complete.multiply(radius);
  29473. var normal = complete.divide(radius).normalize();
  29474. positions.push(vertex.x, vertex.y, vertex.z);
  29475. normals.push(normal.x, normal.y, normal.z);
  29476. uvs.push(normalizedY, normalizedZ);
  29477. }
  29478. if (zRotationStep > 0) {
  29479. var verticesCount = positions.length / 3;
  29480. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29481. indices.push((firstIndex));
  29482. indices.push((firstIndex + 1));
  29483. indices.push(firstIndex + totalYRotationSteps + 1);
  29484. indices.push((firstIndex + totalYRotationSteps + 1));
  29485. indices.push((firstIndex + 1));
  29486. indices.push((firstIndex + totalYRotationSteps + 2));
  29487. }
  29488. }
  29489. }
  29490. // Sides
  29491. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29492. // Result
  29493. var vertexData = new VertexData();
  29494. vertexData.indices = indices;
  29495. vertexData.positions = positions;
  29496. vertexData.normals = normals;
  29497. vertexData.uvs = uvs;
  29498. return vertexData;
  29499. };
  29500. /**
  29501. * Creates the VertexData of the Cylinder or Cone.
  29502. */
  29503. VertexData.CreateCylinder = function (options) {
  29504. var height = options.height || 2;
  29505. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29506. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29507. var tessellation = options.tessellation || 24;
  29508. var subdivisions = options.subdivisions || 1;
  29509. var hasRings = options.hasRings ? true : false;
  29510. var enclose = options.enclose ? true : false;
  29511. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29512. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29513. var faceUV = options.faceUV || new Array(3);
  29514. var faceColors = options.faceColors;
  29515. // default face colors and UV if undefined
  29516. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29517. var ringNb = (hasRings) ? subdivisions : 1;
  29518. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29519. var f;
  29520. for (f = 0; f < surfaceNb; f++) {
  29521. if (faceColors && faceColors[f] === undefined) {
  29522. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29523. }
  29524. }
  29525. for (f = 0; f < surfaceNb; f++) {
  29526. if (faceUV && faceUV[f] === undefined) {
  29527. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29528. }
  29529. }
  29530. var indices = new Array();
  29531. var positions = new Array();
  29532. var normals = new Array();
  29533. var uvs = new Array();
  29534. var colors = new Array();
  29535. var angle_step = Math.PI * 2 * arc / tessellation;
  29536. var angle;
  29537. var h;
  29538. var radius;
  29539. var tan = (diameterBottom - diameterTop) / 2 / height;
  29540. var ringVertex = BABYLON.Vector3.Zero();
  29541. var ringNormal = BABYLON.Vector3.Zero();
  29542. var ringFirstVertex = BABYLON.Vector3.Zero();
  29543. var ringFirstNormal = BABYLON.Vector3.Zero();
  29544. var quadNormal = BABYLON.Vector3.Zero();
  29545. var Y = BABYLON.Axis.Y;
  29546. // positions, normals, uvs
  29547. var i;
  29548. var j;
  29549. var r;
  29550. var ringIdx = 1;
  29551. var s = 1; // surface index
  29552. var cs = 0;
  29553. var v = 0;
  29554. for (i = 0; i <= subdivisions; i++) {
  29555. h = i / subdivisions;
  29556. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29557. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29558. for (r = 0; r < ringIdx; r++) {
  29559. if (hasRings) {
  29560. s += r;
  29561. }
  29562. if (enclose) {
  29563. s += 2 * r;
  29564. }
  29565. for (j = 0; j <= tessellation; j++) {
  29566. angle = j * angle_step;
  29567. // position
  29568. ringVertex.x = Math.cos(-angle) * radius;
  29569. ringVertex.y = -height / 2 + h * height;
  29570. ringVertex.z = Math.sin(-angle) * radius;
  29571. // normal
  29572. if (diameterTop === 0 && i === subdivisions) {
  29573. // if no top cap, reuse former normals
  29574. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29575. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29576. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29577. }
  29578. else {
  29579. ringNormal.x = ringVertex.x;
  29580. ringNormal.z = ringVertex.z;
  29581. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29582. ringNormal.normalize();
  29583. }
  29584. // keep first ring vertex values for enclose
  29585. if (j === 0) {
  29586. ringFirstVertex.copyFrom(ringVertex);
  29587. ringFirstNormal.copyFrom(ringNormal);
  29588. }
  29589. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29590. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29591. if (hasRings) {
  29592. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29593. }
  29594. else {
  29595. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29596. }
  29597. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29598. if (faceColors) {
  29599. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29600. }
  29601. }
  29602. // if enclose, add four vertices and their dedicated normals
  29603. if (arc !== 1 && enclose) {
  29604. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29605. positions.push(0, ringVertex.y, 0);
  29606. positions.push(0, ringVertex.y, 0);
  29607. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29608. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29609. quadNormal.normalize();
  29610. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29611. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29612. quadNormal.normalize();
  29613. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29614. if (hasRings) {
  29615. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29616. }
  29617. else {
  29618. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29619. }
  29620. uvs.push(faceUV[s + 1].x, v);
  29621. uvs.push(faceUV[s + 1].z, v);
  29622. if (hasRings) {
  29623. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29624. }
  29625. else {
  29626. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29627. }
  29628. uvs.push(faceUV[s + 2].x, v);
  29629. uvs.push(faceUV[s + 2].z, v);
  29630. if (faceColors) {
  29631. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29632. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29633. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29634. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29635. }
  29636. }
  29637. if (cs !== s) {
  29638. cs = s;
  29639. }
  29640. }
  29641. }
  29642. // indices
  29643. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29644. var s;
  29645. i = 0;
  29646. for (s = 0; s < subdivisions; s++) {
  29647. var i0 = 0;
  29648. var i1 = 0;
  29649. var i2 = 0;
  29650. var i3 = 0;
  29651. for (j = 0; j < tessellation; j++) {
  29652. i0 = i * (e + 1) + j;
  29653. i1 = (i + 1) * (e + 1) + j;
  29654. i2 = i * (e + 1) + (j + 1);
  29655. i3 = (i + 1) * (e + 1) + (j + 1);
  29656. indices.push(i0, i1, i2);
  29657. indices.push(i3, i2, i1);
  29658. }
  29659. if (arc !== 1 && enclose) {
  29660. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29661. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29662. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29663. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29664. }
  29665. i = (hasRings) ? (i + 2) : (i + 1);
  29666. }
  29667. // Caps
  29668. var createCylinderCap = function (isTop) {
  29669. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29670. if (radius === 0) {
  29671. return;
  29672. }
  29673. // Cap positions, normals & uvs
  29674. var angle;
  29675. var circleVector;
  29676. var i;
  29677. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29678. var c = null;
  29679. if (faceColors) {
  29680. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29681. }
  29682. // cap center
  29683. var vbase = positions.length / 3;
  29684. var offset = isTop ? height / 2 : -height / 2;
  29685. var center = new BABYLON.Vector3(0, offset, 0);
  29686. positions.push(center.x, center.y, center.z);
  29687. normals.push(0, isTop ? 1 : -1, 0);
  29688. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29689. if (c) {
  29690. colors.push(c.r, c.g, c.b, c.a);
  29691. }
  29692. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29693. for (i = 0; i <= tessellation; i++) {
  29694. angle = Math.PI * 2 * i * arc / tessellation;
  29695. var cos = Math.cos(-angle);
  29696. var sin = Math.sin(-angle);
  29697. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29698. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29699. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29700. normals.push(0, isTop ? 1 : -1, 0);
  29701. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29702. if (c) {
  29703. colors.push(c.r, c.g, c.b, c.a);
  29704. }
  29705. }
  29706. // Cap indices
  29707. for (i = 0; i < tessellation; i++) {
  29708. if (!isTop) {
  29709. indices.push(vbase);
  29710. indices.push(vbase + (i + 1));
  29711. indices.push(vbase + (i + 2));
  29712. }
  29713. else {
  29714. indices.push(vbase);
  29715. indices.push(vbase + (i + 2));
  29716. indices.push(vbase + (i + 1));
  29717. }
  29718. }
  29719. };
  29720. // add caps to geometry
  29721. createCylinderCap(false);
  29722. createCylinderCap(true);
  29723. // Sides
  29724. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29725. var vertexData = new VertexData();
  29726. vertexData.indices = indices;
  29727. vertexData.positions = positions;
  29728. vertexData.normals = normals;
  29729. vertexData.uvs = uvs;
  29730. if (faceColors) {
  29731. vertexData.colors = colors;
  29732. }
  29733. return vertexData;
  29734. };
  29735. /**
  29736. * Creates the VertexData of the Torus.
  29737. */
  29738. VertexData.CreateTorus = function (options) {
  29739. var indices = [];
  29740. var positions = [];
  29741. var normals = [];
  29742. var uvs = [];
  29743. var diameter = options.diameter || 1;
  29744. var thickness = options.thickness || 0.5;
  29745. var tessellation = options.tessellation || 16;
  29746. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29747. var stride = tessellation + 1;
  29748. for (var i = 0; i <= tessellation; i++) {
  29749. var u = i / tessellation;
  29750. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29751. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29752. for (var j = 0; j <= tessellation; j++) {
  29753. var v = 1 - j / tessellation;
  29754. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29755. var dx = Math.cos(innerAngle);
  29756. var dy = Math.sin(innerAngle);
  29757. // Create a vertex.
  29758. var normal = new BABYLON.Vector3(dx, dy, 0);
  29759. var position = normal.scale(thickness / 2);
  29760. var textureCoordinate = new BABYLON.Vector2(u, v);
  29761. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29762. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29763. positions.push(position.x, position.y, position.z);
  29764. normals.push(normal.x, normal.y, normal.z);
  29765. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29766. // And create indices for two triangles.
  29767. var nextI = (i + 1) % stride;
  29768. var nextJ = (j + 1) % stride;
  29769. indices.push(i * stride + j);
  29770. indices.push(i * stride + nextJ);
  29771. indices.push(nextI * stride + j);
  29772. indices.push(i * stride + nextJ);
  29773. indices.push(nextI * stride + nextJ);
  29774. indices.push(nextI * stride + j);
  29775. }
  29776. }
  29777. // Sides
  29778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29779. // Result
  29780. var vertexData = new VertexData();
  29781. vertexData.indices = indices;
  29782. vertexData.positions = positions;
  29783. vertexData.normals = normals;
  29784. vertexData.uvs = uvs;
  29785. return vertexData;
  29786. };
  29787. /**
  29788. * Creates the VertexData of the LineSystem.
  29789. */
  29790. VertexData.CreateLineSystem = function (options) {
  29791. var indices = [];
  29792. var positions = [];
  29793. var lines = options.lines;
  29794. var colors = options.colors;
  29795. var vertexColors = [];
  29796. var idx = 0;
  29797. for (var l = 0; l < lines.length; l++) {
  29798. var points = lines[l];
  29799. for (var index = 0; index < points.length; index++) {
  29800. positions.push(points[index].x, points[index].y, points[index].z);
  29801. if (colors) {
  29802. var color = colors[l];
  29803. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29804. }
  29805. if (index > 0) {
  29806. indices.push(idx - 1);
  29807. indices.push(idx);
  29808. }
  29809. idx++;
  29810. }
  29811. }
  29812. var vertexData = new VertexData();
  29813. vertexData.indices = indices;
  29814. vertexData.positions = positions;
  29815. if (colors) {
  29816. vertexData.colors = vertexColors;
  29817. }
  29818. return vertexData;
  29819. };
  29820. /**
  29821. * Create the VertexData of the DashedLines.
  29822. */
  29823. VertexData.CreateDashedLines = function (options) {
  29824. var dashSize = options.dashSize || 3;
  29825. var gapSize = options.gapSize || 1;
  29826. var dashNb = options.dashNb || 200;
  29827. var points = options.points;
  29828. var positions = new Array();
  29829. var indices = new Array();
  29830. var curvect = BABYLON.Vector3.Zero();
  29831. var lg = 0;
  29832. var nb = 0;
  29833. var shft = 0;
  29834. var dashshft = 0;
  29835. var curshft = 0;
  29836. var idx = 0;
  29837. var i = 0;
  29838. for (i = 0; i < points.length - 1; i++) {
  29839. points[i + 1].subtractToRef(points[i], curvect);
  29840. lg += curvect.length();
  29841. }
  29842. shft = lg / dashNb;
  29843. dashshft = dashSize * shft / (dashSize + gapSize);
  29844. for (i = 0; i < points.length - 1; i++) {
  29845. points[i + 1].subtractToRef(points[i], curvect);
  29846. nb = Math.floor(curvect.length() / shft);
  29847. curvect.normalize();
  29848. for (var j = 0; j < nb; j++) {
  29849. curshft = shft * j;
  29850. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29851. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29852. indices.push(idx, idx + 1);
  29853. idx += 2;
  29854. }
  29855. }
  29856. // Result
  29857. var vertexData = new VertexData();
  29858. vertexData.positions = positions;
  29859. vertexData.indices = indices;
  29860. return vertexData;
  29861. };
  29862. /**
  29863. * Creates the VertexData of the Ground.
  29864. */
  29865. VertexData.CreateGround = function (options) {
  29866. var indices = [];
  29867. var positions = [];
  29868. var normals = [];
  29869. var uvs = [];
  29870. var row, col;
  29871. var width = options.width || 1;
  29872. var height = options.height || 1;
  29873. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29874. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29875. for (row = 0; row <= subdivisionsY; row++) {
  29876. for (col = 0; col <= subdivisionsX; col++) {
  29877. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29878. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29879. positions.push(position.x, position.y, position.z);
  29880. normals.push(normal.x, normal.y, normal.z);
  29881. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29882. }
  29883. }
  29884. for (row = 0; row < subdivisionsY; row++) {
  29885. for (col = 0; col < subdivisionsX; col++) {
  29886. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29887. indices.push(col + 1 + row * (subdivisionsX + 1));
  29888. indices.push(col + row * (subdivisionsX + 1));
  29889. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29890. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29891. indices.push(col + row * (subdivisionsX + 1));
  29892. }
  29893. }
  29894. // Result
  29895. var vertexData = new VertexData();
  29896. vertexData.indices = indices;
  29897. vertexData.positions = positions;
  29898. vertexData.normals = normals;
  29899. vertexData.uvs = uvs;
  29900. return vertexData;
  29901. };
  29902. /**
  29903. * Creates the VertexData of the TiledGround.
  29904. */
  29905. VertexData.CreateTiledGround = function (options) {
  29906. var xmin = options.xmin || -1.0;
  29907. var zmin = options.zmin || -1.0;
  29908. var xmax = options.xmax || 1.0;
  29909. var zmax = options.zmax || 1.0;
  29910. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29911. var precision = options.precision || { w: 1, h: 1 };
  29912. var indices = new Array();
  29913. var positions = new Array();
  29914. var normals = new Array();
  29915. var uvs = new Array();
  29916. var row, col, tileRow, tileCol;
  29917. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29918. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29919. precision.w = (precision.w < 1) ? 1 : precision.w;
  29920. precision.h = (precision.h < 1) ? 1 : precision.h;
  29921. var tileSize = {
  29922. 'w': (xmax - xmin) / subdivisions.w,
  29923. 'h': (zmax - zmin) / subdivisions.h
  29924. };
  29925. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29926. // Indices
  29927. var base = positions.length / 3;
  29928. var rowLength = precision.w + 1;
  29929. for (row = 0; row < precision.h; row++) {
  29930. for (col = 0; col < precision.w; col++) {
  29931. var square = [
  29932. base + col + row * rowLength,
  29933. base + (col + 1) + row * rowLength,
  29934. base + (col + 1) + (row + 1) * rowLength,
  29935. base + col + (row + 1) * rowLength
  29936. ];
  29937. indices.push(square[1]);
  29938. indices.push(square[2]);
  29939. indices.push(square[3]);
  29940. indices.push(square[0]);
  29941. indices.push(square[1]);
  29942. indices.push(square[3]);
  29943. }
  29944. }
  29945. // Position, normals and uvs
  29946. var position = BABYLON.Vector3.Zero();
  29947. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29948. for (row = 0; row <= precision.h; row++) {
  29949. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29950. for (col = 0; col <= precision.w; col++) {
  29951. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29952. position.y = 0;
  29953. positions.push(position.x, position.y, position.z);
  29954. normals.push(normal.x, normal.y, normal.z);
  29955. uvs.push(col / precision.w, row / precision.h);
  29956. }
  29957. }
  29958. }
  29959. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29960. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29961. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29962. }
  29963. }
  29964. // Result
  29965. var vertexData = new VertexData();
  29966. vertexData.indices = indices;
  29967. vertexData.positions = positions;
  29968. vertexData.normals = normals;
  29969. vertexData.uvs = uvs;
  29970. return vertexData;
  29971. };
  29972. /**
  29973. * Creates the VertexData of the Ground designed from a heightmap.
  29974. */
  29975. VertexData.CreateGroundFromHeightMap = function (options) {
  29976. var indices = [];
  29977. var positions = [];
  29978. var normals = [];
  29979. var uvs = [];
  29980. var row, col;
  29981. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29982. // Vertices
  29983. for (row = 0; row <= options.subdivisions; row++) {
  29984. for (col = 0; col <= options.subdivisions; col++) {
  29985. 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));
  29986. // Compute height
  29987. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29988. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29989. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29990. var r = options.buffer[pos] / 255.0;
  29991. var g = options.buffer[pos + 1] / 255.0;
  29992. var b = options.buffer[pos + 2] / 255.0;
  29993. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29994. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29995. // Add vertex
  29996. positions.push(position.x, position.y, position.z);
  29997. normals.push(0, 0, 0);
  29998. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29999. }
  30000. }
  30001. // Indices
  30002. for (row = 0; row < options.subdivisions; row++) {
  30003. for (col = 0; col < options.subdivisions; col++) {
  30004. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30005. indices.push(col + 1 + row * (options.subdivisions + 1));
  30006. indices.push(col + row * (options.subdivisions + 1));
  30007. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30008. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30009. indices.push(col + row * (options.subdivisions + 1));
  30010. }
  30011. }
  30012. // Normals
  30013. VertexData.ComputeNormals(positions, indices, normals);
  30014. // Result
  30015. var vertexData = new VertexData();
  30016. vertexData.indices = indices;
  30017. vertexData.positions = positions;
  30018. vertexData.normals = normals;
  30019. vertexData.uvs = uvs;
  30020. return vertexData;
  30021. };
  30022. /**
  30023. * Creates the VertexData of the Plane.
  30024. */
  30025. VertexData.CreatePlane = function (options) {
  30026. var indices = [];
  30027. var positions = [];
  30028. var normals = [];
  30029. var uvs = [];
  30030. var width = options.width || options.size || 1;
  30031. var height = options.height || options.size || 1;
  30032. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30033. // Vertices
  30034. var halfWidth = width / 2.0;
  30035. var halfHeight = height / 2.0;
  30036. positions.push(-halfWidth, -halfHeight, 0);
  30037. normals.push(0, 0, -1.0);
  30038. uvs.push(0.0, 0.0);
  30039. positions.push(halfWidth, -halfHeight, 0);
  30040. normals.push(0, 0, -1.0);
  30041. uvs.push(1.0, 0.0);
  30042. positions.push(halfWidth, halfHeight, 0);
  30043. normals.push(0, 0, -1.0);
  30044. uvs.push(1.0, 1.0);
  30045. positions.push(-halfWidth, halfHeight, 0);
  30046. normals.push(0, 0, -1.0);
  30047. uvs.push(0.0, 1.0);
  30048. // Indices
  30049. indices.push(0);
  30050. indices.push(1);
  30051. indices.push(2);
  30052. indices.push(0);
  30053. indices.push(2);
  30054. indices.push(3);
  30055. // Sides
  30056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30057. // Result
  30058. var vertexData = new VertexData();
  30059. vertexData.indices = indices;
  30060. vertexData.positions = positions;
  30061. vertexData.normals = normals;
  30062. vertexData.uvs = uvs;
  30063. return vertexData;
  30064. };
  30065. /**
  30066. * Creates the VertexData of the Disc or regular Polygon.
  30067. */
  30068. VertexData.CreateDisc = function (options) {
  30069. var positions = new Array();
  30070. var indices = new Array();
  30071. var normals = new Array();
  30072. var uvs = new Array();
  30073. var radius = options.radius || 0.5;
  30074. var tessellation = options.tessellation || 64;
  30075. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30076. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30077. // positions and uvs
  30078. positions.push(0, 0, 0); // disc center first
  30079. uvs.push(0.5, 0.5);
  30080. var theta = Math.PI * 2 * arc;
  30081. var step = theta / tessellation;
  30082. for (var a = 0; a < theta; a += step) {
  30083. var x = Math.cos(a);
  30084. var y = Math.sin(a);
  30085. var u = (x + 1) / 2;
  30086. var v = (1 - y) / 2;
  30087. positions.push(radius * x, radius * y, 0);
  30088. uvs.push(u, v);
  30089. }
  30090. if (arc === 1) {
  30091. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30092. uvs.push(uvs[2], uvs[3]);
  30093. }
  30094. //indices
  30095. var vertexNb = positions.length / 3;
  30096. for (var i = 1; i < vertexNb - 1; i++) {
  30097. indices.push(i + 1, 0, i);
  30098. }
  30099. // result
  30100. VertexData.ComputeNormals(positions, indices, normals);
  30101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30102. var vertexData = new VertexData();
  30103. vertexData.indices = indices;
  30104. vertexData.positions = positions;
  30105. vertexData.normals = normals;
  30106. vertexData.uvs = uvs;
  30107. return vertexData;
  30108. };
  30109. /**
  30110. * Re-creates the VertexData of the Polygon for sideOrientation.
  30111. */
  30112. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30113. var faceUV = fUV || new Array(3);
  30114. var faceColors = fColors;
  30115. var colors = [];
  30116. // default face colors and UV if undefined
  30117. for (var f = 0; f < 3; f++) {
  30118. if (faceUV[f] === undefined) {
  30119. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30120. }
  30121. if (faceColors && faceColors[f] === undefined) {
  30122. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30123. }
  30124. }
  30125. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30126. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30127. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30128. var indices = polygon.getIndices();
  30129. // set face colours and textures
  30130. var idx = 0;
  30131. var face = 0;
  30132. for (var index = 0; index < normals.length; index += 3) {
  30133. //Edge Face no. 1
  30134. if (Math.abs(normals[index + 1]) < 0.001) {
  30135. face = 1;
  30136. }
  30137. //Top Face no. 0
  30138. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30139. face = 0;
  30140. }
  30141. //Bottom Face no. 2
  30142. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30143. face = 2;
  30144. }
  30145. idx = index / 3;
  30146. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30147. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30148. if (faceColors) {
  30149. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30150. }
  30151. }
  30152. // sides
  30153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30154. // Result
  30155. var vertexData = new VertexData();
  30156. vertexData.indices = indices;
  30157. vertexData.positions = positions;
  30158. vertexData.normals = normals;
  30159. vertexData.uvs = uvs;
  30160. if (faceColors) {
  30161. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30162. vertexData.colors = totalColors;
  30163. }
  30164. return vertexData;
  30165. };
  30166. /**
  30167. * Creates the VertexData of the IcoSphere.
  30168. */
  30169. VertexData.CreateIcoSphere = function (options) {
  30170. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30171. var radius = options.radius || 1;
  30172. var flat = (options.flat === undefined) ? true : options.flat;
  30173. var subdivisions = options.subdivisions || 4;
  30174. var radiusX = options.radiusX || radius;
  30175. var radiusY = options.radiusY || radius;
  30176. var radiusZ = options.radiusZ || radius;
  30177. var t = (1 + Math.sqrt(5)) / 2;
  30178. // 12 vertex x,y,z
  30179. var ico_vertices = [
  30180. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30181. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30182. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30183. ];
  30184. // index of 3 vertex makes a face of icopshere
  30185. var ico_indices = [
  30186. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30187. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30188. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30189. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30190. ];
  30191. // vertex for uv have aliased position, not for UV
  30192. var vertices_unalias_id = [
  30193. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30194. // vertex alias
  30195. 0,
  30196. 2,
  30197. 3,
  30198. 3,
  30199. 3,
  30200. 4,
  30201. 7,
  30202. 8,
  30203. 9,
  30204. 9,
  30205. 10,
  30206. 11 // 23: B + 12
  30207. ];
  30208. // uv as integer step (not pixels !)
  30209. var ico_vertexuv = [
  30210. 5, 1, 3, 1, 6, 4, 0, 0,
  30211. 5, 3, 4, 2, 2, 2, 4, 0,
  30212. 2, 0, 1, 1, 6, 0, 6, 2,
  30213. // vertex alias (for same vertex on different faces)
  30214. 0, 4,
  30215. 3, 3,
  30216. 4, 4,
  30217. 3, 1,
  30218. 4, 2,
  30219. 4, 4,
  30220. 0, 2,
  30221. 1, 1,
  30222. 2, 2,
  30223. 3, 3,
  30224. 1, 3,
  30225. 2, 4 // 23: B + 12
  30226. ];
  30227. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30228. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30229. // First island of uv mapping
  30230. // v = 4h 3+ 2
  30231. // v = 3h 9+ 4
  30232. // v = 2h 9+ 5 B
  30233. // v = 1h 9 1 0
  30234. // v = 0h 3 8 7 A
  30235. // u = 0 1 2 3 4 5 6 *a
  30236. // Second island of uv mapping
  30237. // v = 4h 0+ B+ 4+
  30238. // v = 3h A+ 2+
  30239. // v = 2h 7+ 6 3+
  30240. // v = 1h 8+ 3+
  30241. // v = 0h
  30242. // u = 0 1 2 3 4 5 6 *a
  30243. // Face layout on texture UV mapping
  30244. // ============
  30245. // \ 4 /\ 16 / ======
  30246. // \ / \ / /\ 11 /
  30247. // \/ 7 \/ / \ /
  30248. // ======= / 10 \/
  30249. // /\ 17 /\ =======
  30250. // / \ / \ \ 15 /\
  30251. // / 8 \/ 12 \ \ / \
  30252. // ============ \/ 6 \
  30253. // \ 18 /\ ============
  30254. // \ / \ \ 5 /\ 0 /
  30255. // \/ 13 \ \ / \ /
  30256. // ======= \/ 1 \/
  30257. // =============
  30258. // /\ 19 /\ 2 /\
  30259. // / \ / \ / \
  30260. // / 14 \/ 9 \/ 3 \
  30261. // ===================
  30262. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30263. var ustep = 138 / 1024;
  30264. var vstep = 239 / 1024;
  30265. var uoffset = 60 / 1024;
  30266. var voffset = 26 / 1024;
  30267. // Second island should have margin, not to touch the first island
  30268. // avoid any borderline artefact in pixel rounding
  30269. var island_u_offset = -40 / 1024;
  30270. var island_v_offset = +20 / 1024;
  30271. // face is either island 0 or 1 :
  30272. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30273. var island = [
  30274. 0, 0, 0, 0, 1,
  30275. 0, 0, 1, 1, 0,
  30276. 0, 0, 1, 1, 0,
  30277. 0, 1, 1, 1, 0 // 15 - 19
  30278. ];
  30279. var indices = new Array();
  30280. var positions = new Array();
  30281. var normals = new Array();
  30282. var uvs = new Array();
  30283. var current_indice = 0;
  30284. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30285. var face_vertex_pos = new Array(3);
  30286. var face_vertex_uv = new Array(3);
  30287. var v012;
  30288. for (v012 = 0; v012 < 3; v012++) {
  30289. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30290. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30291. }
  30292. // create all with normals
  30293. for (var face = 0; face < 20; face++) {
  30294. // 3 vertex per face
  30295. for (v012 = 0; v012 < 3; v012++) {
  30296. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30297. var v_id = ico_indices[3 * face + v012];
  30298. // vertex have 3D position (x,y,z)
  30299. 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]);
  30300. // Normalize to get normal, then scale to radius
  30301. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30302. // uv Coordinates from vertex ID
  30303. 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);
  30304. }
  30305. // Subdivide the face (interpolate pos, norm, uv)
  30306. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30307. // - norm is linear interpolation of vertex corner normal
  30308. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30309. // - uv is linear interpolation
  30310. //
  30311. // Topology is as below for sub-divide by 2
  30312. // vertex shown as v0,v1,v2
  30313. // interp index is i1 to progress in range [v0,v1[
  30314. // interp index is i2 to progress in range [v0,v2[
  30315. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30316. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30317. //
  30318. //
  30319. // i2 v2
  30320. // ^ ^
  30321. // / / \
  30322. // / / \
  30323. // / / \
  30324. // / / (0,1) \
  30325. // / #---------\
  30326. // / / \ (0,0)'/ \
  30327. // / / \ / \
  30328. // / / \ / \
  30329. // / / (0,0) \ / (1,0) \
  30330. // / #---------#---------\
  30331. // v0 v1
  30332. //
  30333. // --------------------> i1
  30334. //
  30335. // interp of (i1,i2):
  30336. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30337. // along i1 : lerp(x0,x1, i1/(S-i2))
  30338. //
  30339. // centroid of triangle is needed to get help normal computation
  30340. // (c1,c2) are used for centroid location
  30341. var interp_vertex = function (i1, i2, c1, c2) {
  30342. // vertex is interpolated from
  30343. // - face_vertex_pos[0..2]
  30344. // - face_vertex_uv[0..2]
  30345. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30346. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30347. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30348. pos_interp.normalize();
  30349. var vertex_normal;
  30350. if (flat) {
  30351. // in flat mode, recalculate normal as face centroid normal
  30352. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30353. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30354. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30355. }
  30356. else {
  30357. // in smooth mode, recalculate normal from each single vertex position
  30358. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30359. }
  30360. // Vertex normal need correction due to X,Y,Z radius scaling
  30361. vertex_normal.x /= radiusX;
  30362. vertex_normal.y /= radiusY;
  30363. vertex_normal.z /= radiusZ;
  30364. vertex_normal.normalize();
  30365. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30366. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30367. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30368. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30369. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30370. uvs.push(uv_interp.x, uv_interp.y);
  30371. // push each vertex has member of a face
  30372. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30373. indices.push(current_indice);
  30374. current_indice++;
  30375. };
  30376. for (var i2 = 0; i2 < subdivisions; i2++) {
  30377. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30378. // face : (i1,i2) for /\ :
  30379. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30380. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30381. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30382. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30383. if (i1 + i2 + 1 < subdivisions) {
  30384. // face : (i1,i2)' for \/ :
  30385. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30386. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30387. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30388. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30389. }
  30390. }
  30391. }
  30392. }
  30393. // Sides
  30394. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30395. // Result
  30396. var vertexData = new VertexData();
  30397. vertexData.indices = indices;
  30398. vertexData.positions = positions;
  30399. vertexData.normals = normals;
  30400. vertexData.uvs = uvs;
  30401. return vertexData;
  30402. };
  30403. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30404. /**
  30405. * Creates the VertexData of the Polyhedron.
  30406. */
  30407. VertexData.CreatePolyhedron = function (options) {
  30408. // provided polyhedron types :
  30409. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30410. // 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)
  30411. var polyhedra = [];
  30412. 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]] };
  30413. 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]] };
  30414. polyhedra[2] = {
  30415. 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]],
  30416. 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]]
  30417. };
  30418. polyhedra[3] = {
  30419. 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]],
  30420. 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]]
  30421. };
  30422. polyhedra[4] = {
  30423. 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]],
  30424. 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]]
  30425. };
  30426. 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]] };
  30427. 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]] };
  30428. 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]] };
  30429. 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]] };
  30430. 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]] };
  30431. 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]] };
  30432. 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]] };
  30433. 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]] };
  30434. 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]] };
  30435. polyhedra[14] = {
  30436. 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]],
  30437. 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]]
  30438. };
  30439. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30440. var size = options.size;
  30441. var sizeX = options.sizeX || size || 1;
  30442. var sizeY = options.sizeY || size || 1;
  30443. var sizeZ = options.sizeZ || size || 1;
  30444. var data = options.custom || polyhedra[type];
  30445. var nbfaces = data.face.length;
  30446. var faceUV = options.faceUV || new Array(nbfaces);
  30447. var faceColors = options.faceColors;
  30448. var flat = (options.flat === undefined) ? true : options.flat;
  30449. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30450. var positions = new Array();
  30451. var indices = new Array();
  30452. var normals = new Array();
  30453. var uvs = new Array();
  30454. var colors = new Array();
  30455. var index = 0;
  30456. var faceIdx = 0; // face cursor in the array "indexes"
  30457. var indexes = new Array();
  30458. var i = 0;
  30459. var f = 0;
  30460. var u, v, ang, x, y, tmp;
  30461. // default face colors and UV if undefined
  30462. if (flat) {
  30463. for (f = 0; f < nbfaces; f++) {
  30464. if (faceColors && faceColors[f] === undefined) {
  30465. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30466. }
  30467. if (faceUV && faceUV[f] === undefined) {
  30468. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30469. }
  30470. }
  30471. }
  30472. if (!flat) {
  30473. for (i = 0; i < data.vertex.length; i++) {
  30474. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30475. uvs.push(0, 0);
  30476. }
  30477. for (f = 0; f < nbfaces; f++) {
  30478. for (i = 0; i < data.face[f].length - 2; i++) {
  30479. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30480. }
  30481. }
  30482. }
  30483. else {
  30484. for (f = 0; f < nbfaces; f++) {
  30485. var fl = data.face[f].length; // number of vertices of the current face
  30486. ang = 2 * Math.PI / fl;
  30487. x = 0.5 * Math.tan(ang / 2);
  30488. y = 0.5;
  30489. // positions, uvs, colors
  30490. for (i = 0; i < fl; i++) {
  30491. // positions
  30492. 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);
  30493. indexes.push(index);
  30494. index++;
  30495. // uvs
  30496. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30497. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30498. uvs.push(u, v);
  30499. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30500. y = x * Math.sin(ang) + y * Math.cos(ang);
  30501. x = tmp;
  30502. // colors
  30503. if (faceColors) {
  30504. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30505. }
  30506. }
  30507. // indices from indexes
  30508. for (i = 0; i < fl - 2; i++) {
  30509. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30510. }
  30511. faceIdx += fl;
  30512. }
  30513. }
  30514. VertexData.ComputeNormals(positions, indices, normals);
  30515. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30516. var vertexData = new VertexData();
  30517. vertexData.positions = positions;
  30518. vertexData.indices = indices;
  30519. vertexData.normals = normals;
  30520. vertexData.uvs = uvs;
  30521. if (faceColors && flat) {
  30522. vertexData.colors = colors;
  30523. }
  30524. return vertexData;
  30525. };
  30526. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30527. /**
  30528. * Creates the VertexData of the Torus Knot.
  30529. */
  30530. VertexData.CreateTorusKnot = function (options) {
  30531. var indices = new Array();
  30532. var positions = new Array();
  30533. var normals = new Array();
  30534. var uvs = new Array();
  30535. var radius = options.radius || 2;
  30536. var tube = options.tube || 0.5;
  30537. var radialSegments = options.radialSegments || 32;
  30538. var tubularSegments = options.tubularSegments || 32;
  30539. var p = options.p || 2;
  30540. var q = options.q || 3;
  30541. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30542. // Helper
  30543. var getPos = function (angle) {
  30544. var cu = Math.cos(angle);
  30545. var su = Math.sin(angle);
  30546. var quOverP = q / p * angle;
  30547. var cs = Math.cos(quOverP);
  30548. var tx = radius * (2 + cs) * 0.5 * cu;
  30549. var ty = radius * (2 + cs) * su * 0.5;
  30550. var tz = radius * Math.sin(quOverP) * 0.5;
  30551. return new BABYLON.Vector3(tx, ty, tz);
  30552. };
  30553. // Vertices
  30554. var i;
  30555. var j;
  30556. for (i = 0; i <= radialSegments; i++) {
  30557. var modI = i % radialSegments;
  30558. var u = modI / radialSegments * 2 * p * Math.PI;
  30559. var p1 = getPos(u);
  30560. var p2 = getPos(u + 0.01);
  30561. var tang = p2.subtract(p1);
  30562. var n = p2.add(p1);
  30563. var bitan = BABYLON.Vector3.Cross(tang, n);
  30564. n = BABYLON.Vector3.Cross(bitan, tang);
  30565. bitan.normalize();
  30566. n.normalize();
  30567. for (j = 0; j < tubularSegments; j++) {
  30568. var modJ = j % tubularSegments;
  30569. var v = modJ / tubularSegments * 2 * Math.PI;
  30570. var cx = -tube * Math.cos(v);
  30571. var cy = tube * Math.sin(v);
  30572. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30573. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30574. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30575. uvs.push(i / radialSegments);
  30576. uvs.push(j / tubularSegments);
  30577. }
  30578. }
  30579. for (i = 0; i < radialSegments; i++) {
  30580. for (j = 0; j < tubularSegments; j++) {
  30581. var jNext = (j + 1) % tubularSegments;
  30582. var a = i * tubularSegments + j;
  30583. var b = (i + 1) * tubularSegments + j;
  30584. var c = (i + 1) * tubularSegments + jNext;
  30585. var d = i * tubularSegments + jNext;
  30586. indices.push(d);
  30587. indices.push(b);
  30588. indices.push(a);
  30589. indices.push(d);
  30590. indices.push(c);
  30591. indices.push(b);
  30592. }
  30593. }
  30594. // Normals
  30595. VertexData.ComputeNormals(positions, indices, normals);
  30596. // Sides
  30597. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30598. // Result
  30599. var vertexData = new VertexData();
  30600. vertexData.indices = indices;
  30601. vertexData.positions = positions;
  30602. vertexData.normals = normals;
  30603. vertexData.uvs = uvs;
  30604. return vertexData;
  30605. };
  30606. // Tools
  30607. /**
  30608. * @param {any} - positions (number[] or Float32Array)
  30609. * @param {any} - indices (number[] or Uint16Array)
  30610. * @param {any} - normals (number[] or Float32Array)
  30611. * options (optional) :
  30612. * facetPositions : optional array of facet positions (vector3)
  30613. * facetNormals : optional array of facet normals (vector3)
  30614. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30615. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30616. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30617. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30618. * bInfo : optional bounding info, required for facetPartitioning computation
  30619. * useRightHandedSystem: optional boolean to for right handed system computation
  30620. * depthSort : optional boolean to enable the facet depth sort computation
  30621. * distanceTo : optional Vector3 to compute the facet depth from this location
  30622. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30623. */
  30624. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30625. // temporary scalar variables
  30626. var index = 0; // facet index
  30627. var p1p2x = 0.0; // p1p2 vector x coordinate
  30628. var p1p2y = 0.0; // p1p2 vector y coordinate
  30629. var p1p2z = 0.0; // p1p2 vector z coordinate
  30630. var p3p2x = 0.0; // p3p2 vector x coordinate
  30631. var p3p2y = 0.0; // p3p2 vector y coordinate
  30632. var p3p2z = 0.0; // p3p2 vector z coordinate
  30633. var faceNormalx = 0.0; // facet normal x coordinate
  30634. var faceNormaly = 0.0; // facet normal y coordinate
  30635. var faceNormalz = 0.0; // facet normal z coordinate
  30636. var length = 0.0; // facet normal length before normalization
  30637. var v1x = 0; // vector1 x index in the positions array
  30638. var v1y = 0; // vector1 y index in the positions array
  30639. var v1z = 0; // vector1 z index in the positions array
  30640. var v2x = 0; // vector2 x index in the positions array
  30641. var v2y = 0; // vector2 y index in the positions array
  30642. var v2z = 0; // vector2 z index in the positions array
  30643. var v3x = 0; // vector3 x index in the positions array
  30644. var v3y = 0; // vector3 y index in the positions array
  30645. var v3z = 0; // vector3 z index in the positions array
  30646. var computeFacetNormals = false;
  30647. var computeFacetPositions = false;
  30648. var computeFacetPartitioning = false;
  30649. var computeDepthSort = false;
  30650. var faceNormalSign = 1;
  30651. var ratio = 0;
  30652. var distanceTo = null;
  30653. if (options) {
  30654. computeFacetNormals = (options.facetNormals) ? true : false;
  30655. computeFacetPositions = (options.facetPositions) ? true : false;
  30656. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30657. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30658. ratio = options.ratio || 0;
  30659. computeDepthSort = (options.depthSort) ? true : false;
  30660. distanceTo = (options.distanceTo);
  30661. if (computeDepthSort) {
  30662. if (distanceTo === undefined) {
  30663. distanceTo = BABYLON.Vector3.Zero();
  30664. }
  30665. var depthSortedFacets = options.depthSortedFacets;
  30666. }
  30667. }
  30668. // facetPartitioning reinit if needed
  30669. var xSubRatio = 0;
  30670. var ySubRatio = 0;
  30671. var zSubRatio = 0;
  30672. var subSq = 0;
  30673. if (computeFacetPartitioning && options && options.bbSize) {
  30674. var ox = 0; // X partitioning index for facet position
  30675. var oy = 0; // Y partinioning index for facet position
  30676. var oz = 0; // Z partinioning index for facet position
  30677. var b1x = 0; // X partitioning index for facet v1 vertex
  30678. var b1y = 0; // Y partitioning index for facet v1 vertex
  30679. var b1z = 0; // z partitioning index for facet v1 vertex
  30680. var b2x = 0; // X partitioning index for facet v2 vertex
  30681. var b2y = 0; // Y partitioning index for facet v2 vertex
  30682. var b2z = 0; // Z partitioning index for facet v2 vertex
  30683. var b3x = 0; // X partitioning index for facet v3 vertex
  30684. var b3y = 0; // Y partitioning index for facet v3 vertex
  30685. var b3z = 0; // Z partitioning index for facet v3 vertex
  30686. var block_idx_o = 0; // facet barycenter block index
  30687. var block_idx_v1 = 0; // v1 vertex block index
  30688. var block_idx_v2 = 0; // v2 vertex block index
  30689. var block_idx_v3 = 0; // v3 vertex block index
  30690. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30691. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30692. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30693. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30694. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30695. subSq = options.subDiv.max * options.subDiv.max;
  30696. options.facetPartitioning.length = 0;
  30697. }
  30698. // reset the normals
  30699. for (index = 0; index < positions.length; index++) {
  30700. normals[index] = 0.0;
  30701. }
  30702. // Loop : 1 indice triplet = 1 facet
  30703. var nbFaces = (indices.length / 3) | 0;
  30704. for (index = 0; index < nbFaces; index++) {
  30705. // get the indexes of the coordinates of each vertex of the facet
  30706. v1x = indices[index * 3] * 3;
  30707. v1y = v1x + 1;
  30708. v1z = v1x + 2;
  30709. v2x = indices[index * 3 + 1] * 3;
  30710. v2y = v2x + 1;
  30711. v2z = v2x + 2;
  30712. v3x = indices[index * 3 + 2] * 3;
  30713. v3y = v3x + 1;
  30714. v3z = v3x + 2;
  30715. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30716. p1p2y = positions[v1y] - positions[v2y];
  30717. p1p2z = positions[v1z] - positions[v2z];
  30718. p3p2x = positions[v3x] - positions[v2x];
  30719. p3p2y = positions[v3y] - positions[v2y];
  30720. p3p2z = positions[v3z] - positions[v2z];
  30721. // compute the face normal with the cross product
  30722. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30723. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30724. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30725. // normalize this normal and store it in the array facetData
  30726. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30727. length = (length === 0) ? 1.0 : length;
  30728. faceNormalx /= length;
  30729. faceNormaly /= length;
  30730. faceNormalz /= length;
  30731. if (computeFacetNormals && options) {
  30732. options.facetNormals[index].x = faceNormalx;
  30733. options.facetNormals[index].y = faceNormaly;
  30734. options.facetNormals[index].z = faceNormalz;
  30735. }
  30736. if (computeFacetPositions && options) {
  30737. // compute and the facet barycenter coordinates in the array facetPositions
  30738. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30739. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30740. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30741. }
  30742. if (computeFacetPartitioning && options) {
  30743. // store the facet indexes in arrays in the main facetPartitioning array :
  30744. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30745. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30746. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30747. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30748. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30749. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30750. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30751. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30752. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30753. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30754. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30755. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30756. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30757. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30758. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30759. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30760. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30761. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30762. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30763. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30764. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30765. // push each facet index in each block containing the vertex
  30766. options.facetPartitioning[block_idx_v1].push(index);
  30767. if (block_idx_v2 != block_idx_v1) {
  30768. options.facetPartitioning[block_idx_v2].push(index);
  30769. }
  30770. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30771. options.facetPartitioning[block_idx_v3].push(index);
  30772. }
  30773. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30774. options.facetPartitioning[block_idx_o].push(index);
  30775. }
  30776. }
  30777. if (computeDepthSort && options && options.facetPositions) {
  30778. var dsf = depthSortedFacets[index];
  30779. dsf.ind = index * 3;
  30780. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30781. }
  30782. // compute the normals anyway
  30783. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30784. normals[v1y] += faceNormaly;
  30785. normals[v1z] += faceNormalz;
  30786. normals[v2x] += faceNormalx;
  30787. normals[v2y] += faceNormaly;
  30788. normals[v2z] += faceNormalz;
  30789. normals[v3x] += faceNormalx;
  30790. normals[v3y] += faceNormaly;
  30791. normals[v3z] += faceNormalz;
  30792. }
  30793. // last normalization of each normal
  30794. for (index = 0; index < normals.length / 3; index++) {
  30795. faceNormalx = normals[index * 3];
  30796. faceNormaly = normals[index * 3 + 1];
  30797. faceNormalz = normals[index * 3 + 2];
  30798. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30799. length = (length === 0) ? 1.0 : length;
  30800. faceNormalx /= length;
  30801. faceNormaly /= length;
  30802. faceNormalz /= length;
  30803. normals[index * 3] = faceNormalx;
  30804. normals[index * 3 + 1] = faceNormaly;
  30805. normals[index * 3 + 2] = faceNormalz;
  30806. }
  30807. };
  30808. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30809. var li = indices.length;
  30810. var ln = normals.length;
  30811. var i;
  30812. var n;
  30813. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30814. switch (sideOrientation) {
  30815. case BABYLON.Mesh.FRONTSIDE:
  30816. // nothing changed
  30817. break;
  30818. case BABYLON.Mesh.BACKSIDE:
  30819. var tmp;
  30820. // indices
  30821. for (i = 0; i < li; i += 3) {
  30822. tmp = indices[i];
  30823. indices[i] = indices[i + 2];
  30824. indices[i + 2] = tmp;
  30825. }
  30826. // normals
  30827. for (n = 0; n < ln; n++) {
  30828. normals[n] = -normals[n];
  30829. }
  30830. break;
  30831. case BABYLON.Mesh.DOUBLESIDE:
  30832. // positions
  30833. var lp = positions.length;
  30834. var l = lp / 3;
  30835. for (var p = 0; p < lp; p++) {
  30836. positions[lp + p] = positions[p];
  30837. }
  30838. // indices
  30839. for (i = 0; i < li; i += 3) {
  30840. indices[i + li] = indices[i + 2] + l;
  30841. indices[i + 1 + li] = indices[i + 1] + l;
  30842. indices[i + 2 + li] = indices[i] + l;
  30843. }
  30844. // normals
  30845. for (n = 0; n < ln; n++) {
  30846. normals[ln + n] = -normals[n];
  30847. }
  30848. // uvs
  30849. var lu = uvs.length;
  30850. var u = 0;
  30851. for (u = 0; u < lu; u++) {
  30852. uvs[u + lu] = uvs[u];
  30853. }
  30854. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30855. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30856. u = 0;
  30857. for (i = 0; i < lu / 2; i++) {
  30858. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30859. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30860. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30861. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30862. u += 2;
  30863. }
  30864. break;
  30865. }
  30866. };
  30867. /**
  30868. * Creates a new VertexData from the imported parameters.
  30869. */
  30870. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30871. var vertexData = new VertexData();
  30872. // positions
  30873. var positions = parsedVertexData.positions;
  30874. if (positions) {
  30875. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30876. }
  30877. // normals
  30878. var normals = parsedVertexData.normals;
  30879. if (normals) {
  30880. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30881. }
  30882. // tangents
  30883. var tangents = parsedVertexData.tangents;
  30884. if (tangents) {
  30885. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30886. }
  30887. // uvs
  30888. var uvs = parsedVertexData.uvs;
  30889. if (uvs) {
  30890. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30891. }
  30892. // uv2s
  30893. var uv2s = parsedVertexData.uv2s;
  30894. if (uv2s) {
  30895. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30896. }
  30897. // uv3s
  30898. var uv3s = parsedVertexData.uv3s;
  30899. if (uv3s) {
  30900. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30901. }
  30902. // uv4s
  30903. var uv4s = parsedVertexData.uv4s;
  30904. if (uv4s) {
  30905. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30906. }
  30907. // uv5s
  30908. var uv5s = parsedVertexData.uv5s;
  30909. if (uv5s) {
  30910. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30911. }
  30912. // uv6s
  30913. var uv6s = parsedVertexData.uv6s;
  30914. if (uv6s) {
  30915. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30916. }
  30917. // colors
  30918. var colors = parsedVertexData.colors;
  30919. if (colors) {
  30920. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30921. }
  30922. // matricesIndices
  30923. var matricesIndices = parsedVertexData.matricesIndices;
  30924. if (matricesIndices) {
  30925. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30926. }
  30927. // matricesWeights
  30928. var matricesWeights = parsedVertexData.matricesWeights;
  30929. if (matricesWeights) {
  30930. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30931. }
  30932. // indices
  30933. var indices = parsedVertexData.indices;
  30934. if (indices) {
  30935. vertexData.indices = indices;
  30936. }
  30937. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30938. };
  30939. return VertexData;
  30940. }());
  30941. BABYLON.VertexData = VertexData;
  30942. })(BABYLON || (BABYLON = {}));
  30943. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30944. var BABYLON;
  30945. (function (BABYLON) {
  30946. var Geometry = /** @class */ (function () {
  30947. function Geometry(id, scene, vertexData, updatable, mesh) {
  30948. if (updatable === void 0) { updatable = false; }
  30949. if (mesh === void 0) { mesh = null; }
  30950. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30951. this._totalVertices = 0;
  30952. this._isDisposed = false;
  30953. this._indexBufferIsUpdatable = false;
  30954. this.id = id;
  30955. this._engine = scene.getEngine();
  30956. this._meshes = [];
  30957. this._scene = scene;
  30958. //Init vertex buffer cache
  30959. this._vertexBuffers = {};
  30960. this._indices = [];
  30961. this._updatable = updatable;
  30962. // vertexData
  30963. if (vertexData) {
  30964. this.setAllVerticesData(vertexData, updatable);
  30965. }
  30966. else {
  30967. this._totalVertices = 0;
  30968. this._indices = [];
  30969. }
  30970. if (this._engine.getCaps().vertexArrayObject) {
  30971. this._vertexArrayObjects = {};
  30972. }
  30973. // applyToMesh
  30974. if (mesh) {
  30975. if (mesh.getClassName() === "LinesMesh") {
  30976. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30977. this.updateExtend();
  30978. }
  30979. this.applyToMesh(mesh);
  30980. mesh.computeWorldMatrix(true);
  30981. }
  30982. }
  30983. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30984. /**
  30985. * 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
  30986. * @returns The Bias Vector
  30987. */
  30988. get: function () {
  30989. return this._boundingBias;
  30990. },
  30991. set: function (value) {
  30992. if (this._boundingBias && this._boundingBias.equals(value)) {
  30993. return;
  30994. }
  30995. this._boundingBias = value.clone();
  30996. this.updateBoundingInfo(true, null);
  30997. },
  30998. enumerable: true,
  30999. configurable: true
  31000. });
  31001. Geometry.CreateGeometryForMesh = function (mesh) {
  31002. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31003. geometry.applyToMesh(mesh);
  31004. return geometry;
  31005. };
  31006. Object.defineProperty(Geometry.prototype, "extend", {
  31007. get: function () {
  31008. return this._extend;
  31009. },
  31010. enumerable: true,
  31011. configurable: true
  31012. });
  31013. Geometry.prototype.getScene = function () {
  31014. return this._scene;
  31015. };
  31016. Geometry.prototype.getEngine = function () {
  31017. return this._engine;
  31018. };
  31019. Geometry.prototype.isReady = function () {
  31020. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31021. };
  31022. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31023. get: function () {
  31024. for (var index = 0; index < this._meshes.length; index++) {
  31025. if (!this._meshes[index].doNotSerialize) {
  31026. return false;
  31027. }
  31028. }
  31029. return true;
  31030. },
  31031. enumerable: true,
  31032. configurable: true
  31033. });
  31034. Geometry.prototype._rebuild = function () {
  31035. if (this._vertexArrayObjects) {
  31036. this._vertexArrayObjects = {};
  31037. }
  31038. // Index buffer
  31039. if (this._meshes.length !== 0 && this._indices) {
  31040. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31041. }
  31042. // Vertex buffers
  31043. for (var key in this._vertexBuffers) {
  31044. var vertexBuffer = this._vertexBuffers[key];
  31045. vertexBuffer._rebuild();
  31046. }
  31047. };
  31048. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31049. vertexData.applyToGeometry(this, updatable);
  31050. this.notifyUpdate();
  31051. };
  31052. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31053. if (updatable === void 0) { updatable = false; }
  31054. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31055. this.setVerticesBuffer(buffer);
  31056. };
  31057. Geometry.prototype.removeVerticesData = function (kind) {
  31058. if (this._vertexBuffers[kind]) {
  31059. this._vertexBuffers[kind].dispose();
  31060. delete this._vertexBuffers[kind];
  31061. }
  31062. };
  31063. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31064. var kind = buffer.getKind();
  31065. if (this._vertexBuffers[kind]) {
  31066. this._vertexBuffers[kind].dispose();
  31067. }
  31068. this._vertexBuffers[kind] = buffer;
  31069. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31070. var data = buffer.getData();
  31071. var stride = buffer.getStrideSize();
  31072. this._totalVertices = data.length / stride;
  31073. this.updateExtend(data, stride);
  31074. this._resetPointsArrayCache();
  31075. var meshes = this._meshes;
  31076. var numOfMeshes = meshes.length;
  31077. for (var index = 0; index < numOfMeshes; index++) {
  31078. var mesh = meshes[index];
  31079. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31080. mesh._createGlobalSubMesh(false);
  31081. mesh.computeWorldMatrix(true);
  31082. }
  31083. }
  31084. this.notifyUpdate(kind);
  31085. if (this._vertexArrayObjects) {
  31086. this._disposeVertexArrayObjects();
  31087. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31088. }
  31089. };
  31090. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31091. var vertexBuffer = this.getVertexBuffer(kind);
  31092. if (!vertexBuffer) {
  31093. return;
  31094. }
  31095. vertexBuffer.updateDirectly(data, offset);
  31096. this.notifyUpdate(kind);
  31097. };
  31098. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31099. if (updateExtends === void 0) { updateExtends = false; }
  31100. var vertexBuffer = this.getVertexBuffer(kind);
  31101. if (!vertexBuffer) {
  31102. return;
  31103. }
  31104. vertexBuffer.update(data);
  31105. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31106. var stride = vertexBuffer.getStrideSize();
  31107. this._totalVertices = data.length / stride;
  31108. this.updateBoundingInfo(updateExtends, data);
  31109. }
  31110. this.notifyUpdate(kind);
  31111. };
  31112. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31113. if (updateExtends) {
  31114. this.updateExtend(data);
  31115. }
  31116. var meshes = this._meshes;
  31117. var numOfMeshes = meshes.length;
  31118. this._resetPointsArrayCache();
  31119. for (var index = 0; index < numOfMeshes; index++) {
  31120. var mesh = meshes[index];
  31121. if (updateExtends) {
  31122. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31123. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31124. var subMesh = mesh.subMeshes[subIndex];
  31125. subMesh.refreshBoundingInfo();
  31126. }
  31127. }
  31128. }
  31129. };
  31130. Geometry.prototype._bind = function (effect, indexToBind) {
  31131. if (!effect) {
  31132. return;
  31133. }
  31134. if (indexToBind === undefined) {
  31135. indexToBind = this._indexBuffer;
  31136. }
  31137. var vbs = this.getVertexBuffers();
  31138. if (!vbs) {
  31139. return;
  31140. }
  31141. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31142. this._engine.bindBuffers(vbs, indexToBind, effect);
  31143. return;
  31144. }
  31145. // Using VAO
  31146. if (!this._vertexArrayObjects[effect.key]) {
  31147. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31148. }
  31149. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31150. };
  31151. Geometry.prototype.getTotalVertices = function () {
  31152. if (!this.isReady()) {
  31153. return 0;
  31154. }
  31155. return this._totalVertices;
  31156. };
  31157. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31158. var vertexBuffer = this.getVertexBuffer(kind);
  31159. if (!vertexBuffer) {
  31160. return null;
  31161. }
  31162. var orig = vertexBuffer.getData();
  31163. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31164. return orig;
  31165. }
  31166. else {
  31167. var len = orig.length;
  31168. var copy = [];
  31169. for (var i = 0; i < len; i++) {
  31170. copy.push(orig[i]);
  31171. }
  31172. return copy;
  31173. }
  31174. };
  31175. /**
  31176. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31177. * Possible `kind` values :
  31178. * - BABYLON.VertexBuffer.PositionKind
  31179. * - BABYLON.VertexBuffer.UVKind
  31180. * - BABYLON.VertexBuffer.UV2Kind
  31181. * - BABYLON.VertexBuffer.UV3Kind
  31182. * - BABYLON.VertexBuffer.UV4Kind
  31183. * - BABYLON.VertexBuffer.UV5Kind
  31184. * - BABYLON.VertexBuffer.UV6Kind
  31185. * - BABYLON.VertexBuffer.ColorKind
  31186. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31187. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31188. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31189. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31190. */
  31191. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31192. var vb = this._vertexBuffers[kind];
  31193. if (!vb) {
  31194. return false;
  31195. }
  31196. return vb.isUpdatable();
  31197. };
  31198. Geometry.prototype.getVertexBuffer = function (kind) {
  31199. if (!this.isReady()) {
  31200. return null;
  31201. }
  31202. return this._vertexBuffers[kind];
  31203. };
  31204. Geometry.prototype.getVertexBuffers = function () {
  31205. if (!this.isReady()) {
  31206. return null;
  31207. }
  31208. return this._vertexBuffers;
  31209. };
  31210. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31211. if (!this._vertexBuffers) {
  31212. if (this._delayInfo) {
  31213. return this._delayInfo.indexOf(kind) !== -1;
  31214. }
  31215. return false;
  31216. }
  31217. return this._vertexBuffers[kind] !== undefined;
  31218. };
  31219. Geometry.prototype.getVerticesDataKinds = function () {
  31220. var result = [];
  31221. var kind;
  31222. if (!this._vertexBuffers && this._delayInfo) {
  31223. for (kind in this._delayInfo) {
  31224. result.push(kind);
  31225. }
  31226. }
  31227. else {
  31228. for (kind in this._vertexBuffers) {
  31229. result.push(kind);
  31230. }
  31231. }
  31232. return result;
  31233. };
  31234. Geometry.prototype.updateIndices = function (indices, offset) {
  31235. if (!this._indexBuffer) {
  31236. return;
  31237. }
  31238. if (!this._indexBufferIsUpdatable) {
  31239. this.setIndices(indices, null, true);
  31240. }
  31241. else {
  31242. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31243. }
  31244. };
  31245. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31246. if (totalVertices === void 0) { totalVertices = null; }
  31247. if (updatable === void 0) { updatable = false; }
  31248. if (this._indexBuffer) {
  31249. this._engine._releaseBuffer(this._indexBuffer);
  31250. }
  31251. this._disposeVertexArrayObjects();
  31252. this._indices = indices;
  31253. this._indexBufferIsUpdatable = updatable;
  31254. if (this._meshes.length !== 0 && this._indices) {
  31255. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31256. }
  31257. if (totalVertices != undefined) {
  31258. this._totalVertices = totalVertices;
  31259. }
  31260. var meshes = this._meshes;
  31261. var numOfMeshes = meshes.length;
  31262. for (var index = 0; index < numOfMeshes; index++) {
  31263. meshes[index]._createGlobalSubMesh(true);
  31264. }
  31265. this.notifyUpdate();
  31266. };
  31267. Geometry.prototype.getTotalIndices = function () {
  31268. if (!this.isReady()) {
  31269. return 0;
  31270. }
  31271. return this._indices.length;
  31272. };
  31273. Geometry.prototype.getIndices = function (copyWhenShared) {
  31274. if (!this.isReady()) {
  31275. return null;
  31276. }
  31277. var orig = this._indices;
  31278. if (!copyWhenShared || this._meshes.length === 1) {
  31279. return orig;
  31280. }
  31281. else {
  31282. var len = orig.length;
  31283. var copy = [];
  31284. for (var i = 0; i < len; i++) {
  31285. copy.push(orig[i]);
  31286. }
  31287. return copy;
  31288. }
  31289. };
  31290. Geometry.prototype.getIndexBuffer = function () {
  31291. if (!this.isReady()) {
  31292. return null;
  31293. }
  31294. return this._indexBuffer;
  31295. };
  31296. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31297. if (effect === void 0) { effect = null; }
  31298. if (!effect || !this._vertexArrayObjects) {
  31299. return;
  31300. }
  31301. if (this._vertexArrayObjects[effect.key]) {
  31302. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31303. delete this._vertexArrayObjects[effect.key];
  31304. }
  31305. };
  31306. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31307. var meshes = this._meshes;
  31308. var index = meshes.indexOf(mesh);
  31309. if (index === -1) {
  31310. return;
  31311. }
  31312. meshes.splice(index, 1);
  31313. mesh._geometry = null;
  31314. if (meshes.length === 0 && shouldDispose) {
  31315. this.dispose();
  31316. }
  31317. };
  31318. Geometry.prototype.applyToMesh = function (mesh) {
  31319. if (mesh._geometry === this) {
  31320. return;
  31321. }
  31322. var previousGeometry = mesh._geometry;
  31323. if (previousGeometry) {
  31324. previousGeometry.releaseForMesh(mesh);
  31325. }
  31326. var meshes = this._meshes;
  31327. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31328. mesh._geometry = this;
  31329. this._scene.pushGeometry(this);
  31330. meshes.push(mesh);
  31331. if (this.isReady()) {
  31332. this._applyToMesh(mesh);
  31333. }
  31334. else {
  31335. mesh._boundingInfo = this._boundingInfo;
  31336. }
  31337. };
  31338. Geometry.prototype.updateExtend = function (data, stride) {
  31339. if (data === void 0) { data = null; }
  31340. if (!data) {
  31341. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31342. }
  31343. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31344. };
  31345. Geometry.prototype._applyToMesh = function (mesh) {
  31346. var numOfMeshes = this._meshes.length;
  31347. // vertexBuffers
  31348. for (var kind in this._vertexBuffers) {
  31349. if (numOfMeshes === 1) {
  31350. this._vertexBuffers[kind].create();
  31351. }
  31352. var buffer = this._vertexBuffers[kind].getBuffer();
  31353. if (buffer)
  31354. buffer.references = numOfMeshes;
  31355. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31356. if (!this._extend) {
  31357. this.updateExtend(this._vertexBuffers[kind].getData());
  31358. }
  31359. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31360. mesh._createGlobalSubMesh(false);
  31361. //bounding info was just created again, world matrix should be applied again.
  31362. mesh._updateBoundingInfo();
  31363. }
  31364. }
  31365. // indexBuffer
  31366. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31367. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31368. }
  31369. if (this._indexBuffer) {
  31370. this._indexBuffer.references = numOfMeshes;
  31371. }
  31372. };
  31373. Geometry.prototype.notifyUpdate = function (kind) {
  31374. if (this.onGeometryUpdated) {
  31375. this.onGeometryUpdated(this, kind);
  31376. }
  31377. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31378. var mesh = _a[_i];
  31379. mesh._markSubMeshesAsAttributesDirty();
  31380. }
  31381. };
  31382. Geometry.prototype.load = function (scene, onLoaded) {
  31383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31384. return;
  31385. }
  31386. if (this.isReady()) {
  31387. if (onLoaded) {
  31388. onLoaded();
  31389. }
  31390. return;
  31391. }
  31392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31393. this._queueLoad(scene, onLoaded);
  31394. };
  31395. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31396. var _this = this;
  31397. if (!this.delayLoadingFile) {
  31398. return;
  31399. }
  31400. scene._addPendingData(this);
  31401. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31402. if (!_this._delayLoadingFunction) {
  31403. return;
  31404. }
  31405. _this._delayLoadingFunction(JSON.parse(data), _this);
  31406. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31407. _this._delayInfo = [];
  31408. scene._removePendingData(_this);
  31409. var meshes = _this._meshes;
  31410. var numOfMeshes = meshes.length;
  31411. for (var index = 0; index < numOfMeshes; index++) {
  31412. _this._applyToMesh(meshes[index]);
  31413. }
  31414. if (onLoaded) {
  31415. onLoaded();
  31416. }
  31417. }, function () { }, scene.database);
  31418. };
  31419. /**
  31420. * Invert the geometry to move from a right handed system to a left handed one.
  31421. */
  31422. Geometry.prototype.toLeftHanded = function () {
  31423. // Flip faces
  31424. var tIndices = this.getIndices(false);
  31425. if (tIndices != null && tIndices.length > 0) {
  31426. for (var i = 0; i < tIndices.length; i += 3) {
  31427. var tTemp = tIndices[i + 0];
  31428. tIndices[i + 0] = tIndices[i + 2];
  31429. tIndices[i + 2] = tTemp;
  31430. }
  31431. this.setIndices(tIndices);
  31432. }
  31433. // Negate position.z
  31434. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31435. if (tPositions != null && tPositions.length > 0) {
  31436. for (var i = 0; i < tPositions.length; i += 3) {
  31437. tPositions[i + 2] = -tPositions[i + 2];
  31438. }
  31439. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31440. }
  31441. // Negate normal.z
  31442. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31443. if (tNormals != null && tNormals.length > 0) {
  31444. for (var i = 0; i < tNormals.length; i += 3) {
  31445. tNormals[i + 2] = -tNormals[i + 2];
  31446. }
  31447. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31448. }
  31449. };
  31450. // Cache
  31451. Geometry.prototype._resetPointsArrayCache = function () {
  31452. this._positions = null;
  31453. };
  31454. Geometry.prototype._generatePointsArray = function () {
  31455. if (this._positions)
  31456. return true;
  31457. this._positions = [];
  31458. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31459. if (!data) {
  31460. return false;
  31461. }
  31462. for (var index = 0; index < data.length; index += 3) {
  31463. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31464. }
  31465. return true;
  31466. };
  31467. Geometry.prototype.isDisposed = function () {
  31468. return this._isDisposed;
  31469. };
  31470. Geometry.prototype._disposeVertexArrayObjects = function () {
  31471. if (this._vertexArrayObjects) {
  31472. for (var kind in this._vertexArrayObjects) {
  31473. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31474. }
  31475. this._vertexArrayObjects = {};
  31476. }
  31477. };
  31478. Geometry.prototype.dispose = function () {
  31479. var meshes = this._meshes;
  31480. var numOfMeshes = meshes.length;
  31481. var index;
  31482. for (index = 0; index < numOfMeshes; index++) {
  31483. this.releaseForMesh(meshes[index]);
  31484. }
  31485. this._meshes = [];
  31486. this._disposeVertexArrayObjects();
  31487. for (var kind in this._vertexBuffers) {
  31488. this._vertexBuffers[kind].dispose();
  31489. }
  31490. this._vertexBuffers = {};
  31491. this._totalVertices = 0;
  31492. if (this._indexBuffer) {
  31493. this._engine._releaseBuffer(this._indexBuffer);
  31494. }
  31495. this._indexBuffer = null;
  31496. this._indices = [];
  31497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31498. this.delayLoadingFile = null;
  31499. this._delayLoadingFunction = null;
  31500. this._delayInfo = [];
  31501. this._boundingInfo = null;
  31502. this._scene.removeGeometry(this);
  31503. this._isDisposed = true;
  31504. };
  31505. Geometry.prototype.copy = function (id) {
  31506. var vertexData = new BABYLON.VertexData();
  31507. vertexData.indices = [];
  31508. var indices = this.getIndices();
  31509. if (indices) {
  31510. for (var index = 0; index < indices.length; index++) {
  31511. vertexData.indices.push(indices[index]);
  31512. }
  31513. }
  31514. var updatable = false;
  31515. var stopChecking = false;
  31516. var kind;
  31517. for (kind in this._vertexBuffers) {
  31518. // using slice() to make a copy of the array and not just reference it
  31519. var data = this.getVerticesData(kind);
  31520. if (data instanceof Float32Array) {
  31521. vertexData.set(new Float32Array(data), kind);
  31522. }
  31523. else {
  31524. vertexData.set(data.slice(0), kind);
  31525. }
  31526. if (!stopChecking) {
  31527. var vb = this.getVertexBuffer(kind);
  31528. if (vb) {
  31529. updatable = vb.isUpdatable();
  31530. stopChecking = !updatable;
  31531. }
  31532. }
  31533. }
  31534. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31535. geometry.delayLoadState = this.delayLoadState;
  31536. geometry.delayLoadingFile = this.delayLoadingFile;
  31537. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31538. for (kind in this._delayInfo) {
  31539. geometry._delayInfo = geometry._delayInfo || [];
  31540. geometry._delayInfo.push(kind);
  31541. }
  31542. // Bounding info
  31543. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31544. return geometry;
  31545. };
  31546. Geometry.prototype.serialize = function () {
  31547. var serializationObject = {};
  31548. serializationObject.id = this.id;
  31549. serializationObject.updatable = this._updatable;
  31550. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31551. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31552. }
  31553. return serializationObject;
  31554. };
  31555. Geometry.prototype.toNumberArray = function (origin) {
  31556. if (Array.isArray(origin)) {
  31557. return origin;
  31558. }
  31559. else {
  31560. return Array.prototype.slice.call(origin);
  31561. }
  31562. };
  31563. Geometry.prototype.serializeVerticeData = function () {
  31564. var serializationObject = this.serialize();
  31565. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31566. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31567. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31568. serializationObject.positions._updatable = true;
  31569. }
  31570. }
  31571. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31572. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31573. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31574. serializationObject.normals._updatable = true;
  31575. }
  31576. }
  31577. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31578. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31579. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31580. serializationObject.uvs._updatable = true;
  31581. }
  31582. }
  31583. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31584. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31585. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31586. serializationObject.uv2s._updatable = true;
  31587. }
  31588. }
  31589. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31590. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31591. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31592. serializationObject.uv3s._updatable = true;
  31593. }
  31594. }
  31595. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31596. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31597. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31598. serializationObject.uv4s._updatable = true;
  31599. }
  31600. }
  31601. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31602. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31603. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31604. serializationObject.uv5s._updatable = true;
  31605. }
  31606. }
  31607. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31608. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31609. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31610. serializationObject.uv6s._updatable = true;
  31611. }
  31612. }
  31613. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31614. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31615. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31616. serializationObject.colors._updatable = true;
  31617. }
  31618. }
  31619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31620. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31621. serializationObject.matricesIndices._isExpanded = true;
  31622. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31623. serializationObject.matricesIndices._updatable = true;
  31624. }
  31625. }
  31626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31627. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31628. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31629. serializationObject.matricesWeights._updatable = true;
  31630. }
  31631. }
  31632. serializationObject.indices = this.toNumberArray(this.getIndices());
  31633. return serializationObject;
  31634. };
  31635. // Statics
  31636. Geometry.ExtractFromMesh = function (mesh, id) {
  31637. var geometry = mesh._geometry;
  31638. if (!geometry) {
  31639. return null;
  31640. }
  31641. return geometry.copy(id);
  31642. };
  31643. /**
  31644. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31645. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31646. * Be aware Math.random() could cause collisions, but:
  31647. * "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"
  31648. */
  31649. Geometry.RandomId = function () {
  31650. return BABYLON.Tools.RandomId();
  31651. };
  31652. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31653. var scene = mesh.getScene();
  31654. // Geometry
  31655. var geometryId = parsedGeometry.geometryId;
  31656. if (geometryId) {
  31657. var geometry = scene.getGeometryByID(geometryId);
  31658. if (geometry) {
  31659. geometry.applyToMesh(mesh);
  31660. }
  31661. }
  31662. else if (parsedGeometry instanceof ArrayBuffer) {
  31663. var binaryInfo = mesh._binaryInfo;
  31664. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31665. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31666. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31667. }
  31668. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31669. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31670. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31671. }
  31672. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31673. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31674. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31675. }
  31676. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31677. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31678. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31679. }
  31680. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31681. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31682. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31683. }
  31684. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31685. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31686. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31687. }
  31688. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31689. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31690. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31691. }
  31692. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31693. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31694. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31695. }
  31696. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31697. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31698. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31699. }
  31700. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31701. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31702. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31703. }
  31704. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31705. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31707. }
  31708. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31709. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31710. mesh.setIndices(indicesData, null);
  31711. }
  31712. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31713. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31714. mesh.subMeshes = [];
  31715. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31716. var materialIndex = subMeshesData[(i * 5) + 0];
  31717. var verticesStart = subMeshesData[(i * 5) + 1];
  31718. var verticesCount = subMeshesData[(i * 5) + 2];
  31719. var indexStart = subMeshesData[(i * 5) + 3];
  31720. var indexCount = subMeshesData[(i * 5) + 4];
  31721. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31722. }
  31723. }
  31724. }
  31725. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31726. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31727. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31728. if (parsedGeometry.uvs) {
  31729. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31730. }
  31731. if (parsedGeometry.uvs2) {
  31732. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31733. }
  31734. if (parsedGeometry.uvs3) {
  31735. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31736. }
  31737. if (parsedGeometry.uvs4) {
  31738. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31739. }
  31740. if (parsedGeometry.uvs5) {
  31741. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31742. }
  31743. if (parsedGeometry.uvs6) {
  31744. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31745. }
  31746. if (parsedGeometry.colors) {
  31747. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31748. }
  31749. if (parsedGeometry.matricesIndices) {
  31750. if (!parsedGeometry.matricesIndices._isExpanded) {
  31751. var floatIndices = [];
  31752. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31753. var matricesIndex = parsedGeometry.matricesIndices[i];
  31754. floatIndices.push(matricesIndex & 0x000000FF);
  31755. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31756. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31757. floatIndices.push(matricesIndex >> 24);
  31758. }
  31759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31760. }
  31761. else {
  31762. delete parsedGeometry.matricesIndices._isExpanded;
  31763. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31764. }
  31765. }
  31766. if (parsedGeometry.matricesIndicesExtra) {
  31767. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31768. var floatIndices = [];
  31769. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31770. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31771. floatIndices.push(matricesIndex & 0x000000FF);
  31772. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31773. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31774. floatIndices.push(matricesIndex >> 24);
  31775. }
  31776. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31777. }
  31778. else {
  31779. delete parsedGeometry.matricesIndices._isExpanded;
  31780. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31781. }
  31782. }
  31783. if (parsedGeometry.matricesWeights) {
  31784. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31785. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31786. }
  31787. if (parsedGeometry.matricesWeightsExtra) {
  31788. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31789. }
  31790. mesh.setIndices(parsedGeometry.indices, null);
  31791. }
  31792. // SubMeshes
  31793. if (parsedGeometry.subMeshes) {
  31794. mesh.subMeshes = [];
  31795. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31796. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31797. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31798. }
  31799. }
  31800. // Flat shading
  31801. if (mesh._shouldGenerateFlatShading) {
  31802. mesh.convertToFlatShadedMesh();
  31803. delete mesh._shouldGenerateFlatShading;
  31804. }
  31805. // Update
  31806. mesh.computeWorldMatrix(true);
  31807. // Octree
  31808. if (scene['_selectionOctree']) {
  31809. scene['_selectionOctree'].addMesh(mesh);
  31810. }
  31811. };
  31812. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31813. var epsilon = 1e-3;
  31814. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31815. return;
  31816. }
  31817. var noInfluenceBoneIndex = 0.0;
  31818. if (parsedGeometry.skeletonId > -1) {
  31819. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31820. if (!skeleton) {
  31821. return;
  31822. }
  31823. noInfluenceBoneIndex = skeleton.bones.length;
  31824. }
  31825. else {
  31826. return;
  31827. }
  31828. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31829. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31830. var matricesWeights = parsedGeometry.matricesWeights;
  31831. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31832. var influencers = parsedGeometry.numBoneInfluencer;
  31833. var size = matricesWeights.length;
  31834. for (var i = 0; i < size; i += 4) {
  31835. var weight = 0.0;
  31836. var firstZeroWeight = -1;
  31837. for (var j = 0; j < 4; j++) {
  31838. var w = matricesWeights[i + j];
  31839. weight += w;
  31840. if (w < epsilon && firstZeroWeight < 0) {
  31841. firstZeroWeight = j;
  31842. }
  31843. }
  31844. if (matricesWeightsExtra) {
  31845. for (var j = 0; j < 4; j++) {
  31846. var w = matricesWeightsExtra[i + j];
  31847. weight += w;
  31848. if (w < epsilon && firstZeroWeight < 0) {
  31849. firstZeroWeight = j + 4;
  31850. }
  31851. }
  31852. }
  31853. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31854. firstZeroWeight = influencers - 1;
  31855. }
  31856. if (weight > epsilon) {
  31857. var mweight = 1.0 / weight;
  31858. for (var j = 0; j < 4; j++) {
  31859. matricesWeights[i + j] *= mweight;
  31860. }
  31861. if (matricesWeightsExtra) {
  31862. for (var j = 0; j < 4; j++) {
  31863. matricesWeightsExtra[i + j] *= mweight;
  31864. }
  31865. }
  31866. }
  31867. else {
  31868. if (firstZeroWeight >= 4) {
  31869. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31870. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31871. }
  31872. else {
  31873. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31874. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31875. }
  31876. }
  31877. }
  31878. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31879. if (parsedGeometry.matricesWeightsExtra) {
  31880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31881. }
  31882. };
  31883. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31884. if (scene.getGeometryByID(parsedVertexData.id)) {
  31885. return null; // null since geometry could be something else than a box...
  31886. }
  31887. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31888. if (BABYLON.Tags) {
  31889. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31890. }
  31891. if (parsedVertexData.delayLoadingFile) {
  31892. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31893. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31894. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31895. geometry._delayInfo = [];
  31896. if (parsedVertexData.hasUVs) {
  31897. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31898. }
  31899. if (parsedVertexData.hasUVs2) {
  31900. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31901. }
  31902. if (parsedVertexData.hasUVs3) {
  31903. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31904. }
  31905. if (parsedVertexData.hasUVs4) {
  31906. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31907. }
  31908. if (parsedVertexData.hasUVs5) {
  31909. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31910. }
  31911. if (parsedVertexData.hasUVs6) {
  31912. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31913. }
  31914. if (parsedVertexData.hasColors) {
  31915. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31916. }
  31917. if (parsedVertexData.hasMatricesIndices) {
  31918. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31919. }
  31920. if (parsedVertexData.hasMatricesWeights) {
  31921. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31922. }
  31923. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31924. }
  31925. else {
  31926. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31927. }
  31928. scene.pushGeometry(geometry, true);
  31929. return geometry;
  31930. };
  31931. return Geometry;
  31932. }());
  31933. BABYLON.Geometry = Geometry;
  31934. /////// Primitives //////////////////////////////////////////////
  31935. (function (Geometry) {
  31936. var Primitives;
  31937. (function (Primitives) {
  31938. /// Abstract class
  31939. var _Primitive = /** @class */ (function (_super) {
  31940. __extends(_Primitive, _super);
  31941. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31942. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31943. if (mesh === void 0) { mesh = null; }
  31944. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31945. _this._canBeRegenerated = _canBeRegenerated;
  31946. _this._beingRegenerated = true;
  31947. _this.regenerate();
  31948. _this._beingRegenerated = false;
  31949. return _this;
  31950. }
  31951. _Primitive.prototype.canBeRegenerated = function () {
  31952. return this._canBeRegenerated;
  31953. };
  31954. _Primitive.prototype.regenerate = function () {
  31955. if (!this._canBeRegenerated) {
  31956. return;
  31957. }
  31958. this._beingRegenerated = true;
  31959. this.setAllVerticesData(this._regenerateVertexData(), false);
  31960. this._beingRegenerated = false;
  31961. };
  31962. _Primitive.prototype.asNewGeometry = function (id) {
  31963. return _super.prototype.copy.call(this, id);
  31964. };
  31965. // overrides
  31966. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31967. if (!this._beingRegenerated) {
  31968. return;
  31969. }
  31970. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31971. };
  31972. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31973. if (!this._beingRegenerated) {
  31974. return;
  31975. }
  31976. _super.prototype.setVerticesData.call(this, kind, data, false);
  31977. };
  31978. // to override
  31979. // protected
  31980. _Primitive.prototype._regenerateVertexData = function () {
  31981. throw new Error("Abstract method");
  31982. };
  31983. _Primitive.prototype.copy = function (id) {
  31984. throw new Error("Must be overriden in sub-classes.");
  31985. };
  31986. _Primitive.prototype.serialize = function () {
  31987. var serializationObject = _super.prototype.serialize.call(this);
  31988. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31989. return serializationObject;
  31990. };
  31991. return _Primitive;
  31992. }(Geometry));
  31993. Primitives._Primitive = _Primitive;
  31994. var Ribbon = /** @class */ (function (_super) {
  31995. __extends(Ribbon, _super);
  31996. // Members
  31997. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31998. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31999. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32000. _this.pathArray = pathArray;
  32001. _this.closeArray = closeArray;
  32002. _this.closePath = closePath;
  32003. _this.offset = offset;
  32004. _this.side = side;
  32005. return _this;
  32006. }
  32007. Ribbon.prototype._regenerateVertexData = function () {
  32008. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32009. };
  32010. Ribbon.prototype.copy = function (id) {
  32011. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32012. };
  32013. return Ribbon;
  32014. }(_Primitive));
  32015. Primitives.Ribbon = Ribbon;
  32016. var Box = /** @class */ (function (_super) {
  32017. __extends(Box, _super);
  32018. // Members
  32019. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32020. if (mesh === void 0) { mesh = null; }
  32021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32023. _this.size = size;
  32024. _this.side = side;
  32025. return _this;
  32026. }
  32027. Box.prototype._regenerateVertexData = function () {
  32028. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32029. };
  32030. Box.prototype.copy = function (id) {
  32031. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32032. };
  32033. Box.prototype.serialize = function () {
  32034. var serializationObject = _super.prototype.serialize.call(this);
  32035. serializationObject.size = this.size;
  32036. return serializationObject;
  32037. };
  32038. Box.Parse = function (parsedBox, scene) {
  32039. if (scene.getGeometryByID(parsedBox.id)) {
  32040. return null; // null since geometry could be something else than a box...
  32041. }
  32042. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32043. if (BABYLON.Tags) {
  32044. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32045. }
  32046. scene.pushGeometry(box, true);
  32047. return box;
  32048. };
  32049. return Box;
  32050. }(_Primitive));
  32051. Primitives.Box = Box;
  32052. var Sphere = /** @class */ (function (_super) {
  32053. __extends(Sphere, _super);
  32054. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32055. if (mesh === void 0) { mesh = null; }
  32056. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32057. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32058. _this.segments = segments;
  32059. _this.diameter = diameter;
  32060. _this.side = side;
  32061. return _this;
  32062. }
  32063. Sphere.prototype._regenerateVertexData = function () {
  32064. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32065. };
  32066. Sphere.prototype.copy = function (id) {
  32067. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32068. };
  32069. Sphere.prototype.serialize = function () {
  32070. var serializationObject = _super.prototype.serialize.call(this);
  32071. serializationObject.segments = this.segments;
  32072. serializationObject.diameter = this.diameter;
  32073. return serializationObject;
  32074. };
  32075. Sphere.Parse = function (parsedSphere, scene) {
  32076. if (scene.getGeometryByID(parsedSphere.id)) {
  32077. return null; // null since geometry could be something else than a sphere...
  32078. }
  32079. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32080. if (BABYLON.Tags) {
  32081. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32082. }
  32083. scene.pushGeometry(sphere, true);
  32084. return sphere;
  32085. };
  32086. return Sphere;
  32087. }(_Primitive));
  32088. Primitives.Sphere = Sphere;
  32089. var Disc = /** @class */ (function (_super) {
  32090. __extends(Disc, _super);
  32091. // Members
  32092. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32093. if (mesh === void 0) { mesh = null; }
  32094. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32095. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32096. _this.radius = radius;
  32097. _this.tessellation = tessellation;
  32098. _this.side = side;
  32099. return _this;
  32100. }
  32101. Disc.prototype._regenerateVertexData = function () {
  32102. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32103. };
  32104. Disc.prototype.copy = function (id) {
  32105. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32106. };
  32107. return Disc;
  32108. }(_Primitive));
  32109. Primitives.Disc = Disc;
  32110. var Cylinder = /** @class */ (function (_super) {
  32111. __extends(Cylinder, _super);
  32112. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32113. if (subdivisions === void 0) { subdivisions = 1; }
  32114. if (mesh === void 0) { mesh = null; }
  32115. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32116. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32117. _this.height = height;
  32118. _this.diameterTop = diameterTop;
  32119. _this.diameterBottom = diameterBottom;
  32120. _this.tessellation = tessellation;
  32121. _this.subdivisions = subdivisions;
  32122. _this.side = side;
  32123. return _this;
  32124. }
  32125. Cylinder.prototype._regenerateVertexData = function () {
  32126. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32127. };
  32128. Cylinder.prototype.copy = function (id) {
  32129. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32130. };
  32131. Cylinder.prototype.serialize = function () {
  32132. var serializationObject = _super.prototype.serialize.call(this);
  32133. serializationObject.height = this.height;
  32134. serializationObject.diameterTop = this.diameterTop;
  32135. serializationObject.diameterBottom = this.diameterBottom;
  32136. serializationObject.tessellation = this.tessellation;
  32137. return serializationObject;
  32138. };
  32139. Cylinder.Parse = function (parsedCylinder, scene) {
  32140. if (scene.getGeometryByID(parsedCylinder.id)) {
  32141. return null; // null since geometry could be something else than a cylinder...
  32142. }
  32143. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32144. if (BABYLON.Tags) {
  32145. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32146. }
  32147. scene.pushGeometry(cylinder, true);
  32148. return cylinder;
  32149. };
  32150. return Cylinder;
  32151. }(_Primitive));
  32152. Primitives.Cylinder = Cylinder;
  32153. var Torus = /** @class */ (function (_super) {
  32154. __extends(Torus, _super);
  32155. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32156. if (mesh === void 0) { mesh = null; }
  32157. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32158. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32159. _this.diameter = diameter;
  32160. _this.thickness = thickness;
  32161. _this.tessellation = tessellation;
  32162. _this.side = side;
  32163. return _this;
  32164. }
  32165. Torus.prototype._regenerateVertexData = function () {
  32166. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32167. };
  32168. Torus.prototype.copy = function (id) {
  32169. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32170. };
  32171. Torus.prototype.serialize = function () {
  32172. var serializationObject = _super.prototype.serialize.call(this);
  32173. serializationObject.diameter = this.diameter;
  32174. serializationObject.thickness = this.thickness;
  32175. serializationObject.tessellation = this.tessellation;
  32176. return serializationObject;
  32177. };
  32178. Torus.Parse = function (parsedTorus, scene) {
  32179. if (scene.getGeometryByID(parsedTorus.id)) {
  32180. return null; // null since geometry could be something else than a torus...
  32181. }
  32182. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32183. if (BABYLON.Tags) {
  32184. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32185. }
  32186. scene.pushGeometry(torus, true);
  32187. return torus;
  32188. };
  32189. return Torus;
  32190. }(_Primitive));
  32191. Primitives.Torus = Torus;
  32192. var Ground = /** @class */ (function (_super) {
  32193. __extends(Ground, _super);
  32194. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32195. if (mesh === void 0) { mesh = null; }
  32196. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32197. _this.width = width;
  32198. _this.height = height;
  32199. _this.subdivisions = subdivisions;
  32200. return _this;
  32201. }
  32202. Ground.prototype._regenerateVertexData = function () {
  32203. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32204. };
  32205. Ground.prototype.copy = function (id) {
  32206. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32207. };
  32208. Ground.prototype.serialize = function () {
  32209. var serializationObject = _super.prototype.serialize.call(this);
  32210. serializationObject.width = this.width;
  32211. serializationObject.height = this.height;
  32212. serializationObject.subdivisions = this.subdivisions;
  32213. return serializationObject;
  32214. };
  32215. Ground.Parse = function (parsedGround, scene) {
  32216. if (scene.getGeometryByID(parsedGround.id)) {
  32217. return null; // null since geometry could be something else than a ground...
  32218. }
  32219. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32220. if (BABYLON.Tags) {
  32221. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32222. }
  32223. scene.pushGeometry(ground, true);
  32224. return ground;
  32225. };
  32226. return Ground;
  32227. }(_Primitive));
  32228. Primitives.Ground = Ground;
  32229. var TiledGround = /** @class */ (function (_super) {
  32230. __extends(TiledGround, _super);
  32231. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32232. if (mesh === void 0) { mesh = null; }
  32233. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32234. _this.xmin = xmin;
  32235. _this.zmin = zmin;
  32236. _this.xmax = xmax;
  32237. _this.zmax = zmax;
  32238. _this.subdivisions = subdivisions;
  32239. _this.precision = precision;
  32240. return _this;
  32241. }
  32242. TiledGround.prototype._regenerateVertexData = function () {
  32243. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32244. };
  32245. TiledGround.prototype.copy = function (id) {
  32246. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32247. };
  32248. return TiledGround;
  32249. }(_Primitive));
  32250. Primitives.TiledGround = TiledGround;
  32251. var Plane = /** @class */ (function (_super) {
  32252. __extends(Plane, _super);
  32253. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32254. if (mesh === void 0) { mesh = null; }
  32255. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32256. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32257. _this.size = size;
  32258. _this.side = side;
  32259. return _this;
  32260. }
  32261. Plane.prototype._regenerateVertexData = function () {
  32262. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32263. };
  32264. Plane.prototype.copy = function (id) {
  32265. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32266. };
  32267. Plane.prototype.serialize = function () {
  32268. var serializationObject = _super.prototype.serialize.call(this);
  32269. serializationObject.size = this.size;
  32270. return serializationObject;
  32271. };
  32272. Plane.Parse = function (parsedPlane, scene) {
  32273. if (scene.getGeometryByID(parsedPlane.id)) {
  32274. return null; // null since geometry could be something else than a ground...
  32275. }
  32276. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32277. if (BABYLON.Tags) {
  32278. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32279. }
  32280. scene.pushGeometry(plane, true);
  32281. return plane;
  32282. };
  32283. return Plane;
  32284. }(_Primitive));
  32285. Primitives.Plane = Plane;
  32286. var TorusKnot = /** @class */ (function (_super) {
  32287. __extends(TorusKnot, _super);
  32288. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32289. if (mesh === void 0) { mesh = null; }
  32290. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32291. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32292. _this.radius = radius;
  32293. _this.tube = tube;
  32294. _this.radialSegments = radialSegments;
  32295. _this.tubularSegments = tubularSegments;
  32296. _this.p = p;
  32297. _this.q = q;
  32298. _this.side = side;
  32299. return _this;
  32300. }
  32301. TorusKnot.prototype._regenerateVertexData = function () {
  32302. 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 });
  32303. };
  32304. TorusKnot.prototype.copy = function (id) {
  32305. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32306. };
  32307. TorusKnot.prototype.serialize = function () {
  32308. var serializationObject = _super.prototype.serialize.call(this);
  32309. serializationObject.radius = this.radius;
  32310. serializationObject.tube = this.tube;
  32311. serializationObject.radialSegments = this.radialSegments;
  32312. serializationObject.tubularSegments = this.tubularSegments;
  32313. serializationObject.p = this.p;
  32314. serializationObject.q = this.q;
  32315. return serializationObject;
  32316. };
  32317. ;
  32318. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32319. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32320. return null; // null since geometry could be something else than a ground...
  32321. }
  32322. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32323. if (BABYLON.Tags) {
  32324. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32325. }
  32326. scene.pushGeometry(torusKnot, true);
  32327. return torusKnot;
  32328. };
  32329. return TorusKnot;
  32330. }(_Primitive));
  32331. Primitives.TorusKnot = TorusKnot;
  32332. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32333. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32334. })(BABYLON || (BABYLON = {}));
  32335. //# sourceMappingURL=babylon.geometry.js.map
  32336. var BABYLON;
  32337. (function (BABYLON) {
  32338. var PostProcessManager = /** @class */ (function () {
  32339. function PostProcessManager(scene) {
  32340. this._vertexBuffers = {};
  32341. this._scene = scene;
  32342. }
  32343. PostProcessManager.prototype._prepareBuffers = function () {
  32344. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32345. return;
  32346. }
  32347. // VBO
  32348. var vertices = [];
  32349. vertices.push(1, 1);
  32350. vertices.push(-1, 1);
  32351. vertices.push(-1, -1);
  32352. vertices.push(1, -1);
  32353. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32354. this._buildIndexBuffer();
  32355. };
  32356. PostProcessManager.prototype._buildIndexBuffer = function () {
  32357. // Indices
  32358. var indices = [];
  32359. indices.push(0);
  32360. indices.push(1);
  32361. indices.push(2);
  32362. indices.push(0);
  32363. indices.push(2);
  32364. indices.push(3);
  32365. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32366. };
  32367. PostProcessManager.prototype._rebuild = function () {
  32368. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32369. if (!vb) {
  32370. return;
  32371. }
  32372. vb._rebuild();
  32373. this._buildIndexBuffer();
  32374. };
  32375. // Methods
  32376. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32377. if (sourceTexture === void 0) { sourceTexture = null; }
  32378. if (postProcesses === void 0) { postProcesses = null; }
  32379. var camera = this._scene.activeCamera;
  32380. if (!camera) {
  32381. return false;
  32382. }
  32383. var postProcesses = postProcesses || camera._postProcesses;
  32384. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32385. return false;
  32386. }
  32387. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32388. return true;
  32389. };
  32390. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32391. if (targetTexture === void 0) { targetTexture = null; }
  32392. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32393. if (!this._scene.activeCamera) {
  32394. return;
  32395. }
  32396. var engine = this._scene.getEngine();
  32397. for (var index = 0; index < postProcesses.length; index++) {
  32398. if (index < postProcesses.length - 1) {
  32399. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32400. }
  32401. else {
  32402. if (targetTexture) {
  32403. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32404. }
  32405. else {
  32406. engine.restoreDefaultFramebuffer();
  32407. }
  32408. }
  32409. var pp = postProcesses[index];
  32410. var effect = pp.apply();
  32411. if (effect) {
  32412. pp.onBeforeRenderObservable.notifyObservers(effect);
  32413. // VBOs
  32414. this._prepareBuffers();
  32415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32416. // Draw order
  32417. engine.draw(true, 0, 6);
  32418. pp.onAfterRenderObservable.notifyObservers(effect);
  32419. }
  32420. }
  32421. // Restore depth buffer
  32422. engine.setDepthBuffer(true);
  32423. engine.setDepthWrite(true);
  32424. };
  32425. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32426. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32427. var camera = this._scene.activeCamera;
  32428. if (!camera) {
  32429. return;
  32430. }
  32431. postProcesses = postProcesses || camera._postProcesses;
  32432. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32433. return;
  32434. }
  32435. var engine = this._scene.getEngine();
  32436. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32437. if (index < len - 1) {
  32438. postProcesses[index + 1].activate(camera, targetTexture);
  32439. }
  32440. else {
  32441. if (targetTexture) {
  32442. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32443. }
  32444. else {
  32445. engine.restoreDefaultFramebuffer();
  32446. }
  32447. }
  32448. if (doNotPresent) {
  32449. break;
  32450. }
  32451. var pp = postProcesses[index];
  32452. var effect = pp.apply();
  32453. if (effect) {
  32454. pp.onBeforeRenderObservable.notifyObservers(effect);
  32455. // VBOs
  32456. this._prepareBuffers();
  32457. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32458. // Draw order
  32459. engine.draw(true, 0, 6);
  32460. pp.onAfterRenderObservable.notifyObservers(effect);
  32461. }
  32462. }
  32463. // Restore states
  32464. engine.setDepthBuffer(true);
  32465. engine.setDepthWrite(true);
  32466. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32467. };
  32468. PostProcessManager.prototype.dispose = function () {
  32469. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32470. if (buffer) {
  32471. buffer.dispose();
  32472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32473. }
  32474. if (this._indexBuffer) {
  32475. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32476. this._indexBuffer = null;
  32477. }
  32478. };
  32479. return PostProcessManager;
  32480. }());
  32481. BABYLON.PostProcessManager = PostProcessManager;
  32482. })(BABYLON || (BABYLON = {}));
  32483. //# sourceMappingURL=babylon.postProcessManager.js.map
  32484. var BABYLON;
  32485. (function (BABYLON) {
  32486. /**
  32487. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32488. */
  32489. var PerformanceMonitor = /** @class */ (function () {
  32490. /**
  32491. * constructor
  32492. * @param frameSampleSize The number of samples required to saturate the sliding window
  32493. */
  32494. function PerformanceMonitor(frameSampleSize) {
  32495. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32496. this._enabled = true;
  32497. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32498. }
  32499. /**
  32500. * Samples current frame
  32501. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32502. */
  32503. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32504. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32505. if (!this._enabled)
  32506. return;
  32507. if (this._lastFrameTimeMs != null) {
  32508. var dt = timeMs - this._lastFrameTimeMs;
  32509. this._rollingFrameTime.add(dt);
  32510. }
  32511. this._lastFrameTimeMs = timeMs;
  32512. };
  32513. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32514. /**
  32515. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32516. * @return Average frame time in milliseconds
  32517. */
  32518. get: function () {
  32519. return this._rollingFrameTime.average;
  32520. },
  32521. enumerable: true,
  32522. configurable: true
  32523. });
  32524. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32525. /**
  32526. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32527. * @return Frame time variance in milliseconds squared
  32528. */
  32529. get: function () {
  32530. return this._rollingFrameTime.variance;
  32531. },
  32532. enumerable: true,
  32533. configurable: true
  32534. });
  32535. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32536. /**
  32537. * Returns the frame time of the most recent frame
  32538. * @return Frame time in milliseconds
  32539. */
  32540. get: function () {
  32541. return this._rollingFrameTime.history(0);
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32547. /**
  32548. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32549. * @return Framerate in frames per second
  32550. */
  32551. get: function () {
  32552. return 1000.0 / this._rollingFrameTime.average;
  32553. },
  32554. enumerable: true,
  32555. configurable: true
  32556. });
  32557. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32558. /**
  32559. * Returns the average framerate in frames per second using the most recent frame time
  32560. * @return Framerate in frames per second
  32561. */
  32562. get: function () {
  32563. var history = this._rollingFrameTime.history(0);
  32564. if (history === 0) {
  32565. return 0;
  32566. }
  32567. return 1000.0 / history;
  32568. },
  32569. enumerable: true,
  32570. configurable: true
  32571. });
  32572. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32573. /**
  32574. * Returns true if enough samples have been taken to completely fill the sliding window
  32575. * @return true if saturated
  32576. */
  32577. get: function () {
  32578. return this._rollingFrameTime.isSaturated();
  32579. },
  32580. enumerable: true,
  32581. configurable: true
  32582. });
  32583. /**
  32584. * Enables contributions to the sliding window sample set
  32585. */
  32586. PerformanceMonitor.prototype.enable = function () {
  32587. this._enabled = true;
  32588. };
  32589. /**
  32590. * Disables contributions to the sliding window sample set
  32591. * Samples will not be interpolated over the disabled period
  32592. */
  32593. PerformanceMonitor.prototype.disable = function () {
  32594. this._enabled = false;
  32595. //clear last sample to avoid interpolating over the disabled period when next enabled
  32596. this._lastFrameTimeMs = null;
  32597. };
  32598. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32599. /**
  32600. * Returns true if sampling is enabled
  32601. * @return true if enabled
  32602. */
  32603. get: function () {
  32604. return this._enabled;
  32605. },
  32606. enumerable: true,
  32607. configurable: true
  32608. });
  32609. /**
  32610. * Resets performance monitor
  32611. */
  32612. PerformanceMonitor.prototype.reset = function () {
  32613. //clear last sample to avoid interpolating over the disabled period when next enabled
  32614. this._lastFrameTimeMs = null;
  32615. //wipe record
  32616. this._rollingFrameTime.reset();
  32617. };
  32618. return PerformanceMonitor;
  32619. }());
  32620. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32621. /**
  32622. * RollingAverage
  32623. *
  32624. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32625. */
  32626. var RollingAverage = /** @class */ (function () {
  32627. /**
  32628. * constructor
  32629. * @param length The number of samples required to saturate the sliding window
  32630. */
  32631. function RollingAverage(length) {
  32632. this._samples = new Array(length);
  32633. this.reset();
  32634. }
  32635. /**
  32636. * Adds a sample to the sample set
  32637. * @param v The sample value
  32638. */
  32639. RollingAverage.prototype.add = function (v) {
  32640. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32641. var delta;
  32642. //we need to check if we've already wrapped round
  32643. if (this.isSaturated()) {
  32644. //remove bottom of stack from mean
  32645. var bottomValue = this._samples[this._pos];
  32646. delta = bottomValue - this.average;
  32647. this.average -= delta / (this._sampleCount - 1);
  32648. this._m2 -= delta * (bottomValue - this.average);
  32649. }
  32650. else {
  32651. this._sampleCount++;
  32652. }
  32653. //add new value to mean
  32654. delta = v - this.average;
  32655. this.average += delta / (this._sampleCount);
  32656. this._m2 += delta * (v - this.average);
  32657. //set the new variance
  32658. this.variance = this._m2 / (this._sampleCount - 1);
  32659. this._samples[this._pos] = v;
  32660. this._pos++;
  32661. this._pos %= this._samples.length; //positive wrap around
  32662. };
  32663. /**
  32664. * Returns previously added values or null if outside of history or outside the sliding window domain
  32665. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32666. * @return Value previously recorded with add() or null if outside of range
  32667. */
  32668. RollingAverage.prototype.history = function (i) {
  32669. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32670. return 0;
  32671. }
  32672. var i0 = this._wrapPosition(this._pos - 1.0);
  32673. return this._samples[this._wrapPosition(i0 - i)];
  32674. };
  32675. /**
  32676. * Returns true if enough samples have been taken to completely fill the sliding window
  32677. * @return true if sample-set saturated
  32678. */
  32679. RollingAverage.prototype.isSaturated = function () {
  32680. return this._sampleCount >= this._samples.length;
  32681. };
  32682. /**
  32683. * Resets the rolling average (equivalent to 0 samples taken so far)
  32684. */
  32685. RollingAverage.prototype.reset = function () {
  32686. this.average = 0;
  32687. this.variance = 0;
  32688. this._sampleCount = 0;
  32689. this._pos = 0;
  32690. this._m2 = 0;
  32691. };
  32692. /**
  32693. * Wraps a value around the sample range boundaries
  32694. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32695. * @return Wrapped position in sample range
  32696. */
  32697. RollingAverage.prototype._wrapPosition = function (i) {
  32698. var max = this._samples.length;
  32699. return ((i % max) + max) % max;
  32700. };
  32701. return RollingAverage;
  32702. }());
  32703. BABYLON.RollingAverage = RollingAverage;
  32704. })(BABYLON || (BABYLON = {}));
  32705. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32706. var BABYLON;
  32707. (function (BABYLON) {
  32708. /**
  32709. * This groups together the common properties used for image processing either in direct forward pass
  32710. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32711. * or not.
  32712. */
  32713. var ImageProcessingConfiguration = /** @class */ (function () {
  32714. function ImageProcessingConfiguration() {
  32715. /**
  32716. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32717. */
  32718. this.colorCurves = new BABYLON.ColorCurves();
  32719. this._colorCurvesEnabled = false;
  32720. this._colorGradingEnabled = false;
  32721. this._colorGradingWithGreenDepth = true;
  32722. this._colorGradingBGR = true;
  32723. this._exposure = 1.0;
  32724. this._toneMappingEnabled = false;
  32725. this._contrast = 1.0;
  32726. /**
  32727. * Vignette stretch size.
  32728. */
  32729. this.vignetteStretch = 0;
  32730. /**
  32731. * Vignette centre X Offset.
  32732. */
  32733. this.vignetteCentreX = 0;
  32734. /**
  32735. * Vignette centre Y Offset.
  32736. */
  32737. this.vignetteCentreY = 0;
  32738. /**
  32739. * Vignette weight or intensity of the vignette effect.
  32740. */
  32741. this.vignetteWeight = 1.5;
  32742. /**
  32743. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32744. * if vignetteEnabled is set to true.
  32745. */
  32746. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32747. /**
  32748. * Camera field of view used by the Vignette effect.
  32749. */
  32750. this.vignetteCameraFov = 0.5;
  32751. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32752. this._vignetteEnabled = false;
  32753. this._applyByPostProcess = false;
  32754. this._isEnabled = true;
  32755. /**
  32756. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32757. * @type {BABYLON.Observable}
  32758. */
  32759. this.onUpdateParameters = new BABYLON.Observable();
  32760. }
  32761. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32762. /**
  32763. * Gets wether the color curves effect is enabled.
  32764. */
  32765. get: function () {
  32766. return this._colorCurvesEnabled;
  32767. },
  32768. /**
  32769. * Sets wether the color curves effect is enabled.
  32770. */
  32771. set: function (value) {
  32772. if (this._colorCurvesEnabled === value) {
  32773. return;
  32774. }
  32775. this._colorCurvesEnabled = value;
  32776. this._updateParameters();
  32777. },
  32778. enumerable: true,
  32779. configurable: true
  32780. });
  32781. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32782. /**
  32783. * Gets wether the color grading effect is enabled.
  32784. */
  32785. get: function () {
  32786. return this._colorGradingEnabled;
  32787. },
  32788. /**
  32789. * Sets wether the color grading effect is enabled.
  32790. */
  32791. set: function (value) {
  32792. if (this._colorGradingEnabled === value) {
  32793. return;
  32794. }
  32795. this._colorGradingEnabled = value;
  32796. this._updateParameters();
  32797. },
  32798. enumerable: true,
  32799. configurable: true
  32800. });
  32801. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32802. /**
  32803. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32804. */
  32805. get: function () {
  32806. return this._colorGradingWithGreenDepth;
  32807. },
  32808. /**
  32809. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32810. */
  32811. set: function (value) {
  32812. if (this._colorGradingWithGreenDepth === value) {
  32813. return;
  32814. }
  32815. this._colorGradingWithGreenDepth = value;
  32816. this._updateParameters();
  32817. },
  32818. enumerable: true,
  32819. configurable: true
  32820. });
  32821. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32822. /**
  32823. * Gets wether the color grading texture contains BGR values.
  32824. */
  32825. get: function () {
  32826. return this._colorGradingBGR;
  32827. },
  32828. /**
  32829. * Sets wether the color grading texture contains BGR values.
  32830. */
  32831. set: function (value) {
  32832. if (this._colorGradingBGR === value) {
  32833. return;
  32834. }
  32835. this._colorGradingBGR = value;
  32836. this._updateParameters();
  32837. },
  32838. enumerable: true,
  32839. configurable: true
  32840. });
  32841. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32842. /**
  32843. * Gets the Exposure used in the effect.
  32844. */
  32845. get: function () {
  32846. return this._exposure;
  32847. },
  32848. /**
  32849. * Sets the Exposure used in the effect.
  32850. */
  32851. set: function (value) {
  32852. if (this._exposure === value) {
  32853. return;
  32854. }
  32855. this._exposure = value;
  32856. this._updateParameters();
  32857. },
  32858. enumerable: true,
  32859. configurable: true
  32860. });
  32861. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32862. /**
  32863. * Gets wether the tone mapping effect is enabled.
  32864. */
  32865. get: function () {
  32866. return this._toneMappingEnabled;
  32867. },
  32868. /**
  32869. * Sets wether the tone mapping effect is enabled.
  32870. */
  32871. set: function (value) {
  32872. if (this._toneMappingEnabled === value) {
  32873. return;
  32874. }
  32875. this._toneMappingEnabled = value;
  32876. this._updateParameters();
  32877. },
  32878. enumerable: true,
  32879. configurable: true
  32880. });
  32881. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32882. /**
  32883. * Gets the contrast used in the effect.
  32884. */
  32885. get: function () {
  32886. return this._contrast;
  32887. },
  32888. /**
  32889. * Sets the contrast used in the effect.
  32890. */
  32891. set: function (value) {
  32892. if (this._contrast === value) {
  32893. return;
  32894. }
  32895. this._contrast = value;
  32896. this._updateParameters();
  32897. },
  32898. enumerable: true,
  32899. configurable: true
  32900. });
  32901. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32902. /**
  32903. * Gets the vignette blend mode allowing different kind of effect.
  32904. */
  32905. get: function () {
  32906. return this._vignetteBlendMode;
  32907. },
  32908. /**
  32909. * Sets the vignette blend mode allowing different kind of effect.
  32910. */
  32911. set: function (value) {
  32912. if (this._vignetteBlendMode === value) {
  32913. return;
  32914. }
  32915. this._vignetteBlendMode = value;
  32916. this._updateParameters();
  32917. },
  32918. enumerable: true,
  32919. configurable: true
  32920. });
  32921. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32922. /**
  32923. * Gets wether the vignette effect is enabled.
  32924. */
  32925. get: function () {
  32926. return this._vignetteEnabled;
  32927. },
  32928. /**
  32929. * Sets wether the vignette effect is enabled.
  32930. */
  32931. set: function (value) {
  32932. if (this._vignetteEnabled === value) {
  32933. return;
  32934. }
  32935. this._vignetteEnabled = value;
  32936. this._updateParameters();
  32937. },
  32938. enumerable: true,
  32939. configurable: true
  32940. });
  32941. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32942. /**
  32943. * Gets wether the image processing is applied through a post process or not.
  32944. */
  32945. get: function () {
  32946. return this._applyByPostProcess;
  32947. },
  32948. /**
  32949. * Sets wether the image processing is applied through a post process or not.
  32950. */
  32951. set: function (value) {
  32952. if (this._applyByPostProcess === value) {
  32953. return;
  32954. }
  32955. this._applyByPostProcess = value;
  32956. this._updateParameters();
  32957. },
  32958. enumerable: true,
  32959. configurable: true
  32960. });
  32961. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32962. /**
  32963. * Gets wether the image processing is enabled or not.
  32964. */
  32965. get: function () {
  32966. return this._isEnabled;
  32967. },
  32968. /**
  32969. * Sets wether the image processing is enabled or not.
  32970. */
  32971. set: function (value) {
  32972. if (this._isEnabled === value) {
  32973. return;
  32974. }
  32975. this._isEnabled = value;
  32976. this._updateParameters();
  32977. },
  32978. enumerable: true,
  32979. configurable: true
  32980. });
  32981. /**
  32982. * Method called each time the image processing information changes requires to recompile the effect.
  32983. */
  32984. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32985. this.onUpdateParameters.notifyObservers(this);
  32986. };
  32987. ImageProcessingConfiguration.prototype.getClassName = function () {
  32988. return "ImageProcessingConfiguration";
  32989. };
  32990. /**
  32991. * Prepare the list of uniforms associated with the Image Processing effects.
  32992. * @param uniformsList The list of uniforms used in the effect
  32993. * @param defines the list of defines currently in use
  32994. */
  32995. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32996. if (defines.EXPOSURE) {
  32997. uniforms.push("exposureLinear");
  32998. }
  32999. if (defines.CONTRAST) {
  33000. uniforms.push("contrast");
  33001. }
  33002. if (defines.COLORGRADING) {
  33003. uniforms.push("colorTransformSettings");
  33004. }
  33005. if (defines.VIGNETTE) {
  33006. uniforms.push("vInverseScreenSize");
  33007. uniforms.push("vignetteSettings1");
  33008. uniforms.push("vignetteSettings2");
  33009. }
  33010. if (defines.COLORCURVES) {
  33011. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33012. }
  33013. };
  33014. /**
  33015. * Prepare the list of samplers associated with the Image Processing effects.
  33016. * @param uniformsList The list of uniforms used in the effect
  33017. * @param defines the list of defines currently in use
  33018. */
  33019. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33020. if (defines.COLORGRADING) {
  33021. samplersList.push("txColorTransform");
  33022. }
  33023. };
  33024. /**
  33025. * Prepare the list of defines associated to the shader.
  33026. * @param defines the list of defines to complete
  33027. */
  33028. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33029. if (forPostProcess === void 0) { forPostProcess = false; }
  33030. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33031. defines.VIGNETTE = false;
  33032. defines.TONEMAPPING = false;
  33033. defines.CONTRAST = false;
  33034. defines.EXPOSURE = false;
  33035. defines.COLORCURVES = false;
  33036. defines.COLORGRADING = false;
  33037. defines.COLORGRADING3D = false;
  33038. defines.IMAGEPROCESSING = false;
  33039. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33040. return;
  33041. }
  33042. defines.VIGNETTE = this.vignetteEnabled;
  33043. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33044. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33045. defines.TONEMAPPING = this.toneMappingEnabled;
  33046. defines.CONTRAST = (this.contrast !== 1.0);
  33047. defines.EXPOSURE = (this.exposure !== 1.0);
  33048. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33049. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33050. if (defines.COLORGRADING) {
  33051. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33052. }
  33053. else {
  33054. defines.COLORGRADING3D = false;
  33055. }
  33056. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33057. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33058. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33059. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33060. };
  33061. /**
  33062. * Returns true if all the image processing information are ready.
  33063. */
  33064. ImageProcessingConfiguration.prototype.isReady = function () {
  33065. // Color Grading texure can not be none blocking.
  33066. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33067. };
  33068. /**
  33069. * Binds the image processing to the shader.
  33070. * @param effect The effect to bind to
  33071. */
  33072. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33073. if (aspectRatio === void 0) { aspectRatio = 1; }
  33074. // Color Curves
  33075. if (this._colorCurvesEnabled && this.colorCurves) {
  33076. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33077. }
  33078. // Vignette
  33079. if (this._vignetteEnabled) {
  33080. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33081. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33082. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33083. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33084. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33085. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33086. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33087. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33088. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33089. var vignettePower = -2.0 * this.vignetteWeight;
  33090. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33091. }
  33092. // Exposure
  33093. effect.setFloat("exposureLinear", this.exposure);
  33094. // Contrast
  33095. effect.setFloat("contrast", this.contrast);
  33096. // Color transform settings
  33097. if (this.colorGradingTexture) {
  33098. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33099. var textureSize = this.colorGradingTexture.getSize().height;
  33100. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33101. 0.5 / textureSize, // textureOffset
  33102. textureSize, // textureSize
  33103. this.colorGradingTexture.level // weight
  33104. );
  33105. }
  33106. };
  33107. /**
  33108. * Clones the current image processing instance.
  33109. * @return The cloned image processing
  33110. */
  33111. ImageProcessingConfiguration.prototype.clone = function () {
  33112. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33113. };
  33114. /**
  33115. * Serializes the current image processing instance to a json representation.
  33116. * @return a JSON representation
  33117. */
  33118. ImageProcessingConfiguration.prototype.serialize = function () {
  33119. return BABYLON.SerializationHelper.Serialize(this);
  33120. };
  33121. /**
  33122. * Parses the image processing from a json representation.
  33123. * @param source the JSON source to parse
  33124. * @return The parsed image processing
  33125. */
  33126. ImageProcessingConfiguration.Parse = function (source) {
  33127. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33128. };
  33129. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33130. /**
  33131. * Used to apply the vignette as a mix with the pixel color.
  33132. */
  33133. get: function () {
  33134. return this._VIGNETTEMODE_MULTIPLY;
  33135. },
  33136. enumerable: true,
  33137. configurable: true
  33138. });
  33139. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33140. /**
  33141. * Used to apply the vignette as a replacement of the pixel color.
  33142. */
  33143. get: function () {
  33144. return this._VIGNETTEMODE_OPAQUE;
  33145. },
  33146. enumerable: true,
  33147. configurable: true
  33148. });
  33149. // Static constants associated to the image processing.
  33150. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33151. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33152. __decorate([
  33153. BABYLON.serializeAsColorCurves()
  33154. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33155. __decorate([
  33156. BABYLON.serialize()
  33157. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33158. __decorate([
  33159. BABYLON.serializeAsTexture()
  33160. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33161. __decorate([
  33162. BABYLON.serialize()
  33163. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33164. __decorate([
  33165. BABYLON.serialize()
  33166. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33167. __decorate([
  33168. BABYLON.serialize()
  33169. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33170. __decorate([
  33171. BABYLON.serialize()
  33172. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33173. __decorate([
  33174. BABYLON.serialize()
  33175. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33176. __decorate([
  33177. BABYLON.serialize()
  33178. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33179. __decorate([
  33180. BABYLON.serialize()
  33181. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33182. __decorate([
  33183. BABYLON.serialize()
  33184. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33185. __decorate([
  33186. BABYLON.serialize()
  33187. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33188. __decorate([
  33189. BABYLON.serialize()
  33190. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33191. __decorate([
  33192. BABYLON.serializeAsColor4()
  33193. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33194. __decorate([
  33195. BABYLON.serialize()
  33196. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33197. __decorate([
  33198. BABYLON.serialize()
  33199. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33200. __decorate([
  33201. BABYLON.serialize()
  33202. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33203. __decorate([
  33204. BABYLON.serialize()
  33205. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33206. __decorate([
  33207. BABYLON.serialize()
  33208. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33209. return ImageProcessingConfiguration;
  33210. }());
  33211. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33212. })(BABYLON || (BABYLON = {}));
  33213. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33214. var BABYLON;
  33215. (function (BABYLON) {
  33216. /**
  33217. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33218. * It can help converting any input color in a desired output one. This can then be used to create effects
  33219. * from sepia, black and white to sixties or futuristic rendering...
  33220. *
  33221. * The only supported format is currently 3dl.
  33222. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33223. */
  33224. var ColorGradingTexture = /** @class */ (function (_super) {
  33225. __extends(ColorGradingTexture, _super);
  33226. /**
  33227. * Instantiates a ColorGradingTexture from the following parameters.
  33228. *
  33229. * @param url The location of the color gradind data (currently only supporting 3dl)
  33230. * @param scene The scene the texture will be used in
  33231. */
  33232. function ColorGradingTexture(url, scene) {
  33233. var _this = _super.call(this, scene) || this;
  33234. if (!url) {
  33235. return _this;
  33236. }
  33237. _this._engine = scene.getEngine();
  33238. _this._textureMatrix = BABYLON.Matrix.Identity();
  33239. _this.name = url;
  33240. _this.url = url;
  33241. _this.hasAlpha = false;
  33242. _this.isCube = false;
  33243. _this.is3D = _this._engine.webGLVersion > 1;
  33244. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33245. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33246. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33247. _this.anisotropicFilteringLevel = 1;
  33248. _this._texture = _this._getFromCache(url, true);
  33249. if (!_this._texture) {
  33250. if (!scene.useDelayedTextureLoading) {
  33251. _this.loadTexture();
  33252. }
  33253. else {
  33254. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33255. }
  33256. }
  33257. return _this;
  33258. }
  33259. /**
  33260. * Returns the texture matrix used in most of the material.
  33261. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33262. */
  33263. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33264. return this._textureMatrix;
  33265. };
  33266. /**
  33267. * Occurs when the file being loaded is a .3dl LUT file.
  33268. */
  33269. ColorGradingTexture.prototype.load3dlTexture = function () {
  33270. var engine = this._engine;
  33271. var texture;
  33272. if (engine.webGLVersion === 1) {
  33273. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33274. }
  33275. else {
  33276. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33277. }
  33278. this._texture = texture;
  33279. var callback = function (text) {
  33280. if (typeof text !== "string") {
  33281. return;
  33282. }
  33283. var data = null;
  33284. var tempData = null;
  33285. var line;
  33286. var lines = text.split('\n');
  33287. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33288. var maxColor = 0;
  33289. for (var i = 0; i < lines.length; i++) {
  33290. line = lines[i];
  33291. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33292. continue;
  33293. if (line.indexOf('#') === 0)
  33294. continue;
  33295. var words = line.split(" ");
  33296. if (size === 0) {
  33297. // Number of space + one
  33298. size = words.length;
  33299. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33300. tempData = new Float32Array(size * size * size * 4);
  33301. continue;
  33302. }
  33303. if (size != 0) {
  33304. var r = Math.max(parseInt(words[0]), 0);
  33305. var g = Math.max(parseInt(words[1]), 0);
  33306. var b = Math.max(parseInt(words[2]), 0);
  33307. maxColor = Math.max(r, maxColor);
  33308. maxColor = Math.max(g, maxColor);
  33309. maxColor = Math.max(b, maxColor);
  33310. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33311. if (tempData) {
  33312. tempData[pixelStorageIndex + 0] = r;
  33313. tempData[pixelStorageIndex + 1] = g;
  33314. tempData[pixelStorageIndex + 2] = b;
  33315. }
  33316. pixelIndexSlice++;
  33317. if (pixelIndexSlice % size == 0) {
  33318. pixelIndexH++;
  33319. pixelIndexSlice = 0;
  33320. if (pixelIndexH % size == 0) {
  33321. pixelIndexW++;
  33322. pixelIndexH = 0;
  33323. }
  33324. }
  33325. }
  33326. }
  33327. if (tempData && data) {
  33328. for (var i = 0; i < tempData.length; i++) {
  33329. if (i > 0 && (i + 1) % 4 === 0) {
  33330. data[i] = 255;
  33331. }
  33332. else {
  33333. var value = tempData[i];
  33334. data[i] = (value / maxColor * 255);
  33335. }
  33336. }
  33337. }
  33338. if (texture.is3D) {
  33339. texture.updateSize(size, size, size);
  33340. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33341. }
  33342. else {
  33343. texture.updateSize(size * size, size);
  33344. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33345. }
  33346. };
  33347. BABYLON.Tools.LoadFile(this.url, callback);
  33348. return this._texture;
  33349. };
  33350. /**
  33351. * Starts the loading process of the texture.
  33352. */
  33353. ColorGradingTexture.prototype.loadTexture = function () {
  33354. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33355. this.load3dlTexture();
  33356. }
  33357. };
  33358. /**
  33359. * Clones the color gradind texture.
  33360. */
  33361. ColorGradingTexture.prototype.clone = function () {
  33362. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33363. // Base texture
  33364. newTexture.level = this.level;
  33365. return newTexture;
  33366. };
  33367. /**
  33368. * Called during delayed load for textures.
  33369. */
  33370. ColorGradingTexture.prototype.delayLoad = function () {
  33371. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33372. return;
  33373. }
  33374. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33375. this._texture = this._getFromCache(this.url, true);
  33376. if (!this._texture) {
  33377. this.loadTexture();
  33378. }
  33379. };
  33380. /**
  33381. * Parses a color grading texture serialized by Babylon.
  33382. * @param parsedTexture The texture information being parsedTexture
  33383. * @param scene The scene to load the texture in
  33384. * @param rootUrl The root url of the data assets to load
  33385. * @return A color gradind texture
  33386. */
  33387. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33388. var texture = null;
  33389. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33390. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33391. texture.name = parsedTexture.name;
  33392. texture.level = parsedTexture.level;
  33393. }
  33394. return texture;
  33395. };
  33396. /**
  33397. * Serializes the LUT texture to json format.
  33398. */
  33399. ColorGradingTexture.prototype.serialize = function () {
  33400. if (!this.name) {
  33401. return null;
  33402. }
  33403. var serializationObject = {};
  33404. serializationObject.name = this.name;
  33405. serializationObject.level = this.level;
  33406. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33407. return serializationObject;
  33408. };
  33409. /**
  33410. * Empty line regex stored for GC.
  33411. */
  33412. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33413. return ColorGradingTexture;
  33414. }(BABYLON.BaseTexture));
  33415. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33416. })(BABYLON || (BABYLON = {}));
  33417. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33418. var BABYLON;
  33419. (function (BABYLON) {
  33420. /**
  33421. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33422. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33423. * 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;
  33424. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33425. */
  33426. var ColorCurves = /** @class */ (function () {
  33427. function ColorCurves() {
  33428. this._dirty = true;
  33429. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33430. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33431. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33432. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33433. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33434. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33435. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33436. this._globalHue = 30;
  33437. this._globalDensity = 0;
  33438. this._globalSaturation = 0;
  33439. this._globalExposure = 0;
  33440. this._highlightsHue = 30;
  33441. this._highlightsDensity = 0;
  33442. this._highlightsSaturation = 0;
  33443. this._highlightsExposure = 0;
  33444. this._midtonesHue = 30;
  33445. this._midtonesDensity = 0;
  33446. this._midtonesSaturation = 0;
  33447. this._midtonesExposure = 0;
  33448. this._shadowsHue = 30;
  33449. this._shadowsDensity = 0;
  33450. this._shadowsSaturation = 0;
  33451. this._shadowsExposure = 0;
  33452. }
  33453. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33454. /**
  33455. * Gets the global Hue value.
  33456. * 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).
  33457. */
  33458. get: function () {
  33459. return this._globalHue;
  33460. },
  33461. /**
  33462. * Sets the global Hue value.
  33463. * 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).
  33464. */
  33465. set: function (value) {
  33466. this._globalHue = value;
  33467. this._dirty = true;
  33468. },
  33469. enumerable: true,
  33470. configurable: true
  33471. });
  33472. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33473. /**
  33474. * Gets the global Density value.
  33475. * 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.
  33476. * Values less than zero provide a filter of opposite hue.
  33477. */
  33478. get: function () {
  33479. return this._globalDensity;
  33480. },
  33481. /**
  33482. * Sets the global Density value.
  33483. * 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.
  33484. * Values less than zero provide a filter of opposite hue.
  33485. */
  33486. set: function (value) {
  33487. this._globalDensity = value;
  33488. this._dirty = true;
  33489. },
  33490. enumerable: true,
  33491. configurable: true
  33492. });
  33493. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33494. /**
  33495. * Gets the global Saturation value.
  33496. * 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.
  33497. */
  33498. get: function () {
  33499. return this._globalSaturation;
  33500. },
  33501. /**
  33502. * Sets the global Saturation value.
  33503. * 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.
  33504. */
  33505. set: function (value) {
  33506. this._globalSaturation = value;
  33507. this._dirty = true;
  33508. },
  33509. enumerable: true,
  33510. configurable: true
  33511. });
  33512. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33513. /**
  33514. * Gets the highlights Hue value.
  33515. * 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).
  33516. */
  33517. get: function () {
  33518. return this._highlightsHue;
  33519. },
  33520. /**
  33521. * Sets the highlights Hue value.
  33522. * 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).
  33523. */
  33524. set: function (value) {
  33525. this._highlightsHue = value;
  33526. this._dirty = true;
  33527. },
  33528. enumerable: true,
  33529. configurable: true
  33530. });
  33531. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33532. /**
  33533. * Gets the highlights Density value.
  33534. * 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.
  33535. * Values less than zero provide a filter of opposite hue.
  33536. */
  33537. get: function () {
  33538. return this._highlightsDensity;
  33539. },
  33540. /**
  33541. * Sets the highlights Density value.
  33542. * 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.
  33543. * Values less than zero provide a filter of opposite hue.
  33544. */
  33545. set: function (value) {
  33546. this._highlightsDensity = value;
  33547. this._dirty = true;
  33548. },
  33549. enumerable: true,
  33550. configurable: true
  33551. });
  33552. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33553. /**
  33554. * Gets the highlights Saturation value.
  33555. * 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.
  33556. */
  33557. get: function () {
  33558. return this._highlightsSaturation;
  33559. },
  33560. /**
  33561. * Sets the highlights Saturation value.
  33562. * 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.
  33563. */
  33564. set: function (value) {
  33565. this._highlightsSaturation = value;
  33566. this._dirty = true;
  33567. },
  33568. enumerable: true,
  33569. configurable: true
  33570. });
  33571. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33572. /**
  33573. * Gets the highlights Exposure value.
  33574. * 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.
  33575. */
  33576. get: function () {
  33577. return this._highlightsExposure;
  33578. },
  33579. /**
  33580. * Sets the highlights Exposure value.
  33581. * 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.
  33582. */
  33583. set: function (value) {
  33584. this._highlightsExposure = value;
  33585. this._dirty = true;
  33586. },
  33587. enumerable: true,
  33588. configurable: true
  33589. });
  33590. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33591. /**
  33592. * Gets the midtones Hue value.
  33593. * 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).
  33594. */
  33595. get: function () {
  33596. return this._midtonesHue;
  33597. },
  33598. /**
  33599. * Sets the midtones Hue value.
  33600. * 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).
  33601. */
  33602. set: function (value) {
  33603. this._midtonesHue = value;
  33604. this._dirty = true;
  33605. },
  33606. enumerable: true,
  33607. configurable: true
  33608. });
  33609. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33610. /**
  33611. * Gets the midtones Density value.
  33612. * 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.
  33613. * Values less than zero provide a filter of opposite hue.
  33614. */
  33615. get: function () {
  33616. return this._midtonesDensity;
  33617. },
  33618. /**
  33619. * Sets the midtones Density value.
  33620. * 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.
  33621. * Values less than zero provide a filter of opposite hue.
  33622. */
  33623. set: function (value) {
  33624. this._midtonesDensity = value;
  33625. this._dirty = true;
  33626. },
  33627. enumerable: true,
  33628. configurable: true
  33629. });
  33630. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33631. /**
  33632. * Gets the midtones Saturation value.
  33633. * 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.
  33634. */
  33635. get: function () {
  33636. return this._midtonesSaturation;
  33637. },
  33638. /**
  33639. * Sets the midtones Saturation value.
  33640. * 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.
  33641. */
  33642. set: function (value) {
  33643. this._midtonesSaturation = value;
  33644. this._dirty = true;
  33645. },
  33646. enumerable: true,
  33647. configurable: true
  33648. });
  33649. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33650. /**
  33651. * Gets the midtones Exposure value.
  33652. * 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.
  33653. */
  33654. get: function () {
  33655. return this._midtonesExposure;
  33656. },
  33657. /**
  33658. * Sets the midtones Exposure value.
  33659. * 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.
  33660. */
  33661. set: function (value) {
  33662. this._midtonesExposure = value;
  33663. this._dirty = true;
  33664. },
  33665. enumerable: true,
  33666. configurable: true
  33667. });
  33668. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33669. /**
  33670. * Gets the shadows Hue value.
  33671. * 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).
  33672. */
  33673. get: function () {
  33674. return this._shadowsHue;
  33675. },
  33676. /**
  33677. * Sets the shadows Hue value.
  33678. * 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).
  33679. */
  33680. set: function (value) {
  33681. this._shadowsHue = value;
  33682. this._dirty = true;
  33683. },
  33684. enumerable: true,
  33685. configurable: true
  33686. });
  33687. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33688. /**
  33689. * Gets the shadows Density value.
  33690. * 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.
  33691. * Values less than zero provide a filter of opposite hue.
  33692. */
  33693. get: function () {
  33694. return this._shadowsDensity;
  33695. },
  33696. /**
  33697. * Sets the shadows Density value.
  33698. * 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.
  33699. * Values less than zero provide a filter of opposite hue.
  33700. */
  33701. set: function (value) {
  33702. this._shadowsDensity = value;
  33703. this._dirty = true;
  33704. },
  33705. enumerable: true,
  33706. configurable: true
  33707. });
  33708. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33709. /**
  33710. * Gets the shadows Saturation value.
  33711. * 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.
  33712. */
  33713. get: function () {
  33714. return this._shadowsSaturation;
  33715. },
  33716. /**
  33717. * Sets the shadows Saturation value.
  33718. * 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.
  33719. */
  33720. set: function (value) {
  33721. this._shadowsSaturation = value;
  33722. this._dirty = true;
  33723. },
  33724. enumerable: true,
  33725. configurable: true
  33726. });
  33727. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33728. /**
  33729. * Gets the shadows Exposure value.
  33730. * 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.
  33731. */
  33732. get: function () {
  33733. return this._shadowsExposure;
  33734. },
  33735. /**
  33736. * Sets the shadows Exposure value.
  33737. * 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.
  33738. */
  33739. set: function (value) {
  33740. this._shadowsExposure = value;
  33741. this._dirty = true;
  33742. },
  33743. enumerable: true,
  33744. configurable: true
  33745. });
  33746. ColorCurves.prototype.getClassName = function () {
  33747. return "ColorCurves";
  33748. };
  33749. /**
  33750. * Binds the color curves to the shader.
  33751. * @param colorCurves The color curve to bind
  33752. * @param effect The effect to bind to
  33753. */
  33754. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33755. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33756. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33757. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33758. if (colorCurves._dirty) {
  33759. colorCurves._dirty = false;
  33760. // Fill in global info.
  33761. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33762. // Compute highlights info.
  33763. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33764. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33765. // Compute midtones info.
  33766. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33767. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33768. // Compute shadows info.
  33769. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33770. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33771. // Compute deltas (neutral is midtones).
  33772. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33773. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33774. }
  33775. if (effect) {
  33776. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33777. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33778. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33779. }
  33780. };
  33781. /**
  33782. * Prepare the list of uniforms associated with the ColorCurves effects.
  33783. * @param uniformsList The list of uniforms used in the effect
  33784. */
  33785. ColorCurves.PrepareUniforms = function (uniformsList) {
  33786. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33787. };
  33788. /**
  33789. * Returns color grading data based on a hue, density, saturation and exposure value.
  33790. * @param filterHue The hue of the color filter.
  33791. * @param filterDensity The density of the color filter.
  33792. * @param saturation The saturation.
  33793. * @param exposure The exposure.
  33794. * @param result The result data container.
  33795. */
  33796. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33797. if (hue == null) {
  33798. return;
  33799. }
  33800. hue = ColorCurves.clamp(hue, 0, 360);
  33801. density = ColorCurves.clamp(density, -100, 100);
  33802. saturation = ColorCurves.clamp(saturation, -100, 100);
  33803. exposure = ColorCurves.clamp(exposure, -100, 100);
  33804. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33805. // so that the maximum filter density is only 50% control. This provides fine control
  33806. // for small values and reasonable range.
  33807. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33808. density *= 0.5;
  33809. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33810. if (density < 0) {
  33811. density *= -1;
  33812. hue = (hue + 180) % 360;
  33813. }
  33814. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33815. result.scaleToRef(2, result);
  33816. result.a = 1 + 0.01 * saturation;
  33817. };
  33818. /**
  33819. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33820. * @param value The input slider value in range [-100,100].
  33821. * @returns Adjusted value.
  33822. */
  33823. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33824. value /= 100;
  33825. var x = Math.abs(value);
  33826. x = Math.pow(x, 2);
  33827. if (value < 0) {
  33828. x *= -1;
  33829. }
  33830. x *= 100;
  33831. return x;
  33832. };
  33833. /**
  33834. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33835. * @param hue The hue (H) input.
  33836. * @param saturation The saturation (S) input.
  33837. * @param brightness The brightness (B) input.
  33838. * @result An RGBA color represented as Vector4.
  33839. */
  33840. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33841. var h = ColorCurves.clamp(hue, 0, 360);
  33842. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33843. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33844. if (s === 0) {
  33845. result.r = v;
  33846. result.g = v;
  33847. result.b = v;
  33848. }
  33849. else {
  33850. // sector 0 to 5
  33851. h /= 60;
  33852. var i = Math.floor(h);
  33853. // fractional part of h
  33854. var f = h - i;
  33855. var p = v * (1 - s);
  33856. var q = v * (1 - s * f);
  33857. var t = v * (1 - s * (1 - f));
  33858. switch (i) {
  33859. case 0:
  33860. result.r = v;
  33861. result.g = t;
  33862. result.b = p;
  33863. break;
  33864. case 1:
  33865. result.r = q;
  33866. result.g = v;
  33867. result.b = p;
  33868. break;
  33869. case 2:
  33870. result.r = p;
  33871. result.g = v;
  33872. result.b = t;
  33873. break;
  33874. case 3:
  33875. result.r = p;
  33876. result.g = q;
  33877. result.b = v;
  33878. break;
  33879. case 4:
  33880. result.r = t;
  33881. result.g = p;
  33882. result.b = v;
  33883. break;
  33884. default:// case 5:
  33885. result.r = v;
  33886. result.g = p;
  33887. result.b = q;
  33888. break;
  33889. }
  33890. }
  33891. result.a = 1;
  33892. };
  33893. /**
  33894. * Returns a value clamped between min and max
  33895. * @param value The value to clamp
  33896. * @param min The minimum of value
  33897. * @param max The maximum of value
  33898. * @returns The clamped value.
  33899. */
  33900. ColorCurves.clamp = function (value, min, max) {
  33901. return Math.min(Math.max(value, min), max);
  33902. };
  33903. /**
  33904. * Clones the current color curve instance.
  33905. * @return The cloned curves
  33906. */
  33907. ColorCurves.prototype.clone = function () {
  33908. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33909. };
  33910. /**
  33911. * Serializes the current color curve instance to a json representation.
  33912. * @return a JSON representation
  33913. */
  33914. ColorCurves.prototype.serialize = function () {
  33915. return BABYLON.SerializationHelper.Serialize(this);
  33916. };
  33917. /**
  33918. * Parses the color curve from a json representation.
  33919. * @param source the JSON source to parse
  33920. * @return The parsed curves
  33921. */
  33922. ColorCurves.Parse = function (source) {
  33923. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33924. };
  33925. __decorate([
  33926. BABYLON.serialize()
  33927. ], ColorCurves.prototype, "_globalHue", void 0);
  33928. __decorate([
  33929. BABYLON.serialize()
  33930. ], ColorCurves.prototype, "_globalDensity", void 0);
  33931. __decorate([
  33932. BABYLON.serialize()
  33933. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33934. __decorate([
  33935. BABYLON.serialize()
  33936. ], ColorCurves.prototype, "_globalExposure", void 0);
  33937. __decorate([
  33938. BABYLON.serialize()
  33939. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33940. __decorate([
  33941. BABYLON.serialize()
  33942. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33943. __decorate([
  33944. BABYLON.serialize()
  33945. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33946. __decorate([
  33947. BABYLON.serialize()
  33948. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33949. __decorate([
  33950. BABYLON.serialize()
  33951. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33952. __decorate([
  33953. BABYLON.serialize()
  33954. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33955. __decorate([
  33956. BABYLON.serialize()
  33957. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33958. __decorate([
  33959. BABYLON.serialize()
  33960. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33961. return ColorCurves;
  33962. }());
  33963. BABYLON.ColorCurves = ColorCurves;
  33964. })(BABYLON || (BABYLON = {}));
  33965. //# sourceMappingURL=babylon.colorCurves.js.map
  33966. var BABYLON;
  33967. (function (BABYLON) {
  33968. var StandardMaterialDefines = /** @class */ (function (_super) {
  33969. __extends(StandardMaterialDefines, _super);
  33970. function StandardMaterialDefines() {
  33971. var _this = _super.call(this) || this;
  33972. _this.MAINUV1 = false;
  33973. _this.MAINUV2 = false;
  33974. _this.DIFFUSE = false;
  33975. _this.DIFFUSEDIRECTUV = 0;
  33976. _this.AMBIENT = false;
  33977. _this.AMBIENTDIRECTUV = 0;
  33978. _this.OPACITY = false;
  33979. _this.OPACITYDIRECTUV = 0;
  33980. _this.OPACITYRGB = false;
  33981. _this.REFLECTION = false;
  33982. _this.EMISSIVE = false;
  33983. _this.EMISSIVEDIRECTUV = 0;
  33984. _this.SPECULAR = false;
  33985. _this.SPECULARDIRECTUV = 0;
  33986. _this.BUMP = false;
  33987. _this.BUMPDIRECTUV = 0;
  33988. _this.PARALLAX = false;
  33989. _this.PARALLAXOCCLUSION = false;
  33990. _this.SPECULAROVERALPHA = false;
  33991. _this.CLIPPLANE = false;
  33992. _this.ALPHATEST = false;
  33993. _this.DEPTHPREPASS = false;
  33994. _this.ALPHAFROMDIFFUSE = false;
  33995. _this.POINTSIZE = false;
  33996. _this.FOG = false;
  33997. _this.SPECULARTERM = false;
  33998. _this.DIFFUSEFRESNEL = false;
  33999. _this.OPACITYFRESNEL = false;
  34000. _this.REFLECTIONFRESNEL = false;
  34001. _this.REFRACTIONFRESNEL = false;
  34002. _this.EMISSIVEFRESNEL = false;
  34003. _this.FRESNEL = false;
  34004. _this.NORMAL = false;
  34005. _this.UV1 = false;
  34006. _this.UV2 = false;
  34007. _this.VERTEXCOLOR = false;
  34008. _this.VERTEXALPHA = false;
  34009. _this.NUM_BONE_INFLUENCERS = 0;
  34010. _this.BonesPerMesh = 0;
  34011. _this.INSTANCES = false;
  34012. _this.GLOSSINESS = false;
  34013. _this.ROUGHNESS = false;
  34014. _this.EMISSIVEASILLUMINATION = false;
  34015. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34016. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34017. _this.LIGHTMAP = false;
  34018. _this.LIGHTMAPDIRECTUV = 0;
  34019. _this.USELIGHTMAPASSHADOWMAP = false;
  34020. _this.REFLECTIONMAP_3D = false;
  34021. _this.REFLECTIONMAP_SPHERICAL = false;
  34022. _this.REFLECTIONMAP_PLANAR = false;
  34023. _this.REFLECTIONMAP_CUBIC = false;
  34024. _this.REFLECTIONMAP_PROJECTION = false;
  34025. _this.REFLECTIONMAP_SKYBOX = false;
  34026. _this.REFLECTIONMAP_EXPLICIT = false;
  34027. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34028. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34029. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34030. _this.INVERTCUBICMAP = false;
  34031. _this.LOGARITHMICDEPTH = false;
  34032. _this.REFRACTION = false;
  34033. _this.REFRACTIONMAP_3D = false;
  34034. _this.REFLECTIONOVERALPHA = false;
  34035. _this.TWOSIDEDLIGHTING = false;
  34036. _this.SHADOWFLOAT = false;
  34037. _this.MORPHTARGETS = false;
  34038. _this.MORPHTARGETS_NORMAL = false;
  34039. _this.MORPHTARGETS_TANGENT = false;
  34040. _this.NUM_MORPH_INFLUENCERS = 0;
  34041. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34042. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34043. _this.IMAGEPROCESSING = false;
  34044. _this.VIGNETTE = false;
  34045. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34046. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34047. _this.TONEMAPPING = false;
  34048. _this.CONTRAST = false;
  34049. _this.COLORCURVES = false;
  34050. _this.COLORGRADING = false;
  34051. _this.COLORGRADING3D = false;
  34052. _this.SAMPLER3DGREENDEPTH = false;
  34053. _this.SAMPLER3DBGRMAP = false;
  34054. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34055. _this.EXPOSURE = false;
  34056. _this.rebuild();
  34057. return _this;
  34058. }
  34059. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34060. var modes = [
  34061. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34062. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34063. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34064. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34065. ];
  34066. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34067. var mode = modes_1[_i];
  34068. this[mode] = (mode === modeToEnable);
  34069. }
  34070. };
  34071. return StandardMaterialDefines;
  34072. }(BABYLON.MaterialDefines));
  34073. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34074. var StandardMaterial = /** @class */ (function (_super) {
  34075. __extends(StandardMaterial, _super);
  34076. function StandardMaterial(name, scene) {
  34077. var _this = _super.call(this, name, scene) || this;
  34078. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34079. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34080. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34081. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34082. _this.specularPower = 64;
  34083. _this._useAlphaFromDiffuseTexture = false;
  34084. _this._useEmissiveAsIllumination = false;
  34085. _this._linkEmissiveWithDiffuse = false;
  34086. _this._useSpecularOverAlpha = false;
  34087. _this._useReflectionOverAlpha = false;
  34088. _this._disableLighting = false;
  34089. _this._useParallax = false;
  34090. _this._useParallaxOcclusion = false;
  34091. _this.parallaxScaleBias = 0.05;
  34092. _this._roughness = 0;
  34093. _this.indexOfRefraction = 0.98;
  34094. _this.invertRefractionY = true;
  34095. _this._useLightmapAsShadowmap = false;
  34096. _this._useReflectionFresnelFromSpecular = false;
  34097. _this._useGlossinessFromSpecularMapAlpha = false;
  34098. _this._maxSimultaneousLights = 4;
  34099. /**
  34100. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34101. */
  34102. _this._invertNormalMapX = false;
  34103. /**
  34104. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34105. */
  34106. _this._invertNormalMapY = false;
  34107. /**
  34108. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34109. */
  34110. _this._twoSidedLighting = false;
  34111. _this._renderTargets = new BABYLON.SmartArray(16);
  34112. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34113. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34114. // Setup the default processing configuration to the scene.
  34115. _this._attachImageProcessingConfiguration(null);
  34116. _this.getRenderTargetTextures = function () {
  34117. _this._renderTargets.reset();
  34118. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34119. _this._renderTargets.push(_this._reflectionTexture);
  34120. }
  34121. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34122. _this._renderTargets.push(_this._refractionTexture);
  34123. }
  34124. return _this._renderTargets;
  34125. };
  34126. return _this;
  34127. }
  34128. ;
  34129. ;
  34130. ;
  34131. ;
  34132. ;
  34133. ;
  34134. ;
  34135. ;
  34136. ;
  34137. ;
  34138. ;
  34139. ;
  34140. ;
  34141. ;
  34142. ;
  34143. ;
  34144. ;
  34145. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34146. /**
  34147. * Gets the image processing configuration used either in this material.
  34148. */
  34149. get: function () {
  34150. return this._imageProcessingConfiguration;
  34151. },
  34152. /**
  34153. * Sets the Default image processing configuration used either in the this material.
  34154. *
  34155. * If sets to null, the scene one is in use.
  34156. */
  34157. set: function (value) {
  34158. this._attachImageProcessingConfiguration(value);
  34159. // Ensure the effect will be rebuilt.
  34160. this._markAllSubMeshesAsTexturesDirty();
  34161. },
  34162. enumerable: true,
  34163. configurable: true
  34164. });
  34165. /**
  34166. * Attaches a new image processing configuration to the Standard Material.
  34167. * @param configuration
  34168. */
  34169. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34170. var _this = this;
  34171. if (configuration === this._imageProcessingConfiguration) {
  34172. return;
  34173. }
  34174. // Detaches observer.
  34175. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34176. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34177. }
  34178. // Pick the scene configuration if needed.
  34179. if (!configuration) {
  34180. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34181. }
  34182. else {
  34183. this._imageProcessingConfiguration = configuration;
  34184. }
  34185. // Attaches observer.
  34186. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34187. _this._markAllSubMeshesAsImageProcessingDirty();
  34188. });
  34189. };
  34190. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34191. /**
  34192. * Gets wether the color curves effect is enabled.
  34193. */
  34194. get: function () {
  34195. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34196. },
  34197. /**
  34198. * Sets wether the color curves effect is enabled.
  34199. */
  34200. set: function (value) {
  34201. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34202. },
  34203. enumerable: true,
  34204. configurable: true
  34205. });
  34206. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34207. /**
  34208. * Gets wether the color grading effect is enabled.
  34209. */
  34210. get: function () {
  34211. return this.imageProcessingConfiguration.colorGradingEnabled;
  34212. },
  34213. /**
  34214. * Gets wether the color grading effect is enabled.
  34215. */
  34216. set: function (value) {
  34217. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34218. },
  34219. enumerable: true,
  34220. configurable: true
  34221. });
  34222. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34223. /**
  34224. * Gets wether tonemapping is enabled or not.
  34225. */
  34226. get: function () {
  34227. return this._imageProcessingConfiguration.toneMappingEnabled;
  34228. },
  34229. /**
  34230. * Sets wether tonemapping is enabled or not
  34231. */
  34232. set: function (value) {
  34233. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34234. },
  34235. enumerable: true,
  34236. configurable: true
  34237. });
  34238. ;
  34239. ;
  34240. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34241. /**
  34242. * The camera exposure used on this material.
  34243. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34244. * This corresponds to a photographic exposure.
  34245. */
  34246. get: function () {
  34247. return this._imageProcessingConfiguration.exposure;
  34248. },
  34249. /**
  34250. * The camera exposure used on this material.
  34251. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34252. * This corresponds to a photographic exposure.
  34253. */
  34254. set: function (value) {
  34255. this._imageProcessingConfiguration.exposure = value;
  34256. },
  34257. enumerable: true,
  34258. configurable: true
  34259. });
  34260. ;
  34261. ;
  34262. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34263. /**
  34264. * Gets The camera contrast used on this material.
  34265. */
  34266. get: function () {
  34267. return this._imageProcessingConfiguration.contrast;
  34268. },
  34269. /**
  34270. * Sets The camera contrast used on this material.
  34271. */
  34272. set: function (value) {
  34273. this._imageProcessingConfiguration.contrast = value;
  34274. },
  34275. enumerable: true,
  34276. configurable: true
  34277. });
  34278. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34279. /**
  34280. * Gets the Color Grading 2D Lookup Texture.
  34281. */
  34282. get: function () {
  34283. return this._imageProcessingConfiguration.colorGradingTexture;
  34284. },
  34285. /**
  34286. * Sets the Color Grading 2D Lookup Texture.
  34287. */
  34288. set: function (value) {
  34289. this._imageProcessingConfiguration.colorGradingTexture = value;
  34290. },
  34291. enumerable: true,
  34292. configurable: true
  34293. });
  34294. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34295. /**
  34296. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34297. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34298. * 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;
  34299. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34300. */
  34301. get: function () {
  34302. return this._imageProcessingConfiguration.colorCurves;
  34303. },
  34304. /**
  34305. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34306. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34307. * 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;
  34308. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34309. */
  34310. set: function (value) {
  34311. this._imageProcessingConfiguration.colorCurves = value;
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. StandardMaterial.prototype.getClassName = function () {
  34317. return "StandardMaterial";
  34318. };
  34319. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34320. get: function () {
  34321. return this._useLogarithmicDepth;
  34322. },
  34323. set: function (value) {
  34324. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34325. this._markAllSubMeshesAsMiscDirty();
  34326. },
  34327. enumerable: true,
  34328. configurable: true
  34329. });
  34330. StandardMaterial.prototype.needAlphaBlending = function () {
  34331. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34332. };
  34333. StandardMaterial.prototype.needAlphaTesting = function () {
  34334. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34335. };
  34336. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34337. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34338. };
  34339. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34340. return this._diffuseTexture;
  34341. };
  34342. /**
  34343. * Child classes can use it to update shaders
  34344. */
  34345. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34346. if (useInstances === void 0) { useInstances = false; }
  34347. if (subMesh.effect && this.isFrozen) {
  34348. if (this._wasPreviouslyReady && subMesh.effect) {
  34349. return true;
  34350. }
  34351. }
  34352. if (!subMesh._materialDefines) {
  34353. subMesh._materialDefines = new StandardMaterialDefines();
  34354. }
  34355. var scene = this.getScene();
  34356. var defines = subMesh._materialDefines;
  34357. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34358. if (defines._renderId === scene.getRenderId()) {
  34359. return true;
  34360. }
  34361. }
  34362. var engine = scene.getEngine();
  34363. // Lights
  34364. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34365. // Textures
  34366. if (defines._areTexturesDirty) {
  34367. defines._needUVs = false;
  34368. defines.MAINUV1 = false;
  34369. defines.MAINUV2 = false;
  34370. if (scene.texturesEnabled) {
  34371. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34372. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34373. return false;
  34374. }
  34375. else {
  34376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34377. }
  34378. }
  34379. else {
  34380. defines.DIFFUSE = false;
  34381. }
  34382. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34383. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34384. return false;
  34385. }
  34386. else {
  34387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34388. }
  34389. }
  34390. else {
  34391. defines.AMBIENT = false;
  34392. }
  34393. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34394. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34395. return false;
  34396. }
  34397. else {
  34398. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34399. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34400. }
  34401. }
  34402. else {
  34403. defines.OPACITY = false;
  34404. }
  34405. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34406. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34407. return false;
  34408. }
  34409. else {
  34410. defines._needNormals = true;
  34411. defines.REFLECTION = true;
  34412. defines.ROUGHNESS = (this._roughness > 0);
  34413. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34414. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34415. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34416. switch (this._reflectionTexture.coordinatesMode) {
  34417. case BABYLON.Texture.CUBIC_MODE:
  34418. case BABYLON.Texture.INVCUBIC_MODE:
  34419. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34420. break;
  34421. case BABYLON.Texture.EXPLICIT_MODE:
  34422. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34423. break;
  34424. case BABYLON.Texture.PLANAR_MODE:
  34425. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34426. break;
  34427. case BABYLON.Texture.PROJECTION_MODE:
  34428. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34429. break;
  34430. case BABYLON.Texture.SKYBOX_MODE:
  34431. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34432. break;
  34433. case BABYLON.Texture.SPHERICAL_MODE:
  34434. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34435. break;
  34436. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34437. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34438. break;
  34439. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34440. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34441. break;
  34442. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34443. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34444. break;
  34445. }
  34446. }
  34447. }
  34448. else {
  34449. defines.REFLECTION = false;
  34450. }
  34451. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34452. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34453. return false;
  34454. }
  34455. else {
  34456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34457. }
  34458. }
  34459. else {
  34460. defines.EMISSIVE = false;
  34461. }
  34462. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34463. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34464. return false;
  34465. }
  34466. else {
  34467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34468. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34469. }
  34470. }
  34471. else {
  34472. defines.LIGHTMAP = false;
  34473. }
  34474. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34475. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34476. return false;
  34477. }
  34478. else {
  34479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34480. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34481. }
  34482. }
  34483. else {
  34484. defines.SPECULAR = false;
  34485. }
  34486. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34487. // Bump texure can not be not blocking.
  34488. if (!this._bumpTexture.isReady()) {
  34489. return false;
  34490. }
  34491. else {
  34492. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34493. defines.PARALLAX = this._useParallax;
  34494. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34495. }
  34496. }
  34497. else {
  34498. defines.BUMP = false;
  34499. }
  34500. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34501. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34502. return false;
  34503. }
  34504. else {
  34505. defines._needUVs = true;
  34506. defines.REFRACTION = true;
  34507. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34508. }
  34509. }
  34510. else {
  34511. defines.REFRACTION = false;
  34512. }
  34513. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34514. }
  34515. else {
  34516. defines.DIFFUSE = false;
  34517. defines.AMBIENT = false;
  34518. defines.OPACITY = false;
  34519. defines.REFLECTION = false;
  34520. defines.EMISSIVE = false;
  34521. defines.LIGHTMAP = false;
  34522. defines.BUMP = false;
  34523. defines.REFRACTION = false;
  34524. }
  34525. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34526. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34527. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34528. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34529. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34530. }
  34531. if (defines._areImageProcessingDirty) {
  34532. if (!this._imageProcessingConfiguration.isReady()) {
  34533. return false;
  34534. }
  34535. this._imageProcessingConfiguration.prepareDefines(defines);
  34536. }
  34537. if (defines._areFresnelDirty) {
  34538. if (StandardMaterial.FresnelEnabled) {
  34539. // Fresnel
  34540. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34541. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34542. this._reflectionFresnelParameters) {
  34543. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34544. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34545. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34546. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34547. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34548. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34549. defines._needNormals = true;
  34550. defines.FRESNEL = true;
  34551. }
  34552. }
  34553. else {
  34554. defines.FRESNEL = false;
  34555. }
  34556. }
  34557. // Misc.
  34558. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34559. // Attribs
  34560. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34561. // Values that need to be evaluated on every frame
  34562. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34563. // Get correct effect
  34564. if (defines.isDirty) {
  34565. defines.markAsProcessed();
  34566. scene.resetCachedMaterial();
  34567. // Fallbacks
  34568. var fallbacks = new BABYLON.EffectFallbacks();
  34569. if (defines.REFLECTION) {
  34570. fallbacks.addFallback(0, "REFLECTION");
  34571. }
  34572. if (defines.SPECULAR) {
  34573. fallbacks.addFallback(0, "SPECULAR");
  34574. }
  34575. if (defines.BUMP) {
  34576. fallbacks.addFallback(0, "BUMP");
  34577. }
  34578. if (defines.PARALLAX) {
  34579. fallbacks.addFallback(1, "PARALLAX");
  34580. }
  34581. if (defines.PARALLAXOCCLUSION) {
  34582. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34583. }
  34584. if (defines.SPECULAROVERALPHA) {
  34585. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34586. }
  34587. if (defines.FOG) {
  34588. fallbacks.addFallback(1, "FOG");
  34589. }
  34590. if (defines.POINTSIZE) {
  34591. fallbacks.addFallback(0, "POINTSIZE");
  34592. }
  34593. if (defines.LOGARITHMICDEPTH) {
  34594. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34595. }
  34596. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34597. if (defines.SPECULARTERM) {
  34598. fallbacks.addFallback(0, "SPECULARTERM");
  34599. }
  34600. if (defines.DIFFUSEFRESNEL) {
  34601. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34602. }
  34603. if (defines.OPACITYFRESNEL) {
  34604. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34605. }
  34606. if (defines.REFLECTIONFRESNEL) {
  34607. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34608. }
  34609. if (defines.EMISSIVEFRESNEL) {
  34610. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34611. }
  34612. if (defines.FRESNEL) {
  34613. fallbacks.addFallback(4, "FRESNEL");
  34614. }
  34615. //Attributes
  34616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34617. if (defines.NORMAL) {
  34618. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34619. }
  34620. if (defines.UV1) {
  34621. attribs.push(BABYLON.VertexBuffer.UVKind);
  34622. }
  34623. if (defines.UV2) {
  34624. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34625. }
  34626. if (defines.VERTEXCOLOR) {
  34627. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34628. }
  34629. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34630. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34631. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34632. var shaderName = "default";
  34633. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34634. "vFogInfos", "vFogColor", "pointSize",
  34635. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34636. "mBones",
  34637. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34638. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34639. "logarithmicDepthConstant", "vTangentSpaceParams"
  34640. ];
  34641. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34642. var uniformBuffers = ["Material", "Scene"];
  34643. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34644. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34645. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34646. uniformsNames: uniforms,
  34647. uniformBuffersNames: uniformBuffers,
  34648. samplers: samplers,
  34649. defines: defines,
  34650. maxSimultaneousLights: this._maxSimultaneousLights
  34651. });
  34652. if (this.customShaderNameResolve) {
  34653. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34654. }
  34655. var join = defines.toString();
  34656. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34657. attributes: attribs,
  34658. uniformsNames: uniforms,
  34659. uniformBuffersNames: uniformBuffers,
  34660. samplers: samplers,
  34661. defines: join,
  34662. fallbacks: fallbacks,
  34663. onCompiled: this.onCompiled,
  34664. onError: this.onError,
  34665. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34666. }, engine), defines);
  34667. this.buildUniformLayout();
  34668. }
  34669. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34670. return false;
  34671. }
  34672. defines._renderId = scene.getRenderId();
  34673. this._wasPreviouslyReady = true;
  34674. return true;
  34675. };
  34676. StandardMaterial.prototype.buildUniformLayout = function () {
  34677. // Order is important !
  34678. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34679. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34680. this._uniformBuffer.addUniform("opacityParts", 4);
  34681. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34682. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34683. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34684. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34685. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34686. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34687. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34688. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34689. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34690. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34691. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34692. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34693. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34694. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34695. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34696. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34697. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34698. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34699. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34700. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34701. this._uniformBuffer.addUniform("specularMatrix", 16);
  34702. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34703. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34704. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34705. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34706. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34707. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34708. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34709. this._uniformBuffer.addUniform("pointSize", 1);
  34710. this._uniformBuffer.create();
  34711. };
  34712. StandardMaterial.prototype.unbind = function () {
  34713. if (this._activeEffect) {
  34714. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34715. this._activeEffect.setTexture("reflection2DSampler", null);
  34716. }
  34717. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34718. this._activeEffect.setTexture("refraction2DSampler", null);
  34719. }
  34720. }
  34721. _super.prototype.unbind.call(this);
  34722. };
  34723. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34724. var scene = this.getScene();
  34725. var defines = subMesh._materialDefines;
  34726. if (!defines) {
  34727. return;
  34728. }
  34729. var effect = subMesh.effect;
  34730. if (!effect) {
  34731. return;
  34732. }
  34733. this._activeEffect = effect;
  34734. // Matrices
  34735. this.bindOnlyWorldMatrix(world);
  34736. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34737. // Bones
  34738. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34739. if (mustRebind) {
  34740. this._uniformBuffer.bindToEffect(effect, "Material");
  34741. this.bindViewProjection(effect);
  34742. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34743. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34744. // Fresnel
  34745. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34746. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34747. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34748. }
  34749. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34750. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34751. }
  34752. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34753. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34754. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34755. }
  34756. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34757. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34758. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34759. }
  34760. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34761. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34762. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34763. }
  34764. }
  34765. // Textures
  34766. if (scene.texturesEnabled) {
  34767. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34768. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34769. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34770. }
  34771. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34772. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34773. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34774. }
  34775. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34776. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34777. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34778. }
  34779. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34780. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34781. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34782. }
  34783. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34784. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34785. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34786. }
  34787. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34788. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34789. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34790. }
  34791. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34792. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34793. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34794. }
  34795. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34796. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34797. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34798. if (scene._mirroredCameraPosition) {
  34799. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34800. }
  34801. else {
  34802. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34803. }
  34804. }
  34805. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34806. var depth = 1.0;
  34807. if (!this._refractionTexture.isCube) {
  34808. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34809. if (this._refractionTexture.depth) {
  34810. depth = this._refractionTexture.depth;
  34811. }
  34812. }
  34813. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34814. }
  34815. }
  34816. // Point size
  34817. if (this.pointsCloud) {
  34818. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34819. }
  34820. if (defines.SPECULARTERM) {
  34821. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34822. }
  34823. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34824. // Diffuse
  34825. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34826. }
  34827. // Textures
  34828. if (scene.texturesEnabled) {
  34829. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34830. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34831. }
  34832. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34833. effect.setTexture("ambientSampler", this._ambientTexture);
  34834. }
  34835. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34836. effect.setTexture("opacitySampler", this._opacityTexture);
  34837. }
  34838. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34839. if (this._reflectionTexture.isCube) {
  34840. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34841. }
  34842. else {
  34843. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34844. }
  34845. }
  34846. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34847. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34848. }
  34849. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34850. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34851. }
  34852. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34853. effect.setTexture("specularSampler", this._specularTexture);
  34854. }
  34855. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34856. effect.setTexture("bumpSampler", this._bumpTexture);
  34857. }
  34858. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34859. var depth = 1.0;
  34860. if (this._refractionTexture.isCube) {
  34861. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34862. }
  34863. else {
  34864. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34865. }
  34866. }
  34867. }
  34868. // Clip plane
  34869. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34870. // Colors
  34871. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34872. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34873. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34874. }
  34875. if (mustRebind || !this.isFrozen) {
  34876. // Lights
  34877. if (scene.lightsEnabled && !this._disableLighting) {
  34878. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34879. }
  34880. // View
  34881. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34882. this.bindView(effect);
  34883. }
  34884. // Fog
  34885. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34886. // Morph targets
  34887. if (defines.NUM_MORPH_INFLUENCERS) {
  34888. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34889. }
  34890. // Log. depth
  34891. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34892. // image processing
  34893. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  34894. this._imageProcessingConfiguration.bind(this._activeEffect);
  34895. }
  34896. }
  34897. this._uniformBuffer.update();
  34898. this._afterBind(mesh, this._activeEffect);
  34899. };
  34900. StandardMaterial.prototype.getAnimatables = function () {
  34901. var results = [];
  34902. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34903. results.push(this._diffuseTexture);
  34904. }
  34905. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34906. results.push(this._ambientTexture);
  34907. }
  34908. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34909. results.push(this._opacityTexture);
  34910. }
  34911. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34912. results.push(this._reflectionTexture);
  34913. }
  34914. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34915. results.push(this._emissiveTexture);
  34916. }
  34917. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34918. results.push(this._specularTexture);
  34919. }
  34920. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34921. results.push(this._bumpTexture);
  34922. }
  34923. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34924. results.push(this._lightmapTexture);
  34925. }
  34926. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34927. results.push(this._refractionTexture);
  34928. }
  34929. return results;
  34930. };
  34931. StandardMaterial.prototype.getActiveTextures = function () {
  34932. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34933. if (this._diffuseTexture) {
  34934. activeTextures.push(this._diffuseTexture);
  34935. }
  34936. if (this._ambientTexture) {
  34937. activeTextures.push(this._ambientTexture);
  34938. }
  34939. if (this._opacityTexture) {
  34940. activeTextures.push(this._opacityTexture);
  34941. }
  34942. if (this._reflectionTexture) {
  34943. activeTextures.push(this._reflectionTexture);
  34944. }
  34945. if (this._emissiveTexture) {
  34946. activeTextures.push(this._emissiveTexture);
  34947. }
  34948. if (this._specularTexture) {
  34949. activeTextures.push(this._specularTexture);
  34950. }
  34951. if (this._bumpTexture) {
  34952. activeTextures.push(this._bumpTexture);
  34953. }
  34954. if (this._lightmapTexture) {
  34955. activeTextures.push(this._lightmapTexture);
  34956. }
  34957. if (this._refractionTexture) {
  34958. activeTextures.push(this._refractionTexture);
  34959. }
  34960. return activeTextures;
  34961. };
  34962. StandardMaterial.prototype.hasTexture = function (texture) {
  34963. if (_super.prototype.hasTexture.call(this, texture)) {
  34964. return true;
  34965. }
  34966. if (this._diffuseTexture === texture) {
  34967. return true;
  34968. }
  34969. if (this._ambientTexture === texture) {
  34970. return true;
  34971. }
  34972. if (this._opacityTexture === texture) {
  34973. return true;
  34974. }
  34975. if (this._reflectionTexture === texture) {
  34976. return true;
  34977. }
  34978. if (this._emissiveTexture === texture) {
  34979. return true;
  34980. }
  34981. if (this._specularTexture === texture) {
  34982. return true;
  34983. }
  34984. if (this._bumpTexture === texture) {
  34985. return true;
  34986. }
  34987. if (this._lightmapTexture === texture) {
  34988. return true;
  34989. }
  34990. if (this._refractionTexture === texture) {
  34991. return true;
  34992. }
  34993. return false;
  34994. };
  34995. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34996. if (forceDisposeTextures) {
  34997. if (this._diffuseTexture) {
  34998. this._diffuseTexture.dispose();
  34999. }
  35000. if (this._ambientTexture) {
  35001. this._ambientTexture.dispose();
  35002. }
  35003. if (this._opacityTexture) {
  35004. this._opacityTexture.dispose();
  35005. }
  35006. if (this._reflectionTexture) {
  35007. this._reflectionTexture.dispose();
  35008. }
  35009. if (this._emissiveTexture) {
  35010. this._emissiveTexture.dispose();
  35011. }
  35012. if (this._specularTexture) {
  35013. this._specularTexture.dispose();
  35014. }
  35015. if (this._bumpTexture) {
  35016. this._bumpTexture.dispose();
  35017. }
  35018. if (this._lightmapTexture) {
  35019. this._lightmapTexture.dispose();
  35020. }
  35021. if (this._refractionTexture) {
  35022. this._refractionTexture.dispose();
  35023. }
  35024. }
  35025. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35026. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35027. }
  35028. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35029. };
  35030. StandardMaterial.prototype.clone = function (name) {
  35031. var _this = this;
  35032. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35033. result.name = name;
  35034. result.id = name;
  35035. return result;
  35036. };
  35037. StandardMaterial.prototype.serialize = function () {
  35038. return BABYLON.SerializationHelper.Serialize(this);
  35039. };
  35040. // Statics
  35041. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35042. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35043. };
  35044. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35045. get: function () {
  35046. return StandardMaterial._DiffuseTextureEnabled;
  35047. },
  35048. set: function (value) {
  35049. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35050. return;
  35051. }
  35052. StandardMaterial._DiffuseTextureEnabled = value;
  35053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35054. },
  35055. enumerable: true,
  35056. configurable: true
  35057. });
  35058. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35059. get: function () {
  35060. return StandardMaterial._AmbientTextureEnabled;
  35061. },
  35062. set: function (value) {
  35063. if (StandardMaterial._AmbientTextureEnabled === value) {
  35064. return;
  35065. }
  35066. StandardMaterial._AmbientTextureEnabled = value;
  35067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35068. },
  35069. enumerable: true,
  35070. configurable: true
  35071. });
  35072. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35073. get: function () {
  35074. return StandardMaterial._OpacityTextureEnabled;
  35075. },
  35076. set: function (value) {
  35077. if (StandardMaterial._OpacityTextureEnabled === value) {
  35078. return;
  35079. }
  35080. StandardMaterial._OpacityTextureEnabled = value;
  35081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35082. },
  35083. enumerable: true,
  35084. configurable: true
  35085. });
  35086. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35087. get: function () {
  35088. return StandardMaterial._ReflectionTextureEnabled;
  35089. },
  35090. set: function (value) {
  35091. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35092. return;
  35093. }
  35094. StandardMaterial._ReflectionTextureEnabled = value;
  35095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35096. },
  35097. enumerable: true,
  35098. configurable: true
  35099. });
  35100. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35101. get: function () {
  35102. return StandardMaterial._EmissiveTextureEnabled;
  35103. },
  35104. set: function (value) {
  35105. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35106. return;
  35107. }
  35108. StandardMaterial._EmissiveTextureEnabled = value;
  35109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35110. },
  35111. enumerable: true,
  35112. configurable: true
  35113. });
  35114. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35115. get: function () {
  35116. return StandardMaterial._SpecularTextureEnabled;
  35117. },
  35118. set: function (value) {
  35119. if (StandardMaterial._SpecularTextureEnabled === value) {
  35120. return;
  35121. }
  35122. StandardMaterial._SpecularTextureEnabled = value;
  35123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35124. },
  35125. enumerable: true,
  35126. configurable: true
  35127. });
  35128. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35129. get: function () {
  35130. return StandardMaterial._BumpTextureEnabled;
  35131. },
  35132. set: function (value) {
  35133. if (StandardMaterial._BumpTextureEnabled === value) {
  35134. return;
  35135. }
  35136. StandardMaterial._BumpTextureEnabled = value;
  35137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35138. },
  35139. enumerable: true,
  35140. configurable: true
  35141. });
  35142. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35143. get: function () {
  35144. return StandardMaterial._LightmapTextureEnabled;
  35145. },
  35146. set: function (value) {
  35147. if (StandardMaterial._LightmapTextureEnabled === value) {
  35148. return;
  35149. }
  35150. StandardMaterial._LightmapTextureEnabled = value;
  35151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35157. get: function () {
  35158. return StandardMaterial._RefractionTextureEnabled;
  35159. },
  35160. set: function (value) {
  35161. if (StandardMaterial._RefractionTextureEnabled === value) {
  35162. return;
  35163. }
  35164. StandardMaterial._RefractionTextureEnabled = value;
  35165. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35171. get: function () {
  35172. return StandardMaterial._ColorGradingTextureEnabled;
  35173. },
  35174. set: function (value) {
  35175. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35176. return;
  35177. }
  35178. StandardMaterial._ColorGradingTextureEnabled = value;
  35179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35180. },
  35181. enumerable: true,
  35182. configurable: true
  35183. });
  35184. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35185. get: function () {
  35186. return StandardMaterial._FresnelEnabled;
  35187. },
  35188. set: function (value) {
  35189. if (StandardMaterial._FresnelEnabled === value) {
  35190. return;
  35191. }
  35192. StandardMaterial._FresnelEnabled = value;
  35193. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. // Flags used to enable or disable a type of texture for all Standard Materials
  35199. StandardMaterial._DiffuseTextureEnabled = true;
  35200. StandardMaterial._AmbientTextureEnabled = true;
  35201. StandardMaterial._OpacityTextureEnabled = true;
  35202. StandardMaterial._ReflectionTextureEnabled = true;
  35203. StandardMaterial._EmissiveTextureEnabled = true;
  35204. StandardMaterial._SpecularTextureEnabled = true;
  35205. StandardMaterial._BumpTextureEnabled = true;
  35206. StandardMaterial._LightmapTextureEnabled = true;
  35207. StandardMaterial._RefractionTextureEnabled = true;
  35208. StandardMaterial._ColorGradingTextureEnabled = true;
  35209. StandardMaterial._FresnelEnabled = true;
  35210. __decorate([
  35211. BABYLON.serializeAsTexture("diffuseTexture")
  35212. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35213. __decorate([
  35214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35215. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35216. __decorate([
  35217. BABYLON.serializeAsTexture("ambientTexture")
  35218. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35219. __decorate([
  35220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35221. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35222. __decorate([
  35223. BABYLON.serializeAsTexture("opacityTexture")
  35224. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35225. __decorate([
  35226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35227. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35228. __decorate([
  35229. BABYLON.serializeAsTexture("reflectionTexture")
  35230. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35231. __decorate([
  35232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35233. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35234. __decorate([
  35235. BABYLON.serializeAsTexture("emissiveTexture")
  35236. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35237. __decorate([
  35238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35239. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35240. __decorate([
  35241. BABYLON.serializeAsTexture("specularTexture")
  35242. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35243. __decorate([
  35244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35245. ], StandardMaterial.prototype, "specularTexture", void 0);
  35246. __decorate([
  35247. BABYLON.serializeAsTexture("bumpTexture")
  35248. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35249. __decorate([
  35250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35251. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35252. __decorate([
  35253. BABYLON.serializeAsTexture("lightmapTexture")
  35254. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35255. __decorate([
  35256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35257. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35258. __decorate([
  35259. BABYLON.serializeAsTexture("refractionTexture")
  35260. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35261. __decorate([
  35262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35263. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35264. __decorate([
  35265. BABYLON.serializeAsColor3("ambient")
  35266. ], StandardMaterial.prototype, "ambientColor", void 0);
  35267. __decorate([
  35268. BABYLON.serializeAsColor3("diffuse")
  35269. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35270. __decorate([
  35271. BABYLON.serializeAsColor3("specular")
  35272. ], StandardMaterial.prototype, "specularColor", void 0);
  35273. __decorate([
  35274. BABYLON.serializeAsColor3("emissive")
  35275. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35276. __decorate([
  35277. BABYLON.serialize()
  35278. ], StandardMaterial.prototype, "specularPower", void 0);
  35279. __decorate([
  35280. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35281. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35282. __decorate([
  35283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35284. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35285. __decorate([
  35286. BABYLON.serialize("useEmissiveAsIllumination")
  35287. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35288. __decorate([
  35289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35290. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35291. __decorate([
  35292. BABYLON.serialize("linkEmissiveWithDiffuse")
  35293. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35294. __decorate([
  35295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35296. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35297. __decorate([
  35298. BABYLON.serialize("useSpecularOverAlpha")
  35299. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35300. __decorate([
  35301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35302. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35303. __decorate([
  35304. BABYLON.serialize("useReflectionOverAlpha")
  35305. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35306. __decorate([
  35307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35308. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35309. __decorate([
  35310. BABYLON.serialize("disableLighting")
  35311. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35312. __decorate([
  35313. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35314. ], StandardMaterial.prototype, "disableLighting", void 0);
  35315. __decorate([
  35316. BABYLON.serialize("useParallax")
  35317. ], StandardMaterial.prototype, "_useParallax", void 0);
  35318. __decorate([
  35319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35320. ], StandardMaterial.prototype, "useParallax", void 0);
  35321. __decorate([
  35322. BABYLON.serialize("useParallaxOcclusion")
  35323. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35324. __decorate([
  35325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35326. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35327. __decorate([
  35328. BABYLON.serialize()
  35329. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35330. __decorate([
  35331. BABYLON.serialize("roughness")
  35332. ], StandardMaterial.prototype, "_roughness", void 0);
  35333. __decorate([
  35334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35335. ], StandardMaterial.prototype, "roughness", void 0);
  35336. __decorate([
  35337. BABYLON.serialize()
  35338. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35339. __decorate([
  35340. BABYLON.serialize()
  35341. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35342. __decorate([
  35343. BABYLON.serialize("useLightmapAsShadowmap")
  35344. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35345. __decorate([
  35346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35347. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35348. __decorate([
  35349. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35350. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35351. __decorate([
  35352. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35353. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35354. __decorate([
  35355. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35356. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35357. __decorate([
  35358. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35359. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35360. __decorate([
  35361. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35362. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35363. __decorate([
  35364. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35365. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35366. __decorate([
  35367. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35368. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35369. __decorate([
  35370. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35371. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35372. __decorate([
  35373. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35374. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35375. __decorate([
  35376. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35377. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35378. __decorate([
  35379. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35380. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35381. __decorate([
  35382. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35383. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35384. __decorate([
  35385. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35386. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35387. __decorate([
  35388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35389. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35390. __decorate([
  35391. BABYLON.serialize("maxSimultaneousLights")
  35392. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35393. __decorate([
  35394. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35395. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35396. __decorate([
  35397. BABYLON.serialize("invertNormalMapX")
  35398. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35399. __decorate([
  35400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35401. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35402. __decorate([
  35403. BABYLON.serialize("invertNormalMapY")
  35404. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35405. __decorate([
  35406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35407. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35408. __decorate([
  35409. BABYLON.serialize("twoSidedLighting")
  35410. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35411. __decorate([
  35412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35413. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35414. __decorate([
  35415. BABYLON.serialize()
  35416. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35417. return StandardMaterial;
  35418. }(BABYLON.PushMaterial));
  35419. BABYLON.StandardMaterial = StandardMaterial;
  35420. })(BABYLON || (BABYLON = {}));
  35421. //# sourceMappingURL=babylon.standardMaterial.js.map
  35422. var BABYLON;
  35423. (function (BABYLON) {
  35424. var PBRMaterialDefines = /** @class */ (function (_super) {
  35425. __extends(PBRMaterialDefines, _super);
  35426. function PBRMaterialDefines() {
  35427. var _this = _super.call(this) || this;
  35428. _this.PBR = true;
  35429. _this.MAINUV1 = false;
  35430. _this.MAINUV2 = false;
  35431. _this.UV1 = false;
  35432. _this.UV2 = false;
  35433. _this.ALBEDO = false;
  35434. _this.ALBEDODIRECTUV = 0;
  35435. _this.VERTEXCOLOR = false;
  35436. _this.AMBIENT = false;
  35437. _this.AMBIENTDIRECTUV = 0;
  35438. _this.AMBIENTINGRAYSCALE = false;
  35439. _this.OPACITY = false;
  35440. _this.VERTEXALPHA = false;
  35441. _this.OPACITYDIRECTUV = 0;
  35442. _this.OPACITYRGB = false;
  35443. _this.ALPHATEST = false;
  35444. _this.DEPTHPREPASS = false;
  35445. _this.ALPHABLEND = false;
  35446. _this.ALPHAFROMALBEDO = false;
  35447. _this.ALPHATESTVALUE = 0.5;
  35448. _this.SPECULAROVERALPHA = false;
  35449. _this.RADIANCEOVERALPHA = false;
  35450. _this.ALPHAFRESNEL = false;
  35451. _this.PREMULTIPLYALPHA = false;
  35452. _this.EMISSIVE = false;
  35453. _this.EMISSIVEDIRECTUV = 0;
  35454. _this.REFLECTIVITY = false;
  35455. _this.REFLECTIVITYDIRECTUV = 0;
  35456. _this.SPECULARTERM = false;
  35457. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35458. _this.MICROSURFACEAUTOMATIC = false;
  35459. _this.LODBASEDMICROSFURACE = false;
  35460. _this.MICROSURFACEMAP = false;
  35461. _this.MICROSURFACEMAPDIRECTUV = 0;
  35462. _this.METALLICWORKFLOW = false;
  35463. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35464. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35465. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35466. _this.AOSTOREINMETALMAPRED = false;
  35467. _this.ENVIRONMENTBRDF = false;
  35468. _this.NORMAL = false;
  35469. _this.TANGENT = false;
  35470. _this.BUMP = false;
  35471. _this.BUMPDIRECTUV = 0;
  35472. _this.PARALLAX = false;
  35473. _this.PARALLAXOCCLUSION = false;
  35474. _this.NORMALXYSCALE = true;
  35475. _this.LIGHTMAP = false;
  35476. _this.LIGHTMAPDIRECTUV = 0;
  35477. _this.USELIGHTMAPASSHADOWMAP = false;
  35478. _this.REFLECTION = false;
  35479. _this.REFLECTIONMAP_3D = false;
  35480. _this.REFLECTIONMAP_SPHERICAL = false;
  35481. _this.REFLECTIONMAP_PLANAR = false;
  35482. _this.REFLECTIONMAP_CUBIC = false;
  35483. _this.REFLECTIONMAP_PROJECTION = false;
  35484. _this.REFLECTIONMAP_SKYBOX = false;
  35485. _this.REFLECTIONMAP_EXPLICIT = false;
  35486. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35487. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35488. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35489. _this.INVERTCUBICMAP = false;
  35490. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35491. _this.USESPHERICALINVERTEX = false;
  35492. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35493. _this.LODINREFLECTIONALPHA = false;
  35494. _this.GAMMAREFLECTION = false;
  35495. _this.RADIANCEOCCLUSION = false;
  35496. _this.HORIZONOCCLUSION = false;
  35497. _this.REFRACTION = false;
  35498. _this.REFRACTIONMAP_3D = false;
  35499. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35500. _this.LODINREFRACTIONALPHA = false;
  35501. _this.GAMMAREFRACTION = false;
  35502. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35503. _this.INSTANCES = false;
  35504. _this.NUM_BONE_INFLUENCERS = 0;
  35505. _this.BonesPerMesh = 0;
  35506. _this.NONUNIFORMSCALING = false;
  35507. _this.MORPHTARGETS = false;
  35508. _this.MORPHTARGETS_NORMAL = false;
  35509. _this.MORPHTARGETS_TANGENT = false;
  35510. _this.NUM_MORPH_INFLUENCERS = 0;
  35511. _this.IMAGEPROCESSING = false;
  35512. _this.VIGNETTE = false;
  35513. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35514. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35515. _this.TONEMAPPING = false;
  35516. _this.CONTRAST = false;
  35517. _this.COLORCURVES = false;
  35518. _this.COLORGRADING = false;
  35519. _this.COLORGRADING3D = false;
  35520. _this.SAMPLER3DGREENDEPTH = false;
  35521. _this.SAMPLER3DBGRMAP = false;
  35522. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35523. _this.EXPOSURE = false;
  35524. _this.USEPHYSICALLIGHTFALLOFF = false;
  35525. _this.TWOSIDEDLIGHTING = false;
  35526. _this.SHADOWFLOAT = false;
  35527. _this.CLIPPLANE = false;
  35528. _this.POINTSIZE = false;
  35529. _this.FOG = false;
  35530. _this.LOGARITHMICDEPTH = false;
  35531. _this.FORCENORMALFORWARD = false;
  35532. _this.rebuild();
  35533. return _this;
  35534. }
  35535. PBRMaterialDefines.prototype.reset = function () {
  35536. _super.prototype.reset.call(this);
  35537. this.ALPHATESTVALUE = 0.5;
  35538. this.PBR = true;
  35539. };
  35540. return PBRMaterialDefines;
  35541. }(BABYLON.MaterialDefines));
  35542. /**
  35543. * The Physically based material base class of BJS.
  35544. *
  35545. * This offers the main features of a standard PBR material.
  35546. * For more information, please refer to the documentation :
  35547. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35548. */
  35549. var PBRBaseMaterial = /** @class */ (function (_super) {
  35550. __extends(PBRBaseMaterial, _super);
  35551. /**
  35552. * Instantiates a new PBRMaterial instance.
  35553. *
  35554. * @param name The material name
  35555. * @param scene The scene the material will be use in.
  35556. */
  35557. function PBRBaseMaterial(name, scene) {
  35558. var _this = _super.call(this, name, scene) || this;
  35559. /**
  35560. * Intensity of the direct lights e.g. the four lights available in your scene.
  35561. * This impacts both the direct diffuse and specular highlights.
  35562. */
  35563. _this._directIntensity = 1.0;
  35564. /**
  35565. * Intensity of the emissive part of the material.
  35566. * This helps controlling the emissive effect without modifying the emissive color.
  35567. */
  35568. _this._emissiveIntensity = 1.0;
  35569. /**
  35570. * Intensity of the environment e.g. how much the environment will light the object
  35571. * either through harmonics for rough material or through the refelction for shiny ones.
  35572. */
  35573. _this._environmentIntensity = 1.0;
  35574. /**
  35575. * This is a special control allowing the reduction of the specular highlights coming from the
  35576. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35577. */
  35578. _this._specularIntensity = 1.0;
  35579. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35580. /**
  35581. * Debug Control allowing disabling the bump map on this material.
  35582. */
  35583. _this._disableBumpMap = false;
  35584. /**
  35585. * AKA Occlusion Texture Intensity in other nomenclature.
  35586. */
  35587. _this._ambientTextureStrength = 1.0;
  35588. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35589. /**
  35590. * AKA Diffuse Color in other nomenclature.
  35591. */
  35592. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35593. /**
  35594. * AKA Specular Color in other nomenclature.
  35595. */
  35596. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35597. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35598. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35599. /**
  35600. * AKA Glossiness in other nomenclature.
  35601. */
  35602. _this._microSurface = 0.9;
  35603. /**
  35604. * source material index of refraction (IOR)' / 'destination material IOR.
  35605. */
  35606. _this._indexOfRefraction = 0.66;
  35607. /**
  35608. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35609. */
  35610. _this._invertRefractionY = false;
  35611. /**
  35612. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35613. * Materials half opaque for instance using refraction could benefit from this control.
  35614. */
  35615. _this._linkRefractionWithTransparency = false;
  35616. _this._useLightmapAsShadowmap = false;
  35617. /**
  35618. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35619. * makes the reflect vector face the model (under horizon).
  35620. */
  35621. _this._useHorizonOcclusion = false; // USEHORIZONOCCLUSION
  35622. /**
  35623. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35624. * too much the area relying on ambient texture to define their ambient occlusion.
  35625. */
  35626. _this._useRadianceOcclusion = false;
  35627. /**
  35628. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35629. */
  35630. _this._useAlphaFromAlbedoTexture = false;
  35631. /**
  35632. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35633. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35634. */
  35635. _this._useSpecularOverAlpha = true;
  35636. /**
  35637. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35638. */
  35639. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35640. /**
  35641. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35642. */
  35643. _this._useRoughnessFromMetallicTextureAlpha = true;
  35644. /**
  35645. * Specifies if the metallic texture contains the roughness information in its green channel.
  35646. */
  35647. _this._useRoughnessFromMetallicTextureGreen = false;
  35648. /**
  35649. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35650. */
  35651. _this._useMetallnessFromMetallicTextureBlue = false;
  35652. /**
  35653. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35654. */
  35655. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35656. /**
  35657. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35658. */
  35659. _this._useAmbientInGrayScale = false;
  35660. /**
  35661. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35662. * The material will try to infer what glossiness each pixel should be.
  35663. */
  35664. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35665. /**
  35666. * BJS is using an harcoded light falloff based on a manually sets up range.
  35667. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35668. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35669. */
  35670. _this._usePhysicalLightFalloff = true;
  35671. /**
  35672. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35673. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35674. */
  35675. _this._useRadianceOverAlpha = true;
  35676. /**
  35677. * Allows using the bump map in parallax mode.
  35678. */
  35679. _this._useParallax = false;
  35680. /**
  35681. * Allows using the bump map in parallax occlusion mode.
  35682. */
  35683. _this._useParallaxOcclusion = false;
  35684. /**
  35685. * Controls the scale bias of the parallax mode.
  35686. */
  35687. _this._parallaxScaleBias = 0.05;
  35688. /**
  35689. * If sets to true, disables all the lights affecting the material.
  35690. */
  35691. _this._disableLighting = false;
  35692. /**
  35693. * Number of Simultaneous lights allowed on the material.
  35694. */
  35695. _this._maxSimultaneousLights = 4;
  35696. /**
  35697. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35698. */
  35699. _this._invertNormalMapX = false;
  35700. /**
  35701. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35702. */
  35703. _this._invertNormalMapY = false;
  35704. /**
  35705. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35706. */
  35707. _this._twoSidedLighting = false;
  35708. /**
  35709. * Defines the alpha limits in alpha test mode.
  35710. */
  35711. _this._alphaCutOff = 0.4;
  35712. /**
  35713. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35714. */
  35715. _this._forceAlphaTest = false;
  35716. /**
  35717. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35718. * And/Or occlude the blended part.
  35719. */
  35720. _this._useAlphaFresnel = false;
  35721. /**
  35722. * The transparency mode of the material.
  35723. */
  35724. _this._transparencyMode = null;
  35725. /**
  35726. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35727. * from cos thetav and roughness:
  35728. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35729. */
  35730. _this._environmentBRDFTexture = null;
  35731. /**
  35732. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35733. */
  35734. _this._forceIrradianceInFragment = false;
  35735. /**
  35736. * Force normal to face away from face.
  35737. * (Temporary internal fix to remove before 3.1)
  35738. */
  35739. _this._forceNormalForward = false;
  35740. _this._renderTargets = new BABYLON.SmartArray(16);
  35741. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35742. // Setup the default processing configuration to the scene.
  35743. _this._attachImageProcessingConfiguration(null);
  35744. _this.getRenderTargetTextures = function () {
  35745. _this._renderTargets.reset();
  35746. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35747. _this._renderTargets.push(_this._reflectionTexture);
  35748. }
  35749. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35750. _this._renderTargets.push(_this._refractionTexture);
  35751. }
  35752. return _this._renderTargets;
  35753. };
  35754. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35755. return _this;
  35756. }
  35757. /**
  35758. * Attaches a new image processing configuration to the PBR Material.
  35759. * @param configuration
  35760. */
  35761. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35762. var _this = this;
  35763. if (configuration === this._imageProcessingConfiguration) {
  35764. return;
  35765. }
  35766. // Detaches observer.
  35767. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35768. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35769. }
  35770. // Pick the scene configuration if needed.
  35771. if (!configuration) {
  35772. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35773. }
  35774. else {
  35775. this._imageProcessingConfiguration = configuration;
  35776. }
  35777. // Attaches observer.
  35778. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35779. _this._markAllSubMeshesAsImageProcessingDirty();
  35780. });
  35781. };
  35782. PBRBaseMaterial.prototype.getClassName = function () {
  35783. return "PBRBaseMaterial";
  35784. };
  35785. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35786. get: function () {
  35787. return this._useLogarithmicDepth;
  35788. },
  35789. set: function (value) {
  35790. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35791. },
  35792. enumerable: true,
  35793. configurable: true
  35794. });
  35795. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35796. /**
  35797. * Gets the current transparency mode.
  35798. */
  35799. get: function () {
  35800. return this._transparencyMode;
  35801. },
  35802. /**
  35803. * Sets the transparency mode of the material.
  35804. */
  35805. set: function (value) {
  35806. if (this._transparencyMode === value) {
  35807. return;
  35808. }
  35809. this._transparencyMode = value;
  35810. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35811. this._markAllSubMeshesAsTexturesDirty();
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  35817. /**
  35818. * Returns true if alpha blending should be disabled.
  35819. */
  35820. get: function () {
  35821. return (this._linkRefractionWithTransparency ||
  35822. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35823. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. /**
  35829. * Specifies whether or not this material should be rendered in alpha blend mode.
  35830. */
  35831. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35832. if (this._disableAlphaBlending) {
  35833. return false;
  35834. }
  35835. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35836. };
  35837. /**
  35838. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  35839. */
  35840. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35841. if (this._disableAlphaBlending) {
  35842. return false;
  35843. }
  35844. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  35845. };
  35846. /**
  35847. * Specifies whether or not this material should be rendered in alpha test mode.
  35848. */
  35849. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35850. if (this._forceAlphaTest) {
  35851. return true;
  35852. }
  35853. if (this._linkRefractionWithTransparency) {
  35854. return false;
  35855. }
  35856. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35857. };
  35858. /**
  35859. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35860. */
  35861. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35862. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35863. };
  35864. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35865. return this._albedoTexture;
  35866. };
  35867. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35868. var _this = this;
  35869. if (subMesh.effect && this.isFrozen) {
  35870. if (this._wasPreviouslyReady) {
  35871. return true;
  35872. }
  35873. }
  35874. if (!subMesh._materialDefines) {
  35875. subMesh._materialDefines = new PBRMaterialDefines();
  35876. }
  35877. var scene = this.getScene();
  35878. var defines = subMesh._materialDefines;
  35879. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35880. if (defines._renderId === scene.getRenderId()) {
  35881. return true;
  35882. }
  35883. }
  35884. var engine = scene.getEngine();
  35885. // Lights
  35886. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35887. defines._needNormals = true;
  35888. // Textures
  35889. if (defines._areTexturesDirty) {
  35890. defines._needUVs = false;
  35891. if (scene.texturesEnabled) {
  35892. if (scene.getEngine().getCaps().textureLOD) {
  35893. defines.LODBASEDMICROSFURACE = true;
  35894. }
  35895. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35896. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35897. return false;
  35898. }
  35899. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35900. }
  35901. else {
  35902. defines.ALBEDO = false;
  35903. }
  35904. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35905. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35906. return false;
  35907. }
  35908. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35909. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35910. }
  35911. else {
  35912. defines.AMBIENT = false;
  35913. }
  35914. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35915. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35916. return false;
  35917. }
  35918. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35919. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35920. }
  35921. else {
  35922. defines.OPACITY = false;
  35923. }
  35924. var reflectionTexture = this._getReflectionTexture();
  35925. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35926. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35927. return false;
  35928. }
  35929. defines.REFLECTION = true;
  35930. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35931. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35932. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35933. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35934. defines.INVERTCUBICMAP = true;
  35935. }
  35936. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35937. switch (reflectionTexture.coordinatesMode) {
  35938. case BABYLON.Texture.CUBIC_MODE:
  35939. case BABYLON.Texture.INVCUBIC_MODE:
  35940. defines.REFLECTIONMAP_CUBIC = true;
  35941. break;
  35942. case BABYLON.Texture.EXPLICIT_MODE:
  35943. defines.REFLECTIONMAP_EXPLICIT = true;
  35944. break;
  35945. case BABYLON.Texture.PLANAR_MODE:
  35946. defines.REFLECTIONMAP_PLANAR = true;
  35947. break;
  35948. case BABYLON.Texture.PROJECTION_MODE:
  35949. defines.REFLECTIONMAP_PROJECTION = true;
  35950. break;
  35951. case BABYLON.Texture.SKYBOX_MODE:
  35952. defines.REFLECTIONMAP_SKYBOX = true;
  35953. break;
  35954. case BABYLON.Texture.SPHERICAL_MODE:
  35955. defines.REFLECTIONMAP_SPHERICAL = true;
  35956. break;
  35957. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35958. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35959. break;
  35960. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35961. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35962. break;
  35963. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35964. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35965. break;
  35966. }
  35967. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35968. if (reflectionTexture.sphericalPolynomial) {
  35969. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35970. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35971. defines.USESPHERICALINVERTEX = false;
  35972. }
  35973. else {
  35974. defines.USESPHERICALINVERTEX = true;
  35975. }
  35976. }
  35977. }
  35978. }
  35979. else {
  35980. defines.REFLECTION = false;
  35981. defines.REFLECTIONMAP_3D = false;
  35982. defines.REFLECTIONMAP_SPHERICAL = false;
  35983. defines.REFLECTIONMAP_PLANAR = false;
  35984. defines.REFLECTIONMAP_CUBIC = false;
  35985. defines.REFLECTIONMAP_PROJECTION = false;
  35986. defines.REFLECTIONMAP_SKYBOX = false;
  35987. defines.REFLECTIONMAP_EXPLICIT = false;
  35988. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35989. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35990. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35991. defines.INVERTCUBICMAP = false;
  35992. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35993. defines.USESPHERICALINVERTEX = false;
  35994. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35995. defines.LODINREFLECTIONALPHA = false;
  35996. defines.GAMMAREFLECTION = false;
  35997. }
  35998. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35999. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36000. return false;
  36001. }
  36002. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36003. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36004. }
  36005. else {
  36006. defines.LIGHTMAP = false;
  36007. }
  36008. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36009. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36010. return false;
  36011. }
  36012. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36013. }
  36014. else {
  36015. defines.EMISSIVE = false;
  36016. }
  36017. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36018. if (this._metallicTexture) {
  36019. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36020. return false;
  36021. }
  36022. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36023. defines.METALLICWORKFLOW = true;
  36024. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36025. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36026. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36027. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36028. }
  36029. else if (this._reflectivityTexture) {
  36030. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36031. return false;
  36032. }
  36033. defines.METALLICWORKFLOW = false;
  36034. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36035. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36036. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36037. }
  36038. else {
  36039. defines.METALLICWORKFLOW = false;
  36040. defines.REFLECTIVITY = false;
  36041. }
  36042. if (this._microSurfaceTexture) {
  36043. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36044. return false;
  36045. }
  36046. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36047. }
  36048. else {
  36049. defines.MICROSURFACEMAP = false;
  36050. }
  36051. }
  36052. else {
  36053. defines.REFLECTIVITY = false;
  36054. defines.MICROSURFACEMAP = false;
  36055. }
  36056. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36057. // Bump texure can not be none blocking.
  36058. if (!this._bumpTexture.isReady()) {
  36059. return false;
  36060. }
  36061. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36062. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36063. defines.PARALLAX = true;
  36064. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36065. }
  36066. else {
  36067. defines.PARALLAX = false;
  36068. }
  36069. }
  36070. else {
  36071. defines.BUMP = false;
  36072. }
  36073. var refractionTexture = this._getRefractionTexture();
  36074. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36075. if (!refractionTexture.isReadyOrNotBlocking()) {
  36076. return false;
  36077. }
  36078. defines.REFRACTION = true;
  36079. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36080. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36081. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  36082. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36083. if (this._linkRefractionWithTransparency) {
  36084. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36085. }
  36086. }
  36087. else {
  36088. defines.REFRACTION = false;
  36089. }
  36090. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36091. // This is blocking.
  36092. if (!this._environmentBRDFTexture.isReady()) {
  36093. return false;
  36094. }
  36095. defines.ENVIRONMENTBRDF = true;
  36096. }
  36097. else {
  36098. defines.ENVIRONMENTBRDF = false;
  36099. }
  36100. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36101. defines.ALPHAFROMALBEDO = true;
  36102. }
  36103. else {
  36104. defines.ALPHAFROMALBEDO = false;
  36105. }
  36106. }
  36107. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36108. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36109. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36110. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36111. defines.METALLICWORKFLOW = true;
  36112. }
  36113. else {
  36114. defines.METALLICWORKFLOW = false;
  36115. }
  36116. if (!this.backFaceCulling && this._twoSidedLighting) {
  36117. defines.TWOSIDEDLIGHTING = true;
  36118. }
  36119. else {
  36120. defines.TWOSIDEDLIGHTING = false;
  36121. }
  36122. defines.ALPHATESTVALUE = this._alphaCutOff;
  36123. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36124. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36125. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  36126. }
  36127. if (defines._areImageProcessingDirty) {
  36128. if (!this._imageProcessingConfiguration.isReady()) {
  36129. return false;
  36130. }
  36131. this._imageProcessingConfiguration.prepareDefines(defines);
  36132. }
  36133. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36134. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36135. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36136. // Misc.
  36137. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36138. // Values that need to be evaluated on every frame
  36139. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36140. // Attribs
  36141. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  36142. if (mesh) {
  36143. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36144. mesh.createNormals(true);
  36145. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  36146. }
  36147. }
  36148. }
  36149. // Get correct effect
  36150. if (defines.isDirty) {
  36151. defines.markAsProcessed();
  36152. scene.resetCachedMaterial();
  36153. // Fallbacks
  36154. var fallbacks = new BABYLON.EffectFallbacks();
  36155. var fallbackRank = 0;
  36156. if (defines.USESPHERICALINVERTEX) {
  36157. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36158. }
  36159. if (defines.FOG) {
  36160. fallbacks.addFallback(fallbackRank, "FOG");
  36161. }
  36162. if (defines.POINTSIZE) {
  36163. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36164. }
  36165. if (defines.LOGARITHMICDEPTH) {
  36166. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36167. }
  36168. if (defines.PARALLAX) {
  36169. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36170. }
  36171. if (defines.PARALLAXOCCLUSION) {
  36172. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36173. }
  36174. if (defines.ENVIRONMENTBRDF) {
  36175. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36176. }
  36177. if (defines.TANGENT) {
  36178. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36179. }
  36180. if (defines.BUMP) {
  36181. fallbacks.addFallback(fallbackRank++, "BUMP");
  36182. }
  36183. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36184. if (defines.SPECULARTERM) {
  36185. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36186. }
  36187. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36188. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36189. }
  36190. if (defines.LIGHTMAP) {
  36191. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36192. }
  36193. if (defines.NORMAL) {
  36194. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36195. }
  36196. if (defines.AMBIENT) {
  36197. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36198. }
  36199. if (defines.EMISSIVE) {
  36200. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36201. }
  36202. if (defines.VERTEXCOLOR) {
  36203. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36204. }
  36205. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36206. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36207. }
  36208. if (defines.MORPHTARGETS) {
  36209. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36210. }
  36211. //Attributes
  36212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36213. if (defines.NORMAL) {
  36214. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36215. }
  36216. if (defines.TANGENT) {
  36217. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36218. }
  36219. if (defines.UV1) {
  36220. attribs.push(BABYLON.VertexBuffer.UVKind);
  36221. }
  36222. if (defines.UV2) {
  36223. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36224. }
  36225. if (defines.VERTEXCOLOR) {
  36226. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36227. }
  36228. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36229. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36230. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36231. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36232. "vFogInfos", "vFogColor", "pointSize",
  36233. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36234. "mBones",
  36235. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36236. "vLightingIntensity",
  36237. "logarithmicDepthConstant",
  36238. "vSphericalX", "vSphericalY", "vSphericalZ",
  36239. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36240. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36241. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36242. "vTangentSpaceParams"
  36243. ];
  36244. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36245. "bumpSampler", "lightmapSampler", "opacitySampler",
  36246. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36247. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36248. "microSurfaceSampler", "environmentBrdfSampler"];
  36249. var uniformBuffers = ["Material", "Scene"];
  36250. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36251. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36252. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36253. uniformsNames: uniforms,
  36254. uniformBuffersNames: uniformBuffers,
  36255. samplers: samplers,
  36256. defines: defines,
  36257. maxSimultaneousLights: this._maxSimultaneousLights
  36258. });
  36259. var onCompiled = function (effect) {
  36260. if (_this.onCompiled) {
  36261. _this.onCompiled(effect);
  36262. }
  36263. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36264. };
  36265. var join = defines.toString();
  36266. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36267. attributes: attribs,
  36268. uniformsNames: uniforms,
  36269. uniformBuffersNames: uniformBuffers,
  36270. samplers: samplers,
  36271. defines: join,
  36272. fallbacks: fallbacks,
  36273. onCompiled: onCompiled,
  36274. onError: this.onError,
  36275. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36276. }, engine), defines);
  36277. this.buildUniformLayout();
  36278. }
  36279. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36280. return false;
  36281. }
  36282. defines._renderId = scene.getRenderId();
  36283. this._wasPreviouslyReady = true;
  36284. return true;
  36285. };
  36286. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36287. // Order is important !
  36288. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36289. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36290. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36291. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36292. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36293. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36294. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36295. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36296. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36297. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36298. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36299. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36300. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36301. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36302. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36303. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36304. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36305. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36306. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36307. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36308. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36309. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36310. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36311. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36312. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36313. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36314. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36315. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36316. this._uniformBuffer.addUniform("pointSize", 1);
  36317. this._uniformBuffer.create();
  36318. };
  36319. PBRBaseMaterial.prototype.unbind = function () {
  36320. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36321. this._uniformBuffer.setTexture("reflectionSampler", null);
  36322. }
  36323. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36324. this._uniformBuffer.setTexture("refractionSampler", null);
  36325. }
  36326. _super.prototype.unbind.call(this);
  36327. };
  36328. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36329. this._activeEffect.setMatrix("world", world);
  36330. };
  36331. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36332. var scene = this.getScene();
  36333. var defines = subMesh._materialDefines;
  36334. if (!defines) {
  36335. return;
  36336. }
  36337. var effect = subMesh.effect;
  36338. if (!effect) {
  36339. return;
  36340. }
  36341. this._activeEffect = effect;
  36342. // Matrices
  36343. this.bindOnlyWorldMatrix(world);
  36344. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36345. // Bones
  36346. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36347. var reflectionTexture = null;
  36348. if (mustRebind) {
  36349. this._uniformBuffer.bindToEffect(effect, "Material");
  36350. this.bindViewProjection(effect);
  36351. reflectionTexture = this._getReflectionTexture();
  36352. var refractionTexture = this._getRefractionTexture();
  36353. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36354. // Texture uniforms
  36355. if (scene.texturesEnabled) {
  36356. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36357. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36358. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36359. }
  36360. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36361. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36362. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36363. }
  36364. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36365. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36366. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36367. }
  36368. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36369. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36370. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36371. var polynomials = reflectionTexture.sphericalPolynomial;
  36372. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36373. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36374. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36375. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36376. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36377. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36378. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36379. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36380. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36381. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36382. }
  36383. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36384. }
  36385. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36386. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36387. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36388. }
  36389. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36390. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36391. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36392. }
  36393. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36394. if (this._metallicTexture) {
  36395. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36396. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36397. }
  36398. else if (this._reflectivityTexture) {
  36399. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36400. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36401. }
  36402. if (this._microSurfaceTexture) {
  36403. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36404. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36405. }
  36406. }
  36407. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36408. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36409. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36410. if (scene._mirroredCameraPosition) {
  36411. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36412. }
  36413. else {
  36414. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36415. }
  36416. }
  36417. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36418. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36419. var depth = 1.0;
  36420. if (!refractionTexture.isCube) {
  36421. if (refractionTexture.depth) {
  36422. depth = refractionTexture.depth;
  36423. }
  36424. }
  36425. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36426. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36427. }
  36428. }
  36429. // Point size
  36430. if (this.pointsCloud) {
  36431. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36432. }
  36433. // Colors
  36434. if (defines.METALLICWORKFLOW) {
  36435. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36436. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36437. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36438. }
  36439. else {
  36440. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36441. }
  36442. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36443. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36444. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36445. // Misc
  36446. this._lightingInfos.x = this._directIntensity;
  36447. this._lightingInfos.y = this._emissiveIntensity;
  36448. this._lightingInfos.z = this._environmentIntensity;
  36449. this._lightingInfos.w = this._specularIntensity;
  36450. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36451. }
  36452. // Textures
  36453. if (scene.texturesEnabled) {
  36454. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36455. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36456. }
  36457. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36458. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36459. }
  36460. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36461. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36462. }
  36463. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36464. if (defines.LODBASEDMICROSFURACE) {
  36465. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36466. }
  36467. else {
  36468. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36469. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36470. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36471. }
  36472. }
  36473. if (defines.ENVIRONMENTBRDF) {
  36474. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36475. }
  36476. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36477. if (defines.LODBASEDMICROSFURACE) {
  36478. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36479. }
  36480. else {
  36481. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36482. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36483. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36484. }
  36485. }
  36486. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36487. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36488. }
  36489. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36490. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36491. }
  36492. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36493. if (this._metallicTexture) {
  36494. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36495. }
  36496. else if (this._reflectivityTexture) {
  36497. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36498. }
  36499. if (this._microSurfaceTexture) {
  36500. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36501. }
  36502. }
  36503. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36504. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36505. }
  36506. }
  36507. // Clip plane
  36508. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36509. // Colors
  36510. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36511. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36512. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36513. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36514. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36515. }
  36516. if (mustRebind || !this.isFrozen) {
  36517. // Lights
  36518. if (scene.lightsEnabled && !this._disableLighting) {
  36519. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36520. }
  36521. // View
  36522. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36523. this.bindView(effect);
  36524. }
  36525. // Fog
  36526. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36527. // Morph targets
  36528. if (defines.NUM_MORPH_INFLUENCERS) {
  36529. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36530. }
  36531. // image processing
  36532. this._imageProcessingConfiguration.bind(this._activeEffect);
  36533. // Log. depth
  36534. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36535. }
  36536. this._uniformBuffer.update();
  36537. this._afterBind(mesh);
  36538. };
  36539. PBRBaseMaterial.prototype.getAnimatables = function () {
  36540. var results = [];
  36541. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36542. results.push(this._albedoTexture);
  36543. }
  36544. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36545. results.push(this._ambientTexture);
  36546. }
  36547. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36548. results.push(this._opacityTexture);
  36549. }
  36550. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36551. results.push(this._reflectionTexture);
  36552. }
  36553. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36554. results.push(this._emissiveTexture);
  36555. }
  36556. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36557. results.push(this._metallicTexture);
  36558. }
  36559. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36560. results.push(this._reflectivityTexture);
  36561. }
  36562. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36563. results.push(this._bumpTexture);
  36564. }
  36565. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36566. results.push(this._lightmapTexture);
  36567. }
  36568. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36569. results.push(this._refractionTexture);
  36570. }
  36571. return results;
  36572. };
  36573. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36574. if (this._reflectionTexture) {
  36575. return this._reflectionTexture;
  36576. }
  36577. return this.getScene().environmentTexture;
  36578. };
  36579. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36580. if (this._refractionTexture) {
  36581. return this._refractionTexture;
  36582. }
  36583. if (this._linkRefractionWithTransparency) {
  36584. return this.getScene().environmentTexture;
  36585. }
  36586. return null;
  36587. };
  36588. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36589. if (forceDisposeTextures) {
  36590. if (this._albedoTexture) {
  36591. this._albedoTexture.dispose();
  36592. }
  36593. if (this._ambientTexture) {
  36594. this._ambientTexture.dispose();
  36595. }
  36596. if (this._opacityTexture) {
  36597. this._opacityTexture.dispose();
  36598. }
  36599. if (this._reflectionTexture) {
  36600. this._reflectionTexture.dispose();
  36601. }
  36602. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36603. this._environmentBRDFTexture.dispose();
  36604. }
  36605. if (this._emissiveTexture) {
  36606. this._emissiveTexture.dispose();
  36607. }
  36608. if (this._metallicTexture) {
  36609. this._metallicTexture.dispose();
  36610. }
  36611. if (this._reflectivityTexture) {
  36612. this._reflectivityTexture.dispose();
  36613. }
  36614. if (this._bumpTexture) {
  36615. this._bumpTexture.dispose();
  36616. }
  36617. if (this._lightmapTexture) {
  36618. this._lightmapTexture.dispose();
  36619. }
  36620. if (this._refractionTexture) {
  36621. this._refractionTexture.dispose();
  36622. }
  36623. }
  36624. this._renderTargets.dispose();
  36625. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36626. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36627. }
  36628. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36629. };
  36630. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36631. __decorate([
  36632. BABYLON.serializeAsImageProcessingConfiguration()
  36633. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36634. __decorate([
  36635. BABYLON.serialize()
  36636. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36637. __decorate([
  36638. BABYLON.serialize()
  36639. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36640. return PBRBaseMaterial;
  36641. }(BABYLON.PushMaterial));
  36642. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36643. })(BABYLON || (BABYLON = {}));
  36644. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36645. var BABYLON;
  36646. (function (BABYLON) {
  36647. var Internals;
  36648. (function (Internals) {
  36649. /**
  36650. * The Physically based simple base material of BJS.
  36651. *
  36652. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36653. * It is used as the base class for both the specGloss and metalRough conventions.
  36654. */
  36655. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36656. __extends(PBRBaseSimpleMaterial, _super);
  36657. /**
  36658. * Instantiates a new PBRMaterial instance.
  36659. *
  36660. * @param name The material name
  36661. * @param scene The scene the material will be use in.
  36662. */
  36663. function PBRBaseSimpleMaterial(name, scene) {
  36664. var _this = _super.call(this, name, scene) || this;
  36665. /**
  36666. * Number of Simultaneous lights allowed on the material.
  36667. */
  36668. _this.maxSimultaneousLights = 4;
  36669. /**
  36670. * If sets to true, disables all the lights affecting the material.
  36671. */
  36672. _this.disableLighting = false;
  36673. /**
  36674. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36675. */
  36676. _this.invertNormalMapX = false;
  36677. /**
  36678. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36679. */
  36680. _this.invertNormalMapY = false;
  36681. /**
  36682. * Emissivie color used to self-illuminate the model.
  36683. */
  36684. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36685. /**
  36686. * Occlusion Channel Strenght.
  36687. */
  36688. _this.occlusionStrength = 1.0;
  36689. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36690. _this._useAlphaFromAlbedoTexture = true;
  36691. _this._useAmbientInGrayScale = true;
  36692. return _this;
  36693. }
  36694. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36695. /**
  36696. * Gets the current double sided mode.
  36697. */
  36698. get: function () {
  36699. return this._twoSidedLighting;
  36700. },
  36701. /**
  36702. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36703. */
  36704. set: function (value) {
  36705. if (this._twoSidedLighting === value) {
  36706. return;
  36707. }
  36708. this._twoSidedLighting = value;
  36709. this.backFaceCulling = !value;
  36710. this._markAllSubMeshesAsTexturesDirty();
  36711. },
  36712. enumerable: true,
  36713. configurable: true
  36714. });
  36715. /**
  36716. * Return the active textures of the material.
  36717. */
  36718. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36719. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36720. if (this.environmentTexture) {
  36721. activeTextures.push(this.environmentTexture);
  36722. }
  36723. if (this.normalTexture) {
  36724. activeTextures.push(this.normalTexture);
  36725. }
  36726. if (this.emissiveTexture) {
  36727. activeTextures.push(this.emissiveTexture);
  36728. }
  36729. if (this.occlusionTexture) {
  36730. activeTextures.push(this.occlusionTexture);
  36731. }
  36732. return activeTextures;
  36733. };
  36734. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36735. return "PBRBaseSimpleMaterial";
  36736. };
  36737. __decorate([
  36738. BABYLON.serialize(),
  36739. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36740. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36741. __decorate([
  36742. BABYLON.serialize(),
  36743. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36744. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36745. __decorate([
  36746. BABYLON.serializeAsTexture(),
  36747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36748. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36749. __decorate([
  36750. BABYLON.serialize(),
  36751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36752. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36753. __decorate([
  36754. BABYLON.serialize(),
  36755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36756. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36757. __decorate([
  36758. BABYLON.serializeAsTexture(),
  36759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36760. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36761. __decorate([
  36762. BABYLON.serializeAsColor3("emissive"),
  36763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36764. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36765. __decorate([
  36766. BABYLON.serializeAsTexture(),
  36767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36768. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36769. __decorate([
  36770. BABYLON.serialize(),
  36771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36772. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36773. __decorate([
  36774. BABYLON.serializeAsTexture(),
  36775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36776. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36777. __decorate([
  36778. BABYLON.serialize(),
  36779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36780. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36781. __decorate([
  36782. BABYLON.serialize()
  36783. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36784. return PBRBaseSimpleMaterial;
  36785. }(BABYLON.PBRBaseMaterial));
  36786. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36787. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36788. })(BABYLON || (BABYLON = {}));
  36789. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36790. var BABYLON;
  36791. (function (BABYLON) {
  36792. /**
  36793. * The Physically based material of BJS.
  36794. *
  36795. * This offers the main features of a standard PBR material.
  36796. * For more information, please refer to the documentation :
  36797. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36798. */
  36799. var PBRMaterial = /** @class */ (function (_super) {
  36800. __extends(PBRMaterial, _super);
  36801. /**
  36802. * Instantiates a new PBRMaterial instance.
  36803. *
  36804. * @param name The material name
  36805. * @param scene The scene the material will be use in.
  36806. */
  36807. function PBRMaterial(name, scene) {
  36808. var _this = _super.call(this, name, scene) || this;
  36809. /**
  36810. * Intensity of the direct lights e.g. the four lights available in your scene.
  36811. * This impacts both the direct diffuse and specular highlights.
  36812. */
  36813. _this.directIntensity = 1.0;
  36814. /**
  36815. * Intensity of the emissive part of the material.
  36816. * This helps controlling the emissive effect without modifying the emissive color.
  36817. */
  36818. _this.emissiveIntensity = 1.0;
  36819. /**
  36820. * Intensity of the environment e.g. how much the environment will light the object
  36821. * either through harmonics for rough material or through the refelction for shiny ones.
  36822. */
  36823. _this.environmentIntensity = 1.0;
  36824. /**
  36825. * This is a special control allowing the reduction of the specular highlights coming from the
  36826. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36827. */
  36828. _this.specularIntensity = 1.0;
  36829. /**
  36830. * Debug Control allowing disabling the bump map on this material.
  36831. */
  36832. _this.disableBumpMap = false;
  36833. /**
  36834. * AKA Occlusion Texture Intensity in other nomenclature.
  36835. */
  36836. _this.ambientTextureStrength = 1.0;
  36837. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36838. /**
  36839. * AKA Diffuse Color in other nomenclature.
  36840. */
  36841. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36842. /**
  36843. * AKA Specular Color in other nomenclature.
  36844. */
  36845. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36846. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36847. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36848. /**
  36849. * AKA Glossiness in other nomenclature.
  36850. */
  36851. _this.microSurface = 1.0;
  36852. /**
  36853. * source material index of refraction (IOR)' / 'destination material IOR.
  36854. */
  36855. _this.indexOfRefraction = 0.66;
  36856. /**
  36857. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36858. */
  36859. _this.invertRefractionY = false;
  36860. /**
  36861. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36862. * Materials half opaque for instance using refraction could benefit from this control.
  36863. */
  36864. _this.linkRefractionWithTransparency = false;
  36865. _this.useLightmapAsShadowmap = false;
  36866. /**
  36867. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36868. */
  36869. _this.useAlphaFromAlbedoTexture = false;
  36870. /**
  36871. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36872. */
  36873. _this.forceAlphaTest = false;
  36874. /**
  36875. * Defines the alpha limits in alpha test mode.
  36876. */
  36877. _this.alphaCutOff = 0.4;
  36878. /**
  36879. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36880. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36881. */
  36882. _this.useSpecularOverAlpha = true;
  36883. /**
  36884. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36885. */
  36886. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36887. /**
  36888. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36889. */
  36890. _this.useRoughnessFromMetallicTextureAlpha = true;
  36891. /**
  36892. * Specifies if the metallic texture contains the roughness information in its green channel.
  36893. */
  36894. _this.useRoughnessFromMetallicTextureGreen = false;
  36895. /**
  36896. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36897. */
  36898. _this.useMetallnessFromMetallicTextureBlue = false;
  36899. /**
  36900. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36901. */
  36902. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36903. /**
  36904. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36905. */
  36906. _this.useAmbientInGrayScale = false;
  36907. /**
  36908. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36909. * The material will try to infer what glossiness each pixel should be.
  36910. */
  36911. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36912. /**
  36913. * BJS is using an harcoded light falloff based on a manually sets up range.
  36914. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36915. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36916. */
  36917. _this.usePhysicalLightFalloff = true;
  36918. /**
  36919. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36920. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36921. */
  36922. _this.useRadianceOverAlpha = true;
  36923. /**
  36924. * Allows using the bump map in parallax mode.
  36925. */
  36926. _this.useParallax = false;
  36927. /**
  36928. * Allows using the bump map in parallax occlusion mode.
  36929. */
  36930. _this.useParallaxOcclusion = false;
  36931. /**
  36932. * Controls the scale bias of the parallax mode.
  36933. */
  36934. _this.parallaxScaleBias = 0.05;
  36935. /**
  36936. * If sets to true, disables all the lights affecting the material.
  36937. */
  36938. _this.disableLighting = false;
  36939. /**
  36940. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36941. */
  36942. _this.forceIrradianceInFragment = false;
  36943. /**
  36944. * Number of Simultaneous lights allowed on the material.
  36945. */
  36946. _this.maxSimultaneousLights = 4;
  36947. /**
  36948. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36949. */
  36950. _this.invertNormalMapX = false;
  36951. /**
  36952. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36953. */
  36954. _this.invertNormalMapY = false;
  36955. /**
  36956. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36957. */
  36958. _this.twoSidedLighting = false;
  36959. /**
  36960. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36961. * And/Or occlude the blended part.
  36962. */
  36963. _this.useAlphaFresnel = false;
  36964. /**
  36965. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36966. * And/Or occlude the blended part.
  36967. */
  36968. _this.environmentBRDFTexture = null;
  36969. /**
  36970. * Force normal to face away from face.
  36971. * (Temporary internal fix to remove before 3.1)
  36972. */
  36973. _this.forceNormalForward = false;
  36974. /**
  36975. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36976. * makes the reflect vector face the model (under horizon).
  36977. */
  36978. _this.useHorizonOcclusion = false;
  36979. /**
  36980. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36981. * too much the area relying on ambient texture to define their ambient occlusion.
  36982. */
  36983. _this.useRadianceOcclusion = false;
  36984. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36985. return _this;
  36986. }
  36987. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36988. /**
  36989. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36990. */
  36991. get: function () {
  36992. return this._PBRMATERIAL_OPAQUE;
  36993. },
  36994. enumerable: true,
  36995. configurable: true
  36996. });
  36997. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36998. /**
  36999. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37000. */
  37001. get: function () {
  37002. return this._PBRMATERIAL_ALPHATEST;
  37003. },
  37004. enumerable: true,
  37005. configurable: true
  37006. });
  37007. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37008. /**
  37009. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37010. */
  37011. get: function () {
  37012. return this._PBRMATERIAL_ALPHABLEND;
  37013. },
  37014. enumerable: true,
  37015. configurable: true
  37016. });
  37017. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37018. /**
  37019. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37020. * They are also discarded below the alpha cutoff threshold to improve performances.
  37021. */
  37022. get: function () {
  37023. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37024. },
  37025. enumerable: true,
  37026. configurable: true
  37027. });
  37028. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37029. /**
  37030. * Gets the image processing configuration used either in this material.
  37031. */
  37032. get: function () {
  37033. return this._imageProcessingConfiguration;
  37034. },
  37035. /**
  37036. * Sets the Default image processing configuration used either in the this material.
  37037. *
  37038. * If sets to null, the scene one is in use.
  37039. */
  37040. set: function (value) {
  37041. this._attachImageProcessingConfiguration(value);
  37042. // Ensure the effect will be rebuilt.
  37043. this._markAllSubMeshesAsTexturesDirty();
  37044. },
  37045. enumerable: true,
  37046. configurable: true
  37047. });
  37048. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37049. /**
  37050. * Gets wether the color curves effect is enabled.
  37051. */
  37052. get: function () {
  37053. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37054. },
  37055. /**
  37056. * Sets wether the color curves effect is enabled.
  37057. */
  37058. set: function (value) {
  37059. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37060. },
  37061. enumerable: true,
  37062. configurable: true
  37063. });
  37064. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37065. /**
  37066. * Gets wether the color grading effect is enabled.
  37067. */
  37068. get: function () {
  37069. return this.imageProcessingConfiguration.colorGradingEnabled;
  37070. },
  37071. /**
  37072. * Gets wether the color grading effect is enabled.
  37073. */
  37074. set: function (value) {
  37075. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37076. },
  37077. enumerable: true,
  37078. configurable: true
  37079. });
  37080. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37081. /**
  37082. * Gets wether tonemapping is enabled or not.
  37083. */
  37084. get: function () {
  37085. return this._imageProcessingConfiguration.toneMappingEnabled;
  37086. },
  37087. /**
  37088. * Sets wether tonemapping is enabled or not
  37089. */
  37090. set: function (value) {
  37091. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37092. },
  37093. enumerable: true,
  37094. configurable: true
  37095. });
  37096. ;
  37097. ;
  37098. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37099. /**
  37100. * The camera exposure used on this material.
  37101. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37102. * This corresponds to a photographic exposure.
  37103. */
  37104. get: function () {
  37105. return this._imageProcessingConfiguration.exposure;
  37106. },
  37107. /**
  37108. * The camera exposure used on this material.
  37109. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37110. * This corresponds to a photographic exposure.
  37111. */
  37112. set: function (value) {
  37113. this._imageProcessingConfiguration.exposure = value;
  37114. },
  37115. enumerable: true,
  37116. configurable: true
  37117. });
  37118. ;
  37119. ;
  37120. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37121. /**
  37122. * Gets The camera contrast used on this material.
  37123. */
  37124. get: function () {
  37125. return this._imageProcessingConfiguration.contrast;
  37126. },
  37127. /**
  37128. * Sets The camera contrast used on this material.
  37129. */
  37130. set: function (value) {
  37131. this._imageProcessingConfiguration.contrast = value;
  37132. },
  37133. enumerable: true,
  37134. configurable: true
  37135. });
  37136. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37137. /**
  37138. * Gets the Color Grading 2D Lookup Texture.
  37139. */
  37140. get: function () {
  37141. return this._imageProcessingConfiguration.colorGradingTexture;
  37142. },
  37143. /**
  37144. * Sets the Color Grading 2D Lookup Texture.
  37145. */
  37146. set: function (value) {
  37147. this._imageProcessingConfiguration.colorGradingTexture = value;
  37148. },
  37149. enumerable: true,
  37150. configurable: true
  37151. });
  37152. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37153. /**
  37154. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37155. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37156. * 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;
  37157. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37158. */
  37159. get: function () {
  37160. return this._imageProcessingConfiguration.colorCurves;
  37161. },
  37162. /**
  37163. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37164. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37165. * 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;
  37166. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37167. */
  37168. set: function (value) {
  37169. this._imageProcessingConfiguration.colorCurves = value;
  37170. },
  37171. enumerable: true,
  37172. configurable: true
  37173. });
  37174. PBRMaterial.prototype.getClassName = function () {
  37175. return "PBRMaterial";
  37176. };
  37177. PBRMaterial.prototype.getActiveTextures = function () {
  37178. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37179. if (this._albedoTexture) {
  37180. activeTextures.push(this._albedoTexture);
  37181. }
  37182. if (this._ambientTexture) {
  37183. activeTextures.push(this._ambientTexture);
  37184. }
  37185. if (this._opacityTexture) {
  37186. activeTextures.push(this._opacityTexture);
  37187. }
  37188. if (this._reflectionTexture) {
  37189. activeTextures.push(this._reflectionTexture);
  37190. }
  37191. if (this._emissiveTexture) {
  37192. activeTextures.push(this._emissiveTexture);
  37193. }
  37194. if (this._reflectivityTexture) {
  37195. activeTextures.push(this._reflectivityTexture);
  37196. }
  37197. if (this._metallicTexture) {
  37198. activeTextures.push(this._metallicTexture);
  37199. }
  37200. if (this._microSurfaceTexture) {
  37201. activeTextures.push(this._microSurfaceTexture);
  37202. }
  37203. if (this._bumpTexture) {
  37204. activeTextures.push(this._bumpTexture);
  37205. }
  37206. if (this._lightmapTexture) {
  37207. activeTextures.push(this._lightmapTexture);
  37208. }
  37209. if (this._refractionTexture) {
  37210. activeTextures.push(this._refractionTexture);
  37211. }
  37212. return activeTextures;
  37213. };
  37214. PBRMaterial.prototype.hasTexture = function (texture) {
  37215. if (_super.prototype.hasTexture.call(this, texture)) {
  37216. return true;
  37217. }
  37218. if (this._albedoTexture === texture) {
  37219. return true;
  37220. }
  37221. if (this._ambientTexture === texture) {
  37222. return true;
  37223. }
  37224. if (this._opacityTexture === texture) {
  37225. return true;
  37226. }
  37227. if (this._reflectionTexture === texture) {
  37228. return true;
  37229. }
  37230. if (this._reflectivityTexture === texture) {
  37231. return true;
  37232. }
  37233. if (this._metallicTexture === texture) {
  37234. return true;
  37235. }
  37236. if (this._microSurfaceTexture === texture) {
  37237. return true;
  37238. }
  37239. if (this._bumpTexture === texture) {
  37240. return true;
  37241. }
  37242. if (this._lightmapTexture === texture) {
  37243. return true;
  37244. }
  37245. if (this._refractionTexture === texture) {
  37246. return true;
  37247. }
  37248. return false;
  37249. };
  37250. PBRMaterial.prototype.clone = function (name) {
  37251. var _this = this;
  37252. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37253. clone.id = name;
  37254. clone.name = name;
  37255. return clone;
  37256. };
  37257. PBRMaterial.prototype.serialize = function () {
  37258. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37259. serializationObject.customType = "BABYLON.PBRMaterial";
  37260. return serializationObject;
  37261. };
  37262. // Statics
  37263. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37264. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37265. };
  37266. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37267. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37268. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37269. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37270. __decorate([
  37271. BABYLON.serialize(),
  37272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37273. ], PBRMaterial.prototype, "directIntensity", void 0);
  37274. __decorate([
  37275. BABYLON.serialize(),
  37276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37277. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37278. __decorate([
  37279. BABYLON.serialize(),
  37280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37281. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37282. __decorate([
  37283. BABYLON.serialize(),
  37284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37285. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37286. __decorate([
  37287. BABYLON.serialize(),
  37288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37289. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37290. __decorate([
  37291. BABYLON.serializeAsTexture(),
  37292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37293. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37294. __decorate([
  37295. BABYLON.serializeAsTexture(),
  37296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37297. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37298. __decorate([
  37299. BABYLON.serialize(),
  37300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37301. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37302. __decorate([
  37303. BABYLON.serializeAsTexture(),
  37304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37305. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37306. __decorate([
  37307. BABYLON.serializeAsTexture(),
  37308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37309. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37310. __decorate([
  37311. BABYLON.serializeAsTexture(),
  37312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37313. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37314. __decorate([
  37315. BABYLON.serializeAsTexture(),
  37316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37317. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37318. __decorate([
  37319. BABYLON.serializeAsTexture(),
  37320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37321. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37322. __decorate([
  37323. BABYLON.serialize(),
  37324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37325. ], PBRMaterial.prototype, "metallic", void 0);
  37326. __decorate([
  37327. BABYLON.serialize(),
  37328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37329. ], PBRMaterial.prototype, "roughness", void 0);
  37330. __decorate([
  37331. BABYLON.serializeAsTexture(),
  37332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37333. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37334. __decorate([
  37335. BABYLON.serializeAsTexture(),
  37336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37337. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37338. __decorate([
  37339. BABYLON.serializeAsTexture(),
  37340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37341. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37342. __decorate([
  37343. BABYLON.serializeAsTexture(),
  37344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37345. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37346. __decorate([
  37347. BABYLON.serializeAsColor3("ambient"),
  37348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37349. ], PBRMaterial.prototype, "ambientColor", void 0);
  37350. __decorate([
  37351. BABYLON.serializeAsColor3("albedo"),
  37352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37353. ], PBRMaterial.prototype, "albedoColor", void 0);
  37354. __decorate([
  37355. BABYLON.serializeAsColor3("reflectivity"),
  37356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37357. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37358. __decorate([
  37359. BABYLON.serializeAsColor3("reflection"),
  37360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37361. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37362. __decorate([
  37363. BABYLON.serializeAsColor3("emissive"),
  37364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37365. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37366. __decorate([
  37367. BABYLON.serialize(),
  37368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37369. ], PBRMaterial.prototype, "microSurface", void 0);
  37370. __decorate([
  37371. BABYLON.serialize(),
  37372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37373. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37374. __decorate([
  37375. BABYLON.serialize(),
  37376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37377. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37378. __decorate([
  37379. BABYLON.serialize(),
  37380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37381. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37382. __decorate([
  37383. BABYLON.serialize(),
  37384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37385. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37386. __decorate([
  37387. BABYLON.serialize(),
  37388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37389. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37390. __decorate([
  37391. BABYLON.serialize(),
  37392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37393. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37394. __decorate([
  37395. BABYLON.serialize(),
  37396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37397. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37398. __decorate([
  37399. BABYLON.serialize(),
  37400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37401. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37402. __decorate([
  37403. BABYLON.serialize(),
  37404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37405. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37406. __decorate([
  37407. BABYLON.serialize(),
  37408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37409. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37410. __decorate([
  37411. BABYLON.serialize(),
  37412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37413. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37414. __decorate([
  37415. BABYLON.serialize(),
  37416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37417. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37418. __decorate([
  37419. BABYLON.serialize(),
  37420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37421. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37422. __decorate([
  37423. BABYLON.serialize(),
  37424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37425. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37426. __decorate([
  37427. BABYLON.serialize(),
  37428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37429. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37430. __decorate([
  37431. BABYLON.serialize(),
  37432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37433. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37434. __decorate([
  37435. BABYLON.serialize(),
  37436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37437. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37438. __decorate([
  37439. BABYLON.serialize(),
  37440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37441. ], PBRMaterial.prototype, "useParallax", void 0);
  37442. __decorate([
  37443. BABYLON.serialize(),
  37444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37445. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37446. __decorate([
  37447. BABYLON.serialize(),
  37448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37449. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37450. __decorate([
  37451. BABYLON.serialize(),
  37452. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37453. ], PBRMaterial.prototype, "disableLighting", void 0);
  37454. __decorate([
  37455. BABYLON.serialize(),
  37456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37457. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37458. __decorate([
  37459. BABYLON.serialize(),
  37460. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37461. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37462. __decorate([
  37463. BABYLON.serialize(),
  37464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37465. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37466. __decorate([
  37467. BABYLON.serialize(),
  37468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37469. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37470. __decorate([
  37471. BABYLON.serialize(),
  37472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37473. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37474. __decorate([
  37475. BABYLON.serialize(),
  37476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37477. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37478. __decorate([
  37479. BABYLON.serializeAsTexture(),
  37480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37481. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37482. __decorate([
  37483. BABYLON.serialize(),
  37484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37485. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37486. __decorate([
  37487. BABYLON.serialize(),
  37488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37489. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37490. __decorate([
  37491. BABYLON.serialize(),
  37492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37493. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37494. return PBRMaterial;
  37495. }(BABYLON.PBRBaseMaterial));
  37496. BABYLON.PBRMaterial = PBRMaterial;
  37497. })(BABYLON || (BABYLON = {}));
  37498. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37499. var BABYLON;
  37500. (function (BABYLON) {
  37501. /**
  37502. * The PBR material of BJS following the metal roughness convention.
  37503. *
  37504. * This fits to the PBR convention in the GLTF definition:
  37505. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37506. */
  37507. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37508. __extends(PBRMetallicRoughnessMaterial, _super);
  37509. /**
  37510. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37511. *
  37512. * @param name The material name
  37513. * @param scene The scene the material will be use in.
  37514. */
  37515. function PBRMetallicRoughnessMaterial(name, scene) {
  37516. var _this = _super.call(this, name, scene) || this;
  37517. _this._useRoughnessFromMetallicTextureAlpha = false;
  37518. _this._useRoughnessFromMetallicTextureGreen = true;
  37519. _this._useMetallnessFromMetallicTextureBlue = true;
  37520. return _this;
  37521. }
  37522. /**
  37523. * Return the currrent class name of the material.
  37524. */
  37525. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37526. return "PBRMetallicRoughnessMaterial";
  37527. };
  37528. /**
  37529. * Return the active textures of the material.
  37530. */
  37531. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37532. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37533. if (this.baseTexture) {
  37534. activeTextures.push(this.baseTexture);
  37535. }
  37536. if (this.metallicRoughnessTexture) {
  37537. activeTextures.push(this.metallicRoughnessTexture);
  37538. }
  37539. return activeTextures;
  37540. };
  37541. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37542. if (_super.prototype.hasTexture.call(this, texture)) {
  37543. return true;
  37544. }
  37545. if (this.baseTexture === texture) {
  37546. return true;
  37547. }
  37548. if (this.metallicRoughnessTexture === texture) {
  37549. return true;
  37550. }
  37551. return false;
  37552. };
  37553. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37554. var _this = this;
  37555. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37556. clone.id = name;
  37557. clone.name = name;
  37558. return clone;
  37559. };
  37560. /**
  37561. * Serialize the material to a parsable JSON object.
  37562. */
  37563. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37565. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37566. return serializationObject;
  37567. };
  37568. /**
  37569. * Parses a JSON object correponding to the serialize function.
  37570. */
  37571. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37572. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37573. };
  37574. __decorate([
  37575. BABYLON.serializeAsColor3(),
  37576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37577. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37578. __decorate([
  37579. BABYLON.serializeAsTexture(),
  37580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37581. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37582. __decorate([
  37583. BABYLON.serialize(),
  37584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37585. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37586. __decorate([
  37587. BABYLON.serialize(),
  37588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37589. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37590. __decorate([
  37591. BABYLON.serializeAsTexture(),
  37592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37593. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37594. return PBRMetallicRoughnessMaterial;
  37595. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37596. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37597. })(BABYLON || (BABYLON = {}));
  37598. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37599. var BABYLON;
  37600. (function (BABYLON) {
  37601. /**
  37602. * The PBR material of BJS following the specular glossiness convention.
  37603. *
  37604. * This fits to the PBR convention in the GLTF definition:
  37605. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37606. */
  37607. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37608. __extends(PBRSpecularGlossinessMaterial, _super);
  37609. /**
  37610. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37611. *
  37612. * @param name The material name
  37613. * @param scene The scene the material will be use in.
  37614. */
  37615. function PBRSpecularGlossinessMaterial(name, scene) {
  37616. var _this = _super.call(this, name, scene) || this;
  37617. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37618. return _this;
  37619. }
  37620. /**
  37621. * Return the currrent class name of the material.
  37622. */
  37623. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37624. return "PBRSpecularGlossinessMaterial";
  37625. };
  37626. /**
  37627. * Return the active textures of the material.
  37628. */
  37629. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37630. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37631. if (this.diffuseTexture) {
  37632. activeTextures.push(this.diffuseTexture);
  37633. }
  37634. if (this.specularGlossinessTexture) {
  37635. activeTextures.push(this.specularGlossinessTexture);
  37636. }
  37637. return activeTextures;
  37638. };
  37639. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37640. if (_super.prototype.hasTexture.call(this, texture)) {
  37641. return true;
  37642. }
  37643. if (this.diffuseTexture === texture) {
  37644. return true;
  37645. }
  37646. if (this.specularGlossinessTexture === texture) {
  37647. return true;
  37648. }
  37649. return false;
  37650. };
  37651. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37652. var _this = this;
  37653. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37654. clone.id = name;
  37655. clone.name = name;
  37656. return clone;
  37657. };
  37658. /**
  37659. * Serialize the material to a parsable JSON object.
  37660. */
  37661. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37662. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37663. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37664. return serializationObject;
  37665. };
  37666. /**
  37667. * Parses a JSON object correponding to the serialize function.
  37668. */
  37669. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37670. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37671. };
  37672. __decorate([
  37673. BABYLON.serializeAsColor3("diffuse"),
  37674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37675. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37676. __decorate([
  37677. BABYLON.serializeAsTexture(),
  37678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37679. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37680. __decorate([
  37681. BABYLON.serializeAsColor3("specular"),
  37682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37683. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37684. __decorate([
  37685. BABYLON.serialize(),
  37686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37687. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37688. __decorate([
  37689. BABYLON.serializeAsTexture(),
  37690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37691. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37692. return PBRSpecularGlossinessMaterial;
  37693. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37694. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37695. })(BABYLON || (BABYLON = {}));
  37696. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37697. var BABYLON;
  37698. (function (BABYLON) {
  37699. BABYLON.CameraInputTypes = {};
  37700. var CameraInputsManager = /** @class */ (function () {
  37701. function CameraInputsManager(camera) {
  37702. this.attached = {};
  37703. this.camera = camera;
  37704. this.checkInputs = function () { };
  37705. }
  37706. CameraInputsManager.prototype.add = function (input) {
  37707. var type = input.getSimpleName();
  37708. if (this.attached[type]) {
  37709. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37710. return;
  37711. }
  37712. this.attached[type] = input;
  37713. input.camera = this.camera;
  37714. //for checkInputs, we are dynamically creating a function
  37715. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37716. if (input.checkInputs) {
  37717. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37718. }
  37719. if (this.attachedElement) {
  37720. input.attachControl(this.attachedElement);
  37721. }
  37722. };
  37723. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37724. for (var cam in this.attached) {
  37725. var input = this.attached[cam];
  37726. if (input === inputToRemove) {
  37727. input.detachControl(this.attachedElement);
  37728. input.camera = null;
  37729. delete this.attached[cam];
  37730. this.rebuildInputCheck();
  37731. }
  37732. }
  37733. };
  37734. CameraInputsManager.prototype.removeByType = function (inputType) {
  37735. for (var cam in this.attached) {
  37736. var input = this.attached[cam];
  37737. if (input.getClassName() === inputType) {
  37738. input.detachControl(this.attachedElement);
  37739. input.camera = null;
  37740. delete this.attached[cam];
  37741. this.rebuildInputCheck();
  37742. }
  37743. }
  37744. };
  37745. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37746. var current = this.checkInputs;
  37747. return function () {
  37748. current();
  37749. fn();
  37750. };
  37751. };
  37752. CameraInputsManager.prototype.attachInput = function (input) {
  37753. if (this.attachedElement) {
  37754. input.attachControl(this.attachedElement, this.noPreventDefault);
  37755. }
  37756. };
  37757. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37758. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37759. if (this.attachedElement) {
  37760. return;
  37761. }
  37762. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37763. this.attachedElement = element;
  37764. this.noPreventDefault = noPreventDefault;
  37765. for (var cam in this.attached) {
  37766. this.attached[cam].attachControl(element, noPreventDefault);
  37767. }
  37768. };
  37769. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37770. if (disconnect === void 0) { disconnect = false; }
  37771. if (this.attachedElement !== element) {
  37772. return;
  37773. }
  37774. for (var cam in this.attached) {
  37775. this.attached[cam].detachControl(element);
  37776. if (disconnect) {
  37777. this.attached[cam].camera = null;
  37778. }
  37779. }
  37780. this.attachedElement = null;
  37781. };
  37782. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37783. this.checkInputs = function () { };
  37784. for (var cam in this.attached) {
  37785. var input = this.attached[cam];
  37786. if (input.checkInputs) {
  37787. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37788. }
  37789. }
  37790. };
  37791. CameraInputsManager.prototype.clear = function () {
  37792. if (this.attachedElement) {
  37793. this.detachElement(this.attachedElement, true);
  37794. }
  37795. this.attached = {};
  37796. this.attachedElement = null;
  37797. this.checkInputs = function () { };
  37798. };
  37799. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37800. var inputs = {};
  37801. for (var cam in this.attached) {
  37802. var input = this.attached[cam];
  37803. var res = BABYLON.SerializationHelper.Serialize(input);
  37804. inputs[input.getClassName()] = res;
  37805. }
  37806. serializedCamera.inputsmgr = inputs;
  37807. };
  37808. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37809. var parsedInputs = parsedCamera.inputsmgr;
  37810. if (parsedInputs) {
  37811. this.clear();
  37812. for (var n in parsedInputs) {
  37813. var construct = BABYLON.CameraInputTypes[n];
  37814. if (construct) {
  37815. var parsedinput = parsedInputs[n];
  37816. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37817. this.add(input);
  37818. }
  37819. }
  37820. }
  37821. else {
  37822. //2016-03-08 this part is for managing backward compatibility
  37823. for (var n in this.attached) {
  37824. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37825. if (construct) {
  37826. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37827. this.remove(this.attached[n]);
  37828. this.add(input);
  37829. }
  37830. }
  37831. }
  37832. };
  37833. return CameraInputsManager;
  37834. }());
  37835. BABYLON.CameraInputsManager = CameraInputsManager;
  37836. })(BABYLON || (BABYLON = {}));
  37837. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37838. var BABYLON;
  37839. (function (BABYLON) {
  37840. var FreeCameraMouseInput = /** @class */ (function () {
  37841. function FreeCameraMouseInput(touchEnabled) {
  37842. if (touchEnabled === void 0) { touchEnabled = true; }
  37843. this.touchEnabled = touchEnabled;
  37844. this.buttons = [0, 1, 2];
  37845. this.angularSensibility = 2000.0;
  37846. this.previousPosition = null;
  37847. }
  37848. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37849. var _this = this;
  37850. var engine = this.camera.getEngine();
  37851. if (!this._pointerInput) {
  37852. this._pointerInput = function (p, s) {
  37853. var evt = p.event;
  37854. if (engine.isInVRExclusivePointerMode) {
  37855. return;
  37856. }
  37857. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37858. return;
  37859. }
  37860. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37861. return;
  37862. }
  37863. var srcElement = (evt.srcElement || evt.target);
  37864. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37865. try {
  37866. srcElement.setPointerCapture(evt.pointerId);
  37867. }
  37868. catch (e) {
  37869. //Nothing to do with the error. Execution will continue.
  37870. }
  37871. _this.previousPosition = {
  37872. x: evt.clientX,
  37873. y: evt.clientY
  37874. };
  37875. if (!noPreventDefault) {
  37876. evt.preventDefault();
  37877. element.focus();
  37878. }
  37879. }
  37880. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37881. try {
  37882. srcElement.releasePointerCapture(evt.pointerId);
  37883. }
  37884. catch (e) {
  37885. //Nothing to do with the error.
  37886. }
  37887. _this.previousPosition = null;
  37888. if (!noPreventDefault) {
  37889. evt.preventDefault();
  37890. }
  37891. }
  37892. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37893. if (!_this.previousPosition || engine.isPointerLock) {
  37894. return;
  37895. }
  37896. var offsetX = evt.clientX - _this.previousPosition.x;
  37897. var offsetY = evt.clientY - _this.previousPosition.y;
  37898. if (_this.camera.getScene().useRightHandedSystem) {
  37899. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37900. }
  37901. else {
  37902. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37903. }
  37904. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37905. _this.previousPosition = {
  37906. x: evt.clientX,
  37907. y: evt.clientY
  37908. };
  37909. if (!noPreventDefault) {
  37910. evt.preventDefault();
  37911. }
  37912. }
  37913. };
  37914. }
  37915. this._onMouseMove = function (evt) {
  37916. if (!engine.isPointerLock) {
  37917. return;
  37918. }
  37919. if (engine.isInVRExclusivePointerMode) {
  37920. return;
  37921. }
  37922. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37923. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37924. if (_this.camera.getScene().useRightHandedSystem) {
  37925. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37926. }
  37927. else {
  37928. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37929. }
  37930. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37931. _this.previousPosition = null;
  37932. if (!noPreventDefault) {
  37933. evt.preventDefault();
  37934. }
  37935. };
  37936. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37937. element.addEventListener("mousemove", this._onMouseMove, false);
  37938. };
  37939. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37940. if (this._observer && element) {
  37941. this.camera.getScene().onPointerObservable.remove(this._observer);
  37942. if (this._onMouseMove) {
  37943. element.removeEventListener("mousemove", this._onMouseMove);
  37944. }
  37945. this._observer = null;
  37946. this._onMouseMove = null;
  37947. this.previousPosition = null;
  37948. }
  37949. };
  37950. FreeCameraMouseInput.prototype.getClassName = function () {
  37951. return "FreeCameraMouseInput";
  37952. };
  37953. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37954. return "mouse";
  37955. };
  37956. __decorate([
  37957. BABYLON.serialize()
  37958. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37959. __decorate([
  37960. BABYLON.serialize()
  37961. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37962. return FreeCameraMouseInput;
  37963. }());
  37964. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37965. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37966. })(BABYLON || (BABYLON = {}));
  37967. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37968. var BABYLON;
  37969. (function (BABYLON) {
  37970. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37971. function FreeCameraKeyboardMoveInput() {
  37972. this._keys = new Array();
  37973. this.keysUp = [38];
  37974. this.keysDown = [40];
  37975. this.keysLeft = [37];
  37976. this.keysRight = [39];
  37977. }
  37978. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37979. var _this = this;
  37980. if (this._onCanvasBlurObserver) {
  37981. return;
  37982. }
  37983. this._scene = this.camera.getScene();
  37984. this._engine = this._scene.getEngine();
  37985. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37986. _this._keys = [];
  37987. });
  37988. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37989. var evt = info.event;
  37990. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37991. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37992. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37993. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37994. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37995. var index = _this._keys.indexOf(evt.keyCode);
  37996. if (index === -1) {
  37997. _this._keys.push(evt.keyCode);
  37998. }
  37999. if (!noPreventDefault) {
  38000. evt.preventDefault();
  38001. }
  38002. }
  38003. }
  38004. else {
  38005. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38006. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38007. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38008. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38009. var index = _this._keys.indexOf(evt.keyCode);
  38010. if (index >= 0) {
  38011. _this._keys.splice(index, 1);
  38012. }
  38013. if (!noPreventDefault) {
  38014. evt.preventDefault();
  38015. }
  38016. }
  38017. }
  38018. });
  38019. };
  38020. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38021. if (this._scene) {
  38022. if (this._onKeyboardObserver) {
  38023. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38024. }
  38025. if (this._onCanvasBlurObserver) {
  38026. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38027. }
  38028. this._onKeyboardObserver = null;
  38029. this._onCanvasBlurObserver = null;
  38030. }
  38031. this._keys = [];
  38032. };
  38033. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38034. if (this._onKeyboardObserver) {
  38035. var camera = this.camera;
  38036. // Keyboard
  38037. for (var index = 0; index < this._keys.length; index++) {
  38038. var keyCode = this._keys[index];
  38039. var speed = camera._computeLocalCameraSpeed();
  38040. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38041. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38042. }
  38043. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38044. camera._localDirection.copyFromFloats(0, 0, speed);
  38045. }
  38046. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38047. camera._localDirection.copyFromFloats(speed, 0, 0);
  38048. }
  38049. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38050. camera._localDirection.copyFromFloats(0, 0, -speed);
  38051. }
  38052. if (camera.getScene().useRightHandedSystem) {
  38053. camera._localDirection.z *= -1;
  38054. }
  38055. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38056. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38057. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38058. }
  38059. }
  38060. };
  38061. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38062. return "FreeCameraKeyboardMoveInput";
  38063. };
  38064. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38065. this._keys = [];
  38066. };
  38067. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38068. return "keyboard";
  38069. };
  38070. __decorate([
  38071. BABYLON.serialize()
  38072. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38073. __decorate([
  38074. BABYLON.serialize()
  38075. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38076. __decorate([
  38077. BABYLON.serialize()
  38078. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38079. __decorate([
  38080. BABYLON.serialize()
  38081. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38082. return FreeCameraKeyboardMoveInput;
  38083. }());
  38084. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38085. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38086. })(BABYLON || (BABYLON = {}));
  38087. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38088. var BABYLON;
  38089. (function (BABYLON) {
  38090. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38091. __extends(FreeCameraInputsManager, _super);
  38092. function FreeCameraInputsManager(camera) {
  38093. return _super.call(this, camera) || this;
  38094. }
  38095. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38096. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38097. return this;
  38098. };
  38099. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38100. if (touchEnabled === void 0) { touchEnabled = true; }
  38101. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38102. return this;
  38103. };
  38104. FreeCameraInputsManager.prototype.addGamepad = function () {
  38105. this.add(new BABYLON.FreeCameraGamepadInput());
  38106. return this;
  38107. };
  38108. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38109. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38110. return this;
  38111. };
  38112. FreeCameraInputsManager.prototype.addTouch = function () {
  38113. this.add(new BABYLON.FreeCameraTouchInput());
  38114. return this;
  38115. };
  38116. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38117. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38118. return this;
  38119. };
  38120. return FreeCameraInputsManager;
  38121. }(BABYLON.CameraInputsManager));
  38122. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38123. })(BABYLON || (BABYLON = {}));
  38124. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38125. var BABYLON;
  38126. (function (BABYLON) {
  38127. var TargetCamera = /** @class */ (function (_super) {
  38128. __extends(TargetCamera, _super);
  38129. function TargetCamera(name, position, scene) {
  38130. var _this = _super.call(this, name, position, scene) || this;
  38131. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38132. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38133. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38134. _this.speed = 2.0;
  38135. _this.noRotationConstraint = false;
  38136. _this.lockedTarget = null;
  38137. _this._currentTarget = BABYLON.Vector3.Zero();
  38138. _this._viewMatrix = BABYLON.Matrix.Zero();
  38139. _this._camMatrix = BABYLON.Matrix.Zero();
  38140. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38141. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38142. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38143. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  38144. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38145. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38146. _this._tempMatrix = BABYLON.Matrix.Zero();
  38147. return _this;
  38148. }
  38149. TargetCamera.prototype.getFrontPosition = function (distance) {
  38150. var direction = this.getTarget().subtract(this.position);
  38151. direction.normalize();
  38152. direction.scaleInPlace(distance);
  38153. return this.globalPosition.add(direction);
  38154. };
  38155. TargetCamera.prototype._getLockedTargetPosition = function () {
  38156. if (!this.lockedTarget) {
  38157. return null;
  38158. }
  38159. if (this.lockedTarget.absolutePosition) {
  38160. this.lockedTarget.computeWorldMatrix();
  38161. }
  38162. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38163. };
  38164. TargetCamera.prototype.storeState = function () {
  38165. this._storedPosition = this.position.clone();
  38166. this._storedRotation = this.rotation.clone();
  38167. if (this.rotationQuaternion) {
  38168. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38169. }
  38170. return _super.prototype.storeState.call(this);
  38171. };
  38172. /**
  38173. * Restored camera state. You must call storeState() first
  38174. */
  38175. TargetCamera.prototype._restoreStateValues = function () {
  38176. if (!_super.prototype._restoreStateValues.call(this)) {
  38177. return false;
  38178. }
  38179. this.position = this._storedPosition.clone();
  38180. this.rotation = this._storedRotation.clone();
  38181. if (this.rotationQuaternion) {
  38182. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38183. }
  38184. this.cameraDirection.copyFromFloats(0, 0, 0);
  38185. this.cameraRotation.copyFromFloats(0, 0);
  38186. return true;
  38187. };
  38188. // Cache
  38189. TargetCamera.prototype._initCache = function () {
  38190. _super.prototype._initCache.call(this);
  38191. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38192. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38193. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38194. };
  38195. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38196. if (!ignoreParentClass) {
  38197. _super.prototype._updateCache.call(this);
  38198. }
  38199. var lockedTargetPosition = this._getLockedTargetPosition();
  38200. if (!lockedTargetPosition) {
  38201. this._cache.lockedTarget = null;
  38202. }
  38203. else {
  38204. if (!this._cache.lockedTarget) {
  38205. this._cache.lockedTarget = lockedTargetPosition.clone();
  38206. }
  38207. else {
  38208. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38209. }
  38210. }
  38211. this._cache.rotation.copyFrom(this.rotation);
  38212. if (this.rotationQuaternion)
  38213. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38214. };
  38215. // Synchronized
  38216. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38217. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38218. return false;
  38219. }
  38220. var lockedTargetPosition = this._getLockedTargetPosition();
  38221. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38222. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38223. };
  38224. // Methods
  38225. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38226. var engine = this.getEngine();
  38227. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38228. };
  38229. // Target
  38230. TargetCamera.prototype.setTarget = function (target) {
  38231. this.upVector.normalize();
  38232. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  38233. this._camMatrix.invert();
  38234. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38235. var vDir = target.subtract(this.position);
  38236. if (vDir.x >= 0.0) {
  38237. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38238. }
  38239. else {
  38240. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38241. }
  38242. this.rotation.z = 0;
  38243. if (isNaN(this.rotation.x)) {
  38244. this.rotation.x = 0;
  38245. }
  38246. if (isNaN(this.rotation.y)) {
  38247. this.rotation.y = 0;
  38248. }
  38249. if (isNaN(this.rotation.z)) {
  38250. this.rotation.z = 0;
  38251. }
  38252. if (this.rotationQuaternion) {
  38253. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38254. }
  38255. };
  38256. /**
  38257. * Return the current target position of the camera. This value is expressed in local space.
  38258. */
  38259. TargetCamera.prototype.getTarget = function () {
  38260. return this._currentTarget;
  38261. };
  38262. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38263. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38264. };
  38265. TargetCamera.prototype._updatePosition = function () {
  38266. if (this.parent) {
  38267. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38268. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38269. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38270. return;
  38271. }
  38272. this.position.addInPlace(this.cameraDirection);
  38273. };
  38274. TargetCamera.prototype._checkInputs = function () {
  38275. var needToMove = this._decideIfNeedsToMove();
  38276. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38277. // Move
  38278. if (needToMove) {
  38279. this._updatePosition();
  38280. }
  38281. // Rotate
  38282. if (needToRotate) {
  38283. this.rotation.x += this.cameraRotation.x;
  38284. this.rotation.y += this.cameraRotation.y;
  38285. //rotate, if quaternion is set and rotation was used
  38286. if (this.rotationQuaternion) {
  38287. var len = this.rotation.lengthSquared();
  38288. if (len) {
  38289. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38290. }
  38291. }
  38292. if (!this.noRotationConstraint) {
  38293. var limit = (Math.PI / 2) * 0.95;
  38294. if (this.rotation.x > limit)
  38295. this.rotation.x = limit;
  38296. if (this.rotation.x < -limit)
  38297. this.rotation.x = -limit;
  38298. }
  38299. }
  38300. // Inertia
  38301. if (needToMove) {
  38302. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38303. this.cameraDirection.x = 0;
  38304. }
  38305. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38306. this.cameraDirection.y = 0;
  38307. }
  38308. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38309. this.cameraDirection.z = 0;
  38310. }
  38311. this.cameraDirection.scaleInPlace(this.inertia);
  38312. }
  38313. if (needToRotate) {
  38314. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38315. this.cameraRotation.x = 0;
  38316. }
  38317. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38318. this.cameraRotation.y = 0;
  38319. }
  38320. this.cameraRotation.scaleInPlace(this.inertia);
  38321. }
  38322. _super.prototype._checkInputs.call(this);
  38323. };
  38324. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38325. if (this.rotationQuaternion) {
  38326. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38327. }
  38328. else {
  38329. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38330. }
  38331. //update the up vector!
  38332. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  38333. };
  38334. TargetCamera.prototype._getViewMatrix = function () {
  38335. if (!this.lockedTarget) {
  38336. // Compute
  38337. this._updateCameraRotationMatrix();
  38338. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38339. // Computing target and final matrix
  38340. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38341. }
  38342. else {
  38343. var targetPosition = this._getLockedTargetPosition();
  38344. if (targetPosition) {
  38345. this._currentTarget.copyFrom(targetPosition);
  38346. }
  38347. }
  38348. if (this.getScene().useRightHandedSystem) {
  38349. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38350. }
  38351. else {
  38352. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38353. }
  38354. return this._viewMatrix;
  38355. };
  38356. /**
  38357. * @override
  38358. * Override Camera.createRigCamera
  38359. */
  38360. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38361. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38362. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38363. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38364. if (!this.rotationQuaternion) {
  38365. this.rotationQuaternion = new BABYLON.Quaternion();
  38366. }
  38367. rigCamera._cameraRigParams = {};
  38368. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38369. }
  38370. return rigCamera;
  38371. }
  38372. return null;
  38373. };
  38374. /**
  38375. * @override
  38376. * Override Camera._updateRigCameras
  38377. */
  38378. TargetCamera.prototype._updateRigCameras = function () {
  38379. var camLeft = this._rigCameras[0];
  38380. var camRight = this._rigCameras[1];
  38381. switch (this.cameraRigMode) {
  38382. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38383. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38385. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38386. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38387. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38388. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38389. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38390. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38391. camLeft.setTarget(this.getTarget());
  38392. camRight.setTarget(this.getTarget());
  38393. break;
  38394. case BABYLON.Camera.RIG_MODE_VR:
  38395. if (camLeft.rotationQuaternion) {
  38396. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38397. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38398. }
  38399. else {
  38400. camLeft.rotation.copyFrom(this.rotation);
  38401. camRight.rotation.copyFrom(this.rotation);
  38402. }
  38403. camLeft.position.copyFrom(this.position);
  38404. camRight.position.copyFrom(this.position);
  38405. break;
  38406. }
  38407. _super.prototype._updateRigCameras.call(this);
  38408. };
  38409. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38410. if (!this._rigCamTransformMatrix) {
  38411. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38412. }
  38413. var target = this.getTarget();
  38414. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38415. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38416. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38417. };
  38418. TargetCamera.prototype.getClassName = function () {
  38419. return "TargetCamera";
  38420. };
  38421. __decorate([
  38422. BABYLON.serializeAsVector3()
  38423. ], TargetCamera.prototype, "rotation", void 0);
  38424. __decorate([
  38425. BABYLON.serialize()
  38426. ], TargetCamera.prototype, "speed", void 0);
  38427. __decorate([
  38428. BABYLON.serializeAsMeshReference("lockedTargetId")
  38429. ], TargetCamera.prototype, "lockedTarget", void 0);
  38430. return TargetCamera;
  38431. }(BABYLON.Camera));
  38432. BABYLON.TargetCamera = TargetCamera;
  38433. })(BABYLON || (BABYLON = {}));
  38434. //# sourceMappingURL=babylon.targetCamera.js.map
  38435. var BABYLON;
  38436. (function (BABYLON) {
  38437. var FreeCamera = /** @class */ (function (_super) {
  38438. __extends(FreeCamera, _super);
  38439. function FreeCamera(name, position, scene) {
  38440. var _this = _super.call(this, name, position, scene) || this;
  38441. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38442. _this.checkCollisions = false;
  38443. _this.applyGravity = false;
  38444. _this._needMoveForGravity = false;
  38445. _this._oldPosition = BABYLON.Vector3.Zero();
  38446. _this._diffPosition = BABYLON.Vector3.Zero();
  38447. _this._newPosition = BABYLON.Vector3.Zero();
  38448. // Collisions
  38449. _this._collisionMask = -1;
  38450. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38451. if (collidedMesh === void 0) { collidedMesh = null; }
  38452. //TODO move this to the collision coordinator!
  38453. if (_this.getScene().workerCollisions)
  38454. newPosition.multiplyInPlace(_this._collider.radius);
  38455. var updatePosition = function (newPos) {
  38456. _this._newPosition.copyFrom(newPos);
  38457. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38458. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38459. _this.position.addInPlace(_this._diffPosition);
  38460. if (_this.onCollide && collidedMesh) {
  38461. _this.onCollide(collidedMesh);
  38462. }
  38463. }
  38464. };
  38465. updatePosition(newPosition);
  38466. };
  38467. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38468. _this.inputs.addKeyboard().addMouse();
  38469. return _this;
  38470. }
  38471. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38472. //-- begin properties for backward compatibility for inputs
  38473. get: function () {
  38474. var mouse = this.inputs.attached["mouse"];
  38475. if (mouse)
  38476. return mouse.angularSensibility;
  38477. return 0;
  38478. },
  38479. set: function (value) {
  38480. var mouse = this.inputs.attached["mouse"];
  38481. if (mouse)
  38482. mouse.angularSensibility = value;
  38483. },
  38484. enumerable: true,
  38485. configurable: true
  38486. });
  38487. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38488. get: function () {
  38489. var keyboard = this.inputs.attached["keyboard"];
  38490. if (keyboard)
  38491. return keyboard.keysUp;
  38492. return [];
  38493. },
  38494. set: function (value) {
  38495. var keyboard = this.inputs.attached["keyboard"];
  38496. if (keyboard)
  38497. keyboard.keysUp = value;
  38498. },
  38499. enumerable: true,
  38500. configurable: true
  38501. });
  38502. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38503. get: function () {
  38504. var keyboard = this.inputs.attached["keyboard"];
  38505. if (keyboard)
  38506. return keyboard.keysDown;
  38507. return [];
  38508. },
  38509. set: function (value) {
  38510. var keyboard = this.inputs.attached["keyboard"];
  38511. if (keyboard)
  38512. keyboard.keysDown = value;
  38513. },
  38514. enumerable: true,
  38515. configurable: true
  38516. });
  38517. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38518. get: function () {
  38519. var keyboard = this.inputs.attached["keyboard"];
  38520. if (keyboard)
  38521. return keyboard.keysLeft;
  38522. return [];
  38523. },
  38524. set: function (value) {
  38525. var keyboard = this.inputs.attached["keyboard"];
  38526. if (keyboard)
  38527. keyboard.keysLeft = value;
  38528. },
  38529. enumerable: true,
  38530. configurable: true
  38531. });
  38532. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38533. get: function () {
  38534. var keyboard = this.inputs.attached["keyboard"];
  38535. if (keyboard)
  38536. return keyboard.keysRight;
  38537. return [];
  38538. },
  38539. set: function (value) {
  38540. var keyboard = this.inputs.attached["keyboard"];
  38541. if (keyboard)
  38542. keyboard.keysRight = value;
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. // Controls
  38548. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38549. this.inputs.attachElement(element, noPreventDefault);
  38550. };
  38551. FreeCamera.prototype.detachControl = function (element) {
  38552. this.inputs.detachElement(element);
  38553. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38554. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38555. };
  38556. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38557. get: function () {
  38558. return this._collisionMask;
  38559. },
  38560. set: function (mask) {
  38561. this._collisionMask = !isNaN(mask) ? mask : -1;
  38562. },
  38563. enumerable: true,
  38564. configurable: true
  38565. });
  38566. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38567. var globalPosition;
  38568. if (this.parent) {
  38569. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38570. }
  38571. else {
  38572. globalPosition = this.position;
  38573. }
  38574. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38575. if (!this._collider) {
  38576. this._collider = new BABYLON.Collider();
  38577. }
  38578. this._collider.radius = this.ellipsoid;
  38579. this._collider.collisionMask = this._collisionMask;
  38580. //no need for clone, as long as gravity is not on.
  38581. var actualDisplacement = displacement;
  38582. //add gravity to the direction to prevent the dual-collision checking
  38583. if (this.applyGravity) {
  38584. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38585. actualDisplacement = displacement.add(this.getScene().gravity);
  38586. }
  38587. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38588. };
  38589. FreeCamera.prototype._checkInputs = function () {
  38590. if (!this._localDirection) {
  38591. this._localDirection = BABYLON.Vector3.Zero();
  38592. this._transformedDirection = BABYLON.Vector3.Zero();
  38593. }
  38594. this.inputs.checkInputs();
  38595. _super.prototype._checkInputs.call(this);
  38596. };
  38597. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38598. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38599. };
  38600. FreeCamera.prototype._updatePosition = function () {
  38601. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38602. this._collideWithWorld(this.cameraDirection);
  38603. }
  38604. else {
  38605. _super.prototype._updatePosition.call(this);
  38606. }
  38607. };
  38608. FreeCamera.prototype.dispose = function () {
  38609. this.inputs.clear();
  38610. _super.prototype.dispose.call(this);
  38611. };
  38612. FreeCamera.prototype.getClassName = function () {
  38613. return "FreeCamera";
  38614. };
  38615. __decorate([
  38616. BABYLON.serializeAsVector3()
  38617. ], FreeCamera.prototype, "ellipsoid", void 0);
  38618. __decorate([
  38619. BABYLON.serialize()
  38620. ], FreeCamera.prototype, "checkCollisions", void 0);
  38621. __decorate([
  38622. BABYLON.serialize()
  38623. ], FreeCamera.prototype, "applyGravity", void 0);
  38624. return FreeCamera;
  38625. }(BABYLON.TargetCamera));
  38626. BABYLON.FreeCamera = FreeCamera;
  38627. })(BABYLON || (BABYLON = {}));
  38628. //# sourceMappingURL=babylon.freeCamera.js.map
  38629. var BABYLON;
  38630. (function (BABYLON) {
  38631. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38632. function ArcRotateCameraKeyboardMoveInput() {
  38633. this._keys = new Array();
  38634. this.keysUp = [38];
  38635. this.keysDown = [40];
  38636. this.keysLeft = [37];
  38637. this.keysRight = [39];
  38638. this.keysReset = [220];
  38639. this.panningSensibility = 50.0;
  38640. this.zoomingSensibility = 25.0;
  38641. this.useAltToZoom = true;
  38642. }
  38643. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38644. var _this = this;
  38645. if (this._onCanvasBlurObserver) {
  38646. return;
  38647. }
  38648. this._scene = this.camera.getScene();
  38649. this._engine = this._scene.getEngine();
  38650. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38651. _this._keys = [];
  38652. });
  38653. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38654. var evt = info.event;
  38655. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38656. _this._ctrlPressed = evt.ctrlKey;
  38657. _this._altPressed = evt.altKey;
  38658. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38659. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38660. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38661. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38662. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38663. var index = _this._keys.indexOf(evt.keyCode);
  38664. if (index === -1) {
  38665. _this._keys.push(evt.keyCode);
  38666. }
  38667. if (evt.preventDefault) {
  38668. if (!noPreventDefault) {
  38669. evt.preventDefault();
  38670. }
  38671. }
  38672. }
  38673. }
  38674. else {
  38675. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38676. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38677. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38678. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38679. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38680. var index = _this._keys.indexOf(evt.keyCode);
  38681. if (index >= 0) {
  38682. _this._keys.splice(index, 1);
  38683. }
  38684. if (evt.preventDefault) {
  38685. if (!noPreventDefault) {
  38686. evt.preventDefault();
  38687. }
  38688. }
  38689. }
  38690. }
  38691. });
  38692. };
  38693. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38694. if (this._scene) {
  38695. if (this._onKeyboardObserver) {
  38696. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38697. }
  38698. if (this._onCanvasBlurObserver) {
  38699. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38700. }
  38701. this._onKeyboardObserver = null;
  38702. this._onCanvasBlurObserver = null;
  38703. }
  38704. this._keys = [];
  38705. };
  38706. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38707. if (this._onKeyboardObserver) {
  38708. var camera = this.camera;
  38709. for (var index = 0; index < this._keys.length; index++) {
  38710. var keyCode = this._keys[index];
  38711. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38712. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38713. camera.inertialPanningX -= 1 / this.panningSensibility;
  38714. }
  38715. else {
  38716. camera.inertialAlphaOffset -= 0.01;
  38717. }
  38718. }
  38719. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38720. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38721. camera.inertialPanningY += 1 / this.panningSensibility;
  38722. }
  38723. else if (this._altPressed && this.useAltToZoom) {
  38724. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38725. }
  38726. else {
  38727. camera.inertialBetaOffset -= 0.01;
  38728. }
  38729. }
  38730. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38731. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38732. camera.inertialPanningX += 1 / this.panningSensibility;
  38733. }
  38734. else {
  38735. camera.inertialAlphaOffset += 0.01;
  38736. }
  38737. }
  38738. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38739. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38740. camera.inertialPanningY -= 1 / this.panningSensibility;
  38741. }
  38742. else if (this._altPressed && this.useAltToZoom) {
  38743. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38744. }
  38745. else {
  38746. camera.inertialBetaOffset += 0.01;
  38747. }
  38748. }
  38749. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38750. camera.restoreState();
  38751. }
  38752. }
  38753. }
  38754. };
  38755. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38756. return "ArcRotateCameraKeyboardMoveInput";
  38757. };
  38758. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38759. return "keyboard";
  38760. };
  38761. __decorate([
  38762. BABYLON.serialize()
  38763. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38764. __decorate([
  38765. BABYLON.serialize()
  38766. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38767. __decorate([
  38768. BABYLON.serialize()
  38769. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38770. __decorate([
  38771. BABYLON.serialize()
  38772. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38773. __decorate([
  38774. BABYLON.serialize()
  38775. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38776. __decorate([
  38777. BABYLON.serialize()
  38778. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38779. __decorate([
  38780. BABYLON.serialize()
  38781. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38782. __decorate([
  38783. BABYLON.serialize()
  38784. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38785. return ArcRotateCameraKeyboardMoveInput;
  38786. }());
  38787. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38788. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38789. })(BABYLON || (BABYLON = {}));
  38790. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38791. var BABYLON;
  38792. (function (BABYLON) {
  38793. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38794. function ArcRotateCameraMouseWheelInput() {
  38795. this.wheelPrecision = 3.0;
  38796. /**
  38797. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38798. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38799. */
  38800. this.wheelDeltaPercentage = 0;
  38801. }
  38802. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38803. var _this = this;
  38804. this._wheel = function (p, s) {
  38805. //sanity check - this should be a PointerWheel event.
  38806. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38807. return;
  38808. var event = p.event;
  38809. var delta = 0;
  38810. if (event.wheelDelta) {
  38811. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38812. }
  38813. else if (event.detail) {
  38814. delta = -event.detail / _this.wheelPrecision;
  38815. }
  38816. if (delta)
  38817. _this.camera.inertialRadiusOffset += delta;
  38818. if (event.preventDefault) {
  38819. if (!noPreventDefault) {
  38820. event.preventDefault();
  38821. }
  38822. }
  38823. };
  38824. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38825. };
  38826. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38827. if (this._observer && element) {
  38828. this.camera.getScene().onPointerObservable.remove(this._observer);
  38829. this._observer = null;
  38830. this._wheel = null;
  38831. }
  38832. };
  38833. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38834. return "ArcRotateCameraMouseWheelInput";
  38835. };
  38836. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38837. return "mousewheel";
  38838. };
  38839. __decorate([
  38840. BABYLON.serialize()
  38841. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38842. __decorate([
  38843. BABYLON.serialize()
  38844. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38845. return ArcRotateCameraMouseWheelInput;
  38846. }());
  38847. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38848. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38849. })(BABYLON || (BABYLON = {}));
  38850. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38851. var BABYLON;
  38852. (function (BABYLON) {
  38853. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38854. function ArcRotateCameraPointersInput() {
  38855. this.buttons = [0, 1, 2];
  38856. this.angularSensibilityX = 1000.0;
  38857. this.angularSensibilityY = 1000.0;
  38858. this.pinchPrecision = 12.0;
  38859. /**
  38860. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38861. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38862. */
  38863. this.pinchDeltaPercentage = 0;
  38864. this.panningSensibility = 1000.0;
  38865. this.multiTouchPanning = true;
  38866. this.multiTouchPanAndZoom = true;
  38867. this._isPanClick = false;
  38868. this.pinchInwards = true;
  38869. }
  38870. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38871. var _this = this;
  38872. var engine = this.camera.getEngine();
  38873. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38874. var pointA = null;
  38875. var pointB = null;
  38876. var previousPinchSquaredDistance = 0;
  38877. var initialDistance = 0;
  38878. var twoFingerActivityCount = 0;
  38879. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38880. this._pointerInput = function (p, s) {
  38881. var evt = p.event;
  38882. var isTouch = p.event.pointerType === "touch";
  38883. if (engine.isInVRExclusivePointerMode) {
  38884. return;
  38885. }
  38886. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38887. return;
  38888. }
  38889. var srcElement = (evt.srcElement || evt.target);
  38890. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38891. try {
  38892. srcElement.setPointerCapture(evt.pointerId);
  38893. }
  38894. catch (e) {
  38895. //Nothing to do with the error. Execution will continue.
  38896. }
  38897. // Manage panning with pan button click
  38898. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38899. // manage pointers
  38900. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38901. if (pointA === null) {
  38902. pointA = cacheSoloPointer;
  38903. }
  38904. else if (pointB === null) {
  38905. pointB = cacheSoloPointer;
  38906. }
  38907. if (!noPreventDefault) {
  38908. evt.preventDefault();
  38909. element.focus();
  38910. }
  38911. }
  38912. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38913. _this.camera.restoreState();
  38914. }
  38915. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38916. try {
  38917. srcElement.releasePointerCapture(evt.pointerId);
  38918. }
  38919. catch (e) {
  38920. //Nothing to do with the error.
  38921. }
  38922. cacheSoloPointer = null;
  38923. previousPinchSquaredDistance = 0;
  38924. previousMultiTouchPanPosition.isPaning = false;
  38925. previousMultiTouchPanPosition.isPinching = false;
  38926. twoFingerActivityCount = 0;
  38927. initialDistance = 0;
  38928. if (!isTouch) {
  38929. pointB = null; // Mouse and pen are mono pointer
  38930. }
  38931. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38932. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38933. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38934. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38935. if (engine.badOS) {
  38936. pointA = pointB = null;
  38937. }
  38938. else {
  38939. //only remove the impacted pointer in case of multitouch allowing on most
  38940. //platforms switching from rotate to zoom and pan seamlessly.
  38941. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38942. pointA = pointB;
  38943. pointB = null;
  38944. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38945. }
  38946. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38947. pointB = null;
  38948. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38949. }
  38950. else {
  38951. pointA = pointB = null;
  38952. }
  38953. }
  38954. if (!noPreventDefault) {
  38955. evt.preventDefault();
  38956. }
  38957. }
  38958. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38959. if (!noPreventDefault) {
  38960. evt.preventDefault();
  38961. }
  38962. // One button down
  38963. if (pointA && pointB === null && cacheSoloPointer) {
  38964. if (_this.panningSensibility !== 0 &&
  38965. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38966. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38967. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38968. }
  38969. else {
  38970. var offsetX = evt.clientX - cacheSoloPointer.x;
  38971. var offsetY = evt.clientY - cacheSoloPointer.y;
  38972. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38973. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38974. }
  38975. cacheSoloPointer.x = evt.clientX;
  38976. cacheSoloPointer.y = evt.clientY;
  38977. }
  38978. else if (pointA && pointB) {
  38979. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38980. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38981. ed.x = evt.clientX;
  38982. ed.y = evt.clientY;
  38983. var direction = _this.pinchInwards ? 1 : -1;
  38984. var distX = pointA.x - pointB.x;
  38985. var distY = pointA.y - pointB.y;
  38986. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38987. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38988. if (previousPinchSquaredDistance === 0) {
  38989. initialDistance = pinchDistance;
  38990. previousPinchSquaredDistance = pinchSquaredDistance;
  38991. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38992. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38993. return;
  38994. }
  38995. if (_this.multiTouchPanAndZoom) {
  38996. if (_this.pinchDeltaPercentage) {
  38997. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38998. }
  38999. else {
  39000. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39001. (_this.pinchPrecision *
  39002. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39003. direction);
  39004. }
  39005. if (_this.panningSensibility !== 0) {
  39006. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39007. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39008. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39009. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39010. previousMultiTouchPanPosition.x = pointersCenterX;
  39011. previousMultiTouchPanPosition.y = pointersCenterY;
  39012. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39013. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39014. }
  39015. }
  39016. else {
  39017. twoFingerActivityCount++;
  39018. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39019. if (_this.pinchDeltaPercentage) {
  39020. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39021. }
  39022. else {
  39023. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39024. (_this.pinchPrecision *
  39025. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39026. direction);
  39027. }
  39028. previousMultiTouchPanPosition.isPaning = false;
  39029. previousMultiTouchPanPosition.isPinching = true;
  39030. }
  39031. else {
  39032. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39033. if (!previousMultiTouchPanPosition.isPaning) {
  39034. previousMultiTouchPanPosition.isPaning = true;
  39035. previousMultiTouchPanPosition.isPinching = false;
  39036. previousMultiTouchPanPosition.x = ed.x;
  39037. previousMultiTouchPanPosition.y = ed.y;
  39038. return;
  39039. }
  39040. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39041. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39042. }
  39043. }
  39044. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39045. previousMultiTouchPanPosition.x = ed.x;
  39046. previousMultiTouchPanPosition.y = ed.y;
  39047. }
  39048. }
  39049. previousPinchSquaredDistance = pinchSquaredDistance;
  39050. }
  39051. }
  39052. };
  39053. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39054. this._onContextMenu = function (evt) {
  39055. evt.preventDefault();
  39056. };
  39057. if (!this.camera._useCtrlForPanning) {
  39058. element.addEventListener("contextmenu", this._onContextMenu, false);
  39059. }
  39060. this._onLostFocus = function () {
  39061. //this._keys = [];
  39062. pointA = pointB = null;
  39063. previousPinchSquaredDistance = 0;
  39064. previousMultiTouchPanPosition.isPaning = false;
  39065. previousMultiTouchPanPosition.isPinching = false;
  39066. twoFingerActivityCount = 0;
  39067. cacheSoloPointer = null;
  39068. initialDistance = 0;
  39069. };
  39070. this._onMouseMove = function (evt) {
  39071. if (!engine.isPointerLock) {
  39072. return;
  39073. }
  39074. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39075. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39076. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39077. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39078. if (!noPreventDefault) {
  39079. evt.preventDefault();
  39080. }
  39081. };
  39082. this._onGestureStart = function (e) {
  39083. if (window.MSGesture === undefined) {
  39084. return;
  39085. }
  39086. if (!_this._MSGestureHandler) {
  39087. _this._MSGestureHandler = new MSGesture();
  39088. _this._MSGestureHandler.target = element;
  39089. }
  39090. _this._MSGestureHandler.addPointer(e.pointerId);
  39091. };
  39092. this._onGesture = function (e) {
  39093. _this.camera.radius *= e.scale;
  39094. if (e.preventDefault) {
  39095. if (!noPreventDefault) {
  39096. e.stopPropagation();
  39097. e.preventDefault();
  39098. }
  39099. }
  39100. };
  39101. element.addEventListener("mousemove", this._onMouseMove, false);
  39102. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39103. element.addEventListener("MSGestureChange", this._onGesture, false);
  39104. BABYLON.Tools.RegisterTopRootEvents([
  39105. { name: "blur", handler: this._onLostFocus }
  39106. ]);
  39107. };
  39108. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39109. if (this._onLostFocus) {
  39110. BABYLON.Tools.UnregisterTopRootEvents([
  39111. { name: "blur", handler: this._onLostFocus }
  39112. ]);
  39113. }
  39114. if (element && this._observer) {
  39115. this.camera.getScene().onPointerObservable.remove(this._observer);
  39116. this._observer = null;
  39117. if (this._onContextMenu) {
  39118. element.removeEventListener("contextmenu", this._onContextMenu);
  39119. }
  39120. if (this._onMouseMove) {
  39121. element.removeEventListener("mousemove", this._onMouseMove);
  39122. }
  39123. if (this._onGestureStart) {
  39124. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39125. }
  39126. if (this._onGesture) {
  39127. element.removeEventListener("MSGestureChange", this._onGesture);
  39128. }
  39129. this._isPanClick = false;
  39130. this.pinchInwards = true;
  39131. this._onMouseMove = null;
  39132. this._onGestureStart = null;
  39133. this._onGesture = null;
  39134. this._MSGestureHandler = null;
  39135. this._onLostFocus = null;
  39136. this._onContextMenu = null;
  39137. }
  39138. };
  39139. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39140. return "ArcRotateCameraPointersInput";
  39141. };
  39142. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39143. return "pointers";
  39144. };
  39145. __decorate([
  39146. BABYLON.serialize()
  39147. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39148. __decorate([
  39149. BABYLON.serialize()
  39150. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39151. __decorate([
  39152. BABYLON.serialize()
  39153. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39154. __decorate([
  39155. BABYLON.serialize()
  39156. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39157. __decorate([
  39158. BABYLON.serialize()
  39159. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39160. __decorate([
  39161. BABYLON.serialize()
  39162. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39163. __decorate([
  39164. BABYLON.serialize()
  39165. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39166. __decorate([
  39167. BABYLON.serialize()
  39168. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39169. return ArcRotateCameraPointersInput;
  39170. }());
  39171. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39172. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39173. })(BABYLON || (BABYLON = {}));
  39174. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39175. var BABYLON;
  39176. (function (BABYLON) {
  39177. var ArcRotateCamera = /** @class */ (function (_super) {
  39178. __extends(ArcRotateCamera, _super);
  39179. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39180. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39181. _this.inertialAlphaOffset = 0;
  39182. _this.inertialBetaOffset = 0;
  39183. _this.inertialRadiusOffset = 0;
  39184. _this.lowerAlphaLimit = null;
  39185. _this.upperAlphaLimit = null;
  39186. _this.lowerBetaLimit = 0.01;
  39187. _this.upperBetaLimit = Math.PI;
  39188. _this.lowerRadiusLimit = null;
  39189. _this.upperRadiusLimit = null;
  39190. _this.inertialPanningX = 0;
  39191. _this.inertialPanningY = 0;
  39192. _this.pinchToPanMaxDistance = 20;
  39193. _this.panningDistanceLimit = null;
  39194. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39195. _this.panningInertia = 0.9;
  39196. //-- end properties for backward compatibility for inputs
  39197. _this.zoomOnFactor = 1;
  39198. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39199. _this.allowUpsideDown = true;
  39200. _this._viewMatrix = new BABYLON.Matrix();
  39201. // Panning
  39202. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39203. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39204. _this.checkCollisions = false;
  39205. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39206. _this._previousPosition = BABYLON.Vector3.Zero();
  39207. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39208. _this._newPosition = BABYLON.Vector3.Zero();
  39209. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39210. if (collidedMesh === void 0) { collidedMesh = null; }
  39211. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39212. newPosition.multiplyInPlace(_this._collider.radius);
  39213. }
  39214. if (!collidedMesh) {
  39215. _this._previousPosition.copyFrom(_this.position);
  39216. }
  39217. else {
  39218. _this.setPosition(newPosition);
  39219. if (_this.onCollide) {
  39220. _this.onCollide(collidedMesh);
  39221. }
  39222. }
  39223. // Recompute because of constraints
  39224. var cosa = Math.cos(_this.alpha);
  39225. var sina = Math.sin(_this.alpha);
  39226. var cosb = Math.cos(_this.beta);
  39227. var sinb = Math.sin(_this.beta);
  39228. if (sinb === 0) {
  39229. sinb = 0.0001;
  39230. }
  39231. var target = _this._getTargetPosition();
  39232. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39233. _this.position.copyFrom(_this._newPosition);
  39234. var up = _this.upVector;
  39235. if (_this.allowUpsideDown && _this.beta < 0) {
  39236. up = up.clone();
  39237. up = up.negate();
  39238. }
  39239. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39240. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39241. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39242. _this._collisionTriggered = false;
  39243. };
  39244. _this._target = BABYLON.Vector3.Zero();
  39245. if (target) {
  39246. _this.setTarget(target);
  39247. }
  39248. _this.alpha = alpha;
  39249. _this.beta = beta;
  39250. _this.radius = radius;
  39251. _this.getViewMatrix();
  39252. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39253. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39254. return _this;
  39255. }
  39256. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39257. get: function () {
  39258. return this._target;
  39259. },
  39260. set: function (value) {
  39261. this.setTarget(value);
  39262. },
  39263. enumerable: true,
  39264. configurable: true
  39265. });
  39266. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39267. //-- begin properties for backward compatibility for inputs
  39268. get: function () {
  39269. var pointers = this.inputs.attached["pointers"];
  39270. if (pointers)
  39271. return pointers.angularSensibilityX;
  39272. return 0;
  39273. },
  39274. set: function (value) {
  39275. var pointers = this.inputs.attached["pointers"];
  39276. if (pointers) {
  39277. pointers.angularSensibilityX = value;
  39278. }
  39279. },
  39280. enumerable: true,
  39281. configurable: true
  39282. });
  39283. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39284. get: function () {
  39285. var pointers = this.inputs.attached["pointers"];
  39286. if (pointers)
  39287. return pointers.angularSensibilityY;
  39288. return 0;
  39289. },
  39290. set: function (value) {
  39291. var pointers = this.inputs.attached["pointers"];
  39292. if (pointers) {
  39293. pointers.angularSensibilityY = value;
  39294. }
  39295. },
  39296. enumerable: true,
  39297. configurable: true
  39298. });
  39299. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39300. get: function () {
  39301. var pointers = this.inputs.attached["pointers"];
  39302. if (pointers)
  39303. return pointers.pinchPrecision;
  39304. return 0;
  39305. },
  39306. set: function (value) {
  39307. var pointers = this.inputs.attached["pointers"];
  39308. if (pointers) {
  39309. pointers.pinchPrecision = value;
  39310. }
  39311. },
  39312. enumerable: true,
  39313. configurable: true
  39314. });
  39315. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39316. get: function () {
  39317. var pointers = this.inputs.attached["pointers"];
  39318. if (pointers)
  39319. return pointers.pinchDeltaPercentage;
  39320. return 0;
  39321. },
  39322. set: function (value) {
  39323. var pointers = this.inputs.attached["pointers"];
  39324. if (pointers) {
  39325. pointers.pinchDeltaPercentage = value;
  39326. }
  39327. },
  39328. enumerable: true,
  39329. configurable: true
  39330. });
  39331. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39332. get: function () {
  39333. var pointers = this.inputs.attached["pointers"];
  39334. if (pointers)
  39335. return pointers.panningSensibility;
  39336. return 0;
  39337. },
  39338. set: function (value) {
  39339. var pointers = this.inputs.attached["pointers"];
  39340. if (pointers) {
  39341. pointers.panningSensibility = value;
  39342. }
  39343. },
  39344. enumerable: true,
  39345. configurable: true
  39346. });
  39347. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39348. get: function () {
  39349. var keyboard = this.inputs.attached["keyboard"];
  39350. if (keyboard)
  39351. return keyboard.keysUp;
  39352. return [];
  39353. },
  39354. set: function (value) {
  39355. var keyboard = this.inputs.attached["keyboard"];
  39356. if (keyboard)
  39357. keyboard.keysUp = value;
  39358. },
  39359. enumerable: true,
  39360. configurable: true
  39361. });
  39362. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39363. get: function () {
  39364. var keyboard = this.inputs.attached["keyboard"];
  39365. if (keyboard)
  39366. return keyboard.keysDown;
  39367. return [];
  39368. },
  39369. set: function (value) {
  39370. var keyboard = this.inputs.attached["keyboard"];
  39371. if (keyboard)
  39372. keyboard.keysDown = value;
  39373. },
  39374. enumerable: true,
  39375. configurable: true
  39376. });
  39377. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39378. get: function () {
  39379. var keyboard = this.inputs.attached["keyboard"];
  39380. if (keyboard)
  39381. return keyboard.keysLeft;
  39382. return [];
  39383. },
  39384. set: function (value) {
  39385. var keyboard = this.inputs.attached["keyboard"];
  39386. if (keyboard)
  39387. keyboard.keysLeft = value;
  39388. },
  39389. enumerable: true,
  39390. configurable: true
  39391. });
  39392. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39393. get: function () {
  39394. var keyboard = this.inputs.attached["keyboard"];
  39395. if (keyboard)
  39396. return keyboard.keysRight;
  39397. return [];
  39398. },
  39399. set: function (value) {
  39400. var keyboard = this.inputs.attached["keyboard"];
  39401. if (keyboard)
  39402. keyboard.keysRight = value;
  39403. },
  39404. enumerable: true,
  39405. configurable: true
  39406. });
  39407. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39408. get: function () {
  39409. var mousewheel = this.inputs.attached["mousewheel"];
  39410. if (mousewheel)
  39411. return mousewheel.wheelPrecision;
  39412. return 0;
  39413. },
  39414. set: function (value) {
  39415. var mousewheel = this.inputs.attached["mousewheel"];
  39416. if (mousewheel)
  39417. mousewheel.wheelPrecision = value;
  39418. },
  39419. enumerable: true,
  39420. configurable: true
  39421. });
  39422. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39423. get: function () {
  39424. var mousewheel = this.inputs.attached["mousewheel"];
  39425. if (mousewheel)
  39426. return mousewheel.wheelDeltaPercentage;
  39427. return 0;
  39428. },
  39429. set: function (value) {
  39430. var mousewheel = this.inputs.attached["mousewheel"];
  39431. if (mousewheel)
  39432. mousewheel.wheelDeltaPercentage = value;
  39433. },
  39434. enumerable: true,
  39435. configurable: true
  39436. });
  39437. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39438. get: function () {
  39439. return this._bouncingBehavior;
  39440. },
  39441. enumerable: true,
  39442. configurable: true
  39443. });
  39444. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39445. get: function () {
  39446. return this._bouncingBehavior != null;
  39447. },
  39448. set: function (value) {
  39449. if (value === this.useBouncingBehavior) {
  39450. return;
  39451. }
  39452. if (value) {
  39453. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39454. this.addBehavior(this._bouncingBehavior);
  39455. }
  39456. else if (this._bouncingBehavior) {
  39457. this.removeBehavior(this._bouncingBehavior);
  39458. this._bouncingBehavior = null;
  39459. }
  39460. },
  39461. enumerable: true,
  39462. configurable: true
  39463. });
  39464. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39465. get: function () {
  39466. return this._framingBehavior;
  39467. },
  39468. enumerable: true,
  39469. configurable: true
  39470. });
  39471. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39472. get: function () {
  39473. return this._framingBehavior != null;
  39474. },
  39475. set: function (value) {
  39476. if (value === this.useFramingBehavior) {
  39477. return;
  39478. }
  39479. if (value) {
  39480. this._framingBehavior = new BABYLON.FramingBehavior();
  39481. this.addBehavior(this._framingBehavior);
  39482. }
  39483. else if (this._framingBehavior) {
  39484. this.removeBehavior(this._framingBehavior);
  39485. this._framingBehavior = null;
  39486. }
  39487. },
  39488. enumerable: true,
  39489. configurable: true
  39490. });
  39491. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39492. get: function () {
  39493. return this._autoRotationBehavior;
  39494. },
  39495. enumerable: true,
  39496. configurable: true
  39497. });
  39498. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39499. get: function () {
  39500. return this._autoRotationBehavior != null;
  39501. },
  39502. set: function (value) {
  39503. if (value === this.useAutoRotationBehavior) {
  39504. return;
  39505. }
  39506. if (value) {
  39507. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39508. this.addBehavior(this._autoRotationBehavior);
  39509. }
  39510. else if (this._autoRotationBehavior) {
  39511. this.removeBehavior(this._autoRotationBehavior);
  39512. this._autoRotationBehavior = null;
  39513. }
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. // Cache
  39519. ArcRotateCamera.prototype._initCache = function () {
  39520. _super.prototype._initCache.call(this);
  39521. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39522. this._cache.alpha = undefined;
  39523. this._cache.beta = undefined;
  39524. this._cache.radius = undefined;
  39525. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39526. };
  39527. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39528. if (!ignoreParentClass) {
  39529. _super.prototype._updateCache.call(this);
  39530. }
  39531. this._cache._target.copyFrom(this._getTargetPosition());
  39532. this._cache.alpha = this.alpha;
  39533. this._cache.beta = this.beta;
  39534. this._cache.radius = this.radius;
  39535. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39536. };
  39537. ArcRotateCamera.prototype._getTargetPosition = function () {
  39538. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39539. var pos = this._targetHost.getAbsolutePosition();
  39540. if (this._targetBoundingCenter) {
  39541. pos.addToRef(this._targetBoundingCenter, this._target);
  39542. }
  39543. else {
  39544. this._target.copyFrom(pos);
  39545. }
  39546. }
  39547. var lockedTargetPosition = this._getLockedTargetPosition();
  39548. if (lockedTargetPosition) {
  39549. return lockedTargetPosition;
  39550. }
  39551. return this._target;
  39552. };
  39553. ArcRotateCamera.prototype.storeState = function () {
  39554. this._storedAlpha = this.alpha;
  39555. this._storedBeta = this.beta;
  39556. this._storedRadius = this.radius;
  39557. this._storedTarget = this._getTargetPosition().clone();
  39558. return _super.prototype.storeState.call(this);
  39559. };
  39560. /**
  39561. * Restored camera state. You must call storeState() first
  39562. */
  39563. ArcRotateCamera.prototype._restoreStateValues = function () {
  39564. if (!_super.prototype._restoreStateValues.call(this)) {
  39565. return false;
  39566. }
  39567. this.alpha = this._storedAlpha;
  39568. this.beta = this._storedBeta;
  39569. this.radius = this._storedRadius;
  39570. this.setTarget(this._storedTarget.clone());
  39571. this.inertialAlphaOffset = 0;
  39572. this.inertialBetaOffset = 0;
  39573. this.inertialRadiusOffset = 0;
  39574. this.inertialPanningX = 0;
  39575. this.inertialPanningY = 0;
  39576. return true;
  39577. };
  39578. // Synchronized
  39579. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39580. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39581. return false;
  39582. return this._cache._target.equals(this._getTargetPosition())
  39583. && this._cache.alpha === this.alpha
  39584. && this._cache.beta === this.beta
  39585. && this._cache.radius === this.radius
  39586. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39587. };
  39588. // Methods
  39589. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39590. var _this = this;
  39591. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39592. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39593. this._useCtrlForPanning = useCtrlForPanning;
  39594. this._panningMouseButton = panningMouseButton;
  39595. this.inputs.attachElement(element, noPreventDefault);
  39596. this._reset = function () {
  39597. _this.inertialAlphaOffset = 0;
  39598. _this.inertialBetaOffset = 0;
  39599. _this.inertialRadiusOffset = 0;
  39600. _this.inertialPanningX = 0;
  39601. _this.inertialPanningY = 0;
  39602. };
  39603. };
  39604. ArcRotateCamera.prototype.detachControl = function (element) {
  39605. this.inputs.detachElement(element);
  39606. if (this._reset) {
  39607. this._reset();
  39608. }
  39609. };
  39610. ArcRotateCamera.prototype._checkInputs = function () {
  39611. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39612. if (this._collisionTriggered) {
  39613. return;
  39614. }
  39615. this.inputs.checkInputs();
  39616. // Inertia
  39617. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39618. if (this.getScene().useRightHandedSystem) {
  39619. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39620. }
  39621. else {
  39622. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39623. }
  39624. this.beta += this.inertialBetaOffset;
  39625. this.radius -= this.inertialRadiusOffset;
  39626. this.inertialAlphaOffset *= this.inertia;
  39627. this.inertialBetaOffset *= this.inertia;
  39628. this.inertialRadiusOffset *= this.inertia;
  39629. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39630. this.inertialAlphaOffset = 0;
  39631. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39632. this.inertialBetaOffset = 0;
  39633. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39634. this.inertialRadiusOffset = 0;
  39635. }
  39636. // Panning inertia
  39637. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39638. if (!this._localDirection) {
  39639. this._localDirection = BABYLON.Vector3.Zero();
  39640. this._transformedDirection = BABYLON.Vector3.Zero();
  39641. }
  39642. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39643. this._localDirection.multiplyInPlace(this.panningAxis);
  39644. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39645. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39646. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39647. if (!this.panningAxis.y) {
  39648. this._transformedDirection.y = 0;
  39649. }
  39650. if (!this._targetHost) {
  39651. if (this.panningDistanceLimit) {
  39652. this._transformedDirection.addInPlace(this._target);
  39653. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39654. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39655. this._target.copyFrom(this._transformedDirection);
  39656. }
  39657. }
  39658. else {
  39659. this._target.addInPlace(this._transformedDirection);
  39660. }
  39661. }
  39662. this.inertialPanningX *= this.panningInertia;
  39663. this.inertialPanningY *= this.panningInertia;
  39664. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39665. this.inertialPanningX = 0;
  39666. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39667. this.inertialPanningY = 0;
  39668. }
  39669. // Limits
  39670. this._checkLimits();
  39671. _super.prototype._checkInputs.call(this);
  39672. };
  39673. ArcRotateCamera.prototype._checkLimits = function () {
  39674. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39675. if (this.allowUpsideDown && this.beta > Math.PI) {
  39676. this.beta = this.beta - (2 * Math.PI);
  39677. }
  39678. }
  39679. else {
  39680. if (this.beta < this.lowerBetaLimit) {
  39681. this.beta = this.lowerBetaLimit;
  39682. }
  39683. }
  39684. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39685. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39686. this.beta = this.beta + (2 * Math.PI);
  39687. }
  39688. }
  39689. else {
  39690. if (this.beta > this.upperBetaLimit) {
  39691. this.beta = this.upperBetaLimit;
  39692. }
  39693. }
  39694. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39695. this.alpha = this.lowerAlphaLimit;
  39696. }
  39697. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39698. this.alpha = this.upperAlphaLimit;
  39699. }
  39700. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39701. this.radius = this.lowerRadiusLimit;
  39702. }
  39703. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39704. this.radius = this.upperRadiusLimit;
  39705. }
  39706. };
  39707. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39708. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39709. this.radius = radiusv3.length();
  39710. if (this.radius === 0) {
  39711. this.radius = 0.0001; // Just to avoid division by zero
  39712. }
  39713. // Alpha
  39714. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39715. if (radiusv3.z < 0) {
  39716. this.alpha = 2 * Math.PI - this.alpha;
  39717. }
  39718. // Beta
  39719. this.beta = Math.acos(radiusv3.y / this.radius);
  39720. this._checkLimits();
  39721. };
  39722. ArcRotateCamera.prototype.setPosition = function (position) {
  39723. if (this.position.equals(position)) {
  39724. return;
  39725. }
  39726. this.position.copyFrom(position);
  39727. this.rebuildAnglesAndRadius();
  39728. };
  39729. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39730. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39731. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39732. if (target.getBoundingInfo) {
  39733. if (toBoundingCenter) {
  39734. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39735. }
  39736. else {
  39737. this._targetBoundingCenter = null;
  39738. }
  39739. this._targetHost = target;
  39740. this._target = this._getTargetPosition();
  39741. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39742. }
  39743. else {
  39744. var newTarget = target;
  39745. var currentTarget = this._getTargetPosition();
  39746. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39747. return;
  39748. }
  39749. this._targetHost = null;
  39750. this._target = newTarget;
  39751. this._targetBoundingCenter = null;
  39752. this.onMeshTargetChangedObservable.notifyObservers(null);
  39753. }
  39754. this.rebuildAnglesAndRadius();
  39755. };
  39756. ArcRotateCamera.prototype._getViewMatrix = function () {
  39757. // Compute
  39758. var cosa = Math.cos(this.alpha);
  39759. var sina = Math.sin(this.alpha);
  39760. var cosb = Math.cos(this.beta);
  39761. var sinb = Math.sin(this.beta);
  39762. if (sinb === 0) {
  39763. sinb = 0.0001;
  39764. }
  39765. var target = this._getTargetPosition();
  39766. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39767. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39768. if (!this._collider) {
  39769. this._collider = new BABYLON.Collider();
  39770. }
  39771. this._collider.radius = this.collisionRadius;
  39772. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39773. this._collisionTriggered = true;
  39774. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39775. }
  39776. else {
  39777. this.position.copyFrom(this._newPosition);
  39778. var up = this.upVector;
  39779. if (this.allowUpsideDown && sinb < 0) {
  39780. up = up.clone();
  39781. up = up.negate();
  39782. }
  39783. if (this.getScene().useRightHandedSystem) {
  39784. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39785. }
  39786. else {
  39787. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39788. }
  39789. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39790. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39791. }
  39792. this._currentTarget = target;
  39793. return this._viewMatrix;
  39794. };
  39795. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39796. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39797. meshes = meshes || this.getScene().meshes;
  39798. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39799. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39800. this.radius = distance * this.zoomOnFactor;
  39801. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39802. };
  39803. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39804. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39805. var meshesOrMinMaxVector;
  39806. var distance;
  39807. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39808. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39809. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39810. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39811. }
  39812. else {
  39813. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39814. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39815. distance = minMaxVectorAndDistance.distance;
  39816. }
  39817. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39818. if (!doNotUpdateMaxZ) {
  39819. this.maxZ = distance * 2;
  39820. }
  39821. };
  39822. /**
  39823. * @override
  39824. * Override Camera.createRigCamera
  39825. */
  39826. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39827. var alphaShift = 0;
  39828. switch (this.cameraRigMode) {
  39829. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39830. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39831. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39832. case BABYLON.Camera.RIG_MODE_VR:
  39833. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39834. break;
  39835. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39836. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39837. break;
  39838. }
  39839. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39840. rigCam._cameraRigParams = {};
  39841. return rigCam;
  39842. };
  39843. /**
  39844. * @override
  39845. * Override Camera._updateRigCameras
  39846. */
  39847. ArcRotateCamera.prototype._updateRigCameras = function () {
  39848. var camLeft = this._rigCameras[0];
  39849. var camRight = this._rigCameras[1];
  39850. camLeft.beta = camRight.beta = this.beta;
  39851. camLeft.radius = camRight.radius = this.radius;
  39852. switch (this.cameraRigMode) {
  39853. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39854. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39855. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39856. case BABYLON.Camera.RIG_MODE_VR:
  39857. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39858. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39859. break;
  39860. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39861. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39862. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39863. break;
  39864. }
  39865. _super.prototype._updateRigCameras.call(this);
  39866. };
  39867. ArcRotateCamera.prototype.dispose = function () {
  39868. this.inputs.clear();
  39869. _super.prototype.dispose.call(this);
  39870. };
  39871. ArcRotateCamera.prototype.getClassName = function () {
  39872. return "ArcRotateCamera";
  39873. };
  39874. __decorate([
  39875. BABYLON.serialize()
  39876. ], ArcRotateCamera.prototype, "alpha", void 0);
  39877. __decorate([
  39878. BABYLON.serialize()
  39879. ], ArcRotateCamera.prototype, "beta", void 0);
  39880. __decorate([
  39881. BABYLON.serialize()
  39882. ], ArcRotateCamera.prototype, "radius", void 0);
  39883. __decorate([
  39884. BABYLON.serializeAsVector3("target")
  39885. ], ArcRotateCamera.prototype, "_target", void 0);
  39886. __decorate([
  39887. BABYLON.serialize()
  39888. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39889. __decorate([
  39890. BABYLON.serialize()
  39891. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39892. __decorate([
  39893. BABYLON.serialize()
  39894. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39895. __decorate([
  39896. BABYLON.serialize()
  39897. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39898. __decorate([
  39899. BABYLON.serialize()
  39900. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39901. __decorate([
  39902. BABYLON.serialize()
  39903. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39904. __decorate([
  39905. BABYLON.serialize()
  39906. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39907. __decorate([
  39908. BABYLON.serialize()
  39909. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39910. __decorate([
  39911. BABYLON.serialize()
  39912. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39913. __decorate([
  39914. BABYLON.serialize()
  39915. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39916. __decorate([
  39917. BABYLON.serialize()
  39918. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39919. __decorate([
  39920. BABYLON.serialize()
  39921. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39922. __decorate([
  39923. BABYLON.serialize()
  39924. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39925. __decorate([
  39926. BABYLON.serializeAsVector3()
  39927. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39928. __decorate([
  39929. BABYLON.serialize()
  39930. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39931. __decorate([
  39932. BABYLON.serialize()
  39933. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39934. __decorate([
  39935. BABYLON.serialize()
  39936. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39937. return ArcRotateCamera;
  39938. }(BABYLON.TargetCamera));
  39939. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39940. })(BABYLON || (BABYLON = {}));
  39941. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39942. var BABYLON;
  39943. (function (BABYLON) {
  39944. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39945. __extends(ArcRotateCameraInputsManager, _super);
  39946. function ArcRotateCameraInputsManager(camera) {
  39947. return _super.call(this, camera) || this;
  39948. }
  39949. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39950. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39951. return this;
  39952. };
  39953. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39954. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39955. return this;
  39956. };
  39957. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39958. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39959. return this;
  39960. };
  39961. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39962. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39963. return this;
  39964. };
  39965. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39966. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39967. return this;
  39968. };
  39969. return ArcRotateCameraInputsManager;
  39970. }(BABYLON.CameraInputsManager));
  39971. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39972. })(BABYLON || (BABYLON = {}));
  39973. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39974. var BABYLON;
  39975. (function (BABYLON) {
  39976. var HemisphericLight = /** @class */ (function (_super) {
  39977. __extends(HemisphericLight, _super);
  39978. /**
  39979. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39980. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39981. * The HemisphericLight can't cast shadows.
  39982. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39983. */
  39984. function HemisphericLight(name, direction, scene) {
  39985. var _this = _super.call(this, name, scene) || this;
  39986. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39987. _this.direction = direction || BABYLON.Vector3.Up();
  39988. return _this;
  39989. }
  39990. HemisphericLight.prototype._buildUniformLayout = function () {
  39991. this._uniformBuffer.addUniform("vLightData", 4);
  39992. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39993. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39994. this._uniformBuffer.addUniform("vLightGround", 3);
  39995. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39996. this._uniformBuffer.addUniform("depthValues", 2);
  39997. this._uniformBuffer.create();
  39998. };
  39999. /**
  40000. * Returns the string "HemisphericLight".
  40001. */
  40002. HemisphericLight.prototype.getClassName = function () {
  40003. return "HemisphericLight";
  40004. };
  40005. /**
  40006. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40007. * Returns the updated direction.
  40008. */
  40009. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40010. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40011. return this.direction;
  40012. };
  40013. HemisphericLight.prototype.getShadowGenerator = function () {
  40014. return null;
  40015. };
  40016. /**
  40017. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40018. * Returns the HemisphericLight.
  40019. */
  40020. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40021. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40022. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40023. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40024. return this;
  40025. };
  40026. HemisphericLight.prototype._getWorldMatrix = function () {
  40027. if (!this._worldMatrix) {
  40028. this._worldMatrix = BABYLON.Matrix.Identity();
  40029. }
  40030. return this._worldMatrix;
  40031. };
  40032. /**
  40033. * Returns the integer 3.
  40034. */
  40035. HemisphericLight.prototype.getTypeID = function () {
  40036. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40037. };
  40038. __decorate([
  40039. BABYLON.serializeAsColor3()
  40040. ], HemisphericLight.prototype, "groundColor", void 0);
  40041. __decorate([
  40042. BABYLON.serializeAsVector3()
  40043. ], HemisphericLight.prototype, "direction", void 0);
  40044. return HemisphericLight;
  40045. }(BABYLON.Light));
  40046. BABYLON.HemisphericLight = HemisphericLight;
  40047. })(BABYLON || (BABYLON = {}));
  40048. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40049. var BABYLON;
  40050. (function (BABYLON) {
  40051. var ShadowLight = /** @class */ (function (_super) {
  40052. __extends(ShadowLight, _super);
  40053. function ShadowLight() {
  40054. var _this = _super !== null && _super.apply(this, arguments) || this;
  40055. _this._needProjectionMatrixCompute = true;
  40056. return _this;
  40057. }
  40058. Object.defineProperty(ShadowLight.prototype, "direction", {
  40059. get: function () {
  40060. return this._direction;
  40061. },
  40062. set: function (value) {
  40063. this._direction = value;
  40064. },
  40065. enumerable: true,
  40066. configurable: true
  40067. });
  40068. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40069. get: function () {
  40070. return this._shadowMinZ;
  40071. },
  40072. set: function (value) {
  40073. this._shadowMinZ = value;
  40074. this.forceProjectionMatrixCompute();
  40075. },
  40076. enumerable: true,
  40077. configurable: true
  40078. });
  40079. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40080. get: function () {
  40081. return this._shadowMaxZ;
  40082. },
  40083. set: function (value) {
  40084. this._shadowMaxZ = value;
  40085. this.forceProjectionMatrixCompute();
  40086. },
  40087. enumerable: true,
  40088. configurable: true
  40089. });
  40090. /**
  40091. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40092. */
  40093. ShadowLight.prototype.computeTransformedInformation = function () {
  40094. if (this.parent && this.parent.getWorldMatrix) {
  40095. if (!this.transformedPosition) {
  40096. this.transformedPosition = BABYLON.Vector3.Zero();
  40097. }
  40098. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40099. // In case the direction is present.
  40100. if (this.direction) {
  40101. if (!this.transformedDirection) {
  40102. this.transformedDirection = BABYLON.Vector3.Zero();
  40103. }
  40104. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40105. }
  40106. return true;
  40107. }
  40108. return false;
  40109. };
  40110. /**
  40111. * Return the depth scale used for the shadow map.
  40112. */
  40113. ShadowLight.prototype.getDepthScale = function () {
  40114. return 50.0;
  40115. };
  40116. /**
  40117. * Returns the light direction (Vector3) for any passed face index.
  40118. */
  40119. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40120. return this.transformedDirection ? this.transformedDirection : this.direction;
  40121. };
  40122. /**
  40123. * Returns the DirectionalLight absolute position in the World.
  40124. */
  40125. ShadowLight.prototype.getAbsolutePosition = function () {
  40126. return this.transformedPosition ? this.transformedPosition : this.position;
  40127. };
  40128. /**
  40129. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40130. * Returns the updated DirectionalLight direction (Vector3).
  40131. */
  40132. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40133. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40134. return this.direction;
  40135. };
  40136. /**
  40137. * Returns the light rotation (Vector3).
  40138. */
  40139. ShadowLight.prototype.getRotation = function () {
  40140. this.direction.normalize();
  40141. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40142. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40143. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40144. };
  40145. /**
  40146. * Boolean : false by default.
  40147. */
  40148. ShadowLight.prototype.needCube = function () {
  40149. return false;
  40150. };
  40151. /**
  40152. * Specifies wether or not the projection matrix should be recomputed this frame.
  40153. */
  40154. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40155. return this._needProjectionMatrixCompute;
  40156. };
  40157. /**
  40158. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40159. */
  40160. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40161. this._needProjectionMatrixCompute = true;
  40162. };
  40163. /**
  40164. * Get the world matrix of the sahdow lights.
  40165. */
  40166. ShadowLight.prototype._getWorldMatrix = function () {
  40167. if (!this._worldMatrix) {
  40168. this._worldMatrix = BABYLON.Matrix.Identity();
  40169. }
  40170. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40171. return this._worldMatrix;
  40172. };
  40173. /**
  40174. * Gets the minZ used for shadow according to both the scene and the light.
  40175. * @param activeCamera
  40176. */
  40177. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40178. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40179. };
  40180. /**
  40181. * Gets the maxZ used for shadow according to both the scene and the light.
  40182. * @param activeCamera
  40183. */
  40184. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40185. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40186. };
  40187. /**
  40188. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40189. * Returns the light.
  40190. */
  40191. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40192. if (this.customProjectionMatrixBuilder) {
  40193. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40194. }
  40195. else {
  40196. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40197. }
  40198. return this;
  40199. };
  40200. __decorate([
  40201. BABYLON.serializeAsVector3()
  40202. ], ShadowLight.prototype, "position", void 0);
  40203. __decorate([
  40204. BABYLON.serializeAsVector3()
  40205. ], ShadowLight.prototype, "direction", null);
  40206. __decorate([
  40207. BABYLON.serialize()
  40208. ], ShadowLight.prototype, "shadowMinZ", null);
  40209. __decorate([
  40210. BABYLON.serialize()
  40211. ], ShadowLight.prototype, "shadowMaxZ", null);
  40212. return ShadowLight;
  40213. }(BABYLON.Light));
  40214. BABYLON.ShadowLight = ShadowLight;
  40215. })(BABYLON || (BABYLON = {}));
  40216. //# sourceMappingURL=babylon.shadowLight.js.map
  40217. var BABYLON;
  40218. (function (BABYLON) {
  40219. var PointLight = /** @class */ (function (_super) {
  40220. __extends(PointLight, _super);
  40221. /**
  40222. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40223. * A PointLight emits the light in every direction.
  40224. * It can cast shadows.
  40225. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40226. * ```javascript
  40227. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40228. * ```
  40229. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40230. */
  40231. function PointLight(name, position, scene) {
  40232. var _this = _super.call(this, name, scene) || this;
  40233. _this._shadowAngle = Math.PI / 2;
  40234. _this.position = position;
  40235. return _this;
  40236. }
  40237. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40238. /**
  40239. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40240. * This specifies what angle the shadow will use to be created.
  40241. *
  40242. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40243. */
  40244. get: function () {
  40245. return this._shadowAngle;
  40246. },
  40247. /**
  40248. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40249. * This specifies what angle the shadow will use to be created.
  40250. *
  40251. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40252. */
  40253. set: function (value) {
  40254. this._shadowAngle = value;
  40255. this.forceProjectionMatrixCompute();
  40256. },
  40257. enumerable: true,
  40258. configurable: true
  40259. });
  40260. Object.defineProperty(PointLight.prototype, "direction", {
  40261. get: function () {
  40262. return this._direction;
  40263. },
  40264. /**
  40265. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40266. */
  40267. set: function (value) {
  40268. var previousNeedCube = this.needCube();
  40269. this._direction = value;
  40270. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40271. this._shadowGenerator.recreateShadowMap();
  40272. }
  40273. },
  40274. enumerable: true,
  40275. configurable: true
  40276. });
  40277. /**
  40278. * Returns the string "PointLight"
  40279. */
  40280. PointLight.prototype.getClassName = function () {
  40281. return "PointLight";
  40282. };
  40283. /**
  40284. * Returns the integer 0.
  40285. */
  40286. PointLight.prototype.getTypeID = function () {
  40287. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40288. };
  40289. /**
  40290. * Specifies wether or not the shadowmap should be a cube texture.
  40291. */
  40292. PointLight.prototype.needCube = function () {
  40293. return !this.direction;
  40294. };
  40295. /**
  40296. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40297. */
  40298. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40299. if (this.direction) {
  40300. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40301. }
  40302. else {
  40303. switch (faceIndex) {
  40304. case 0:
  40305. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40306. case 1:
  40307. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40308. case 2:
  40309. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40310. case 3:
  40311. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40312. case 4:
  40313. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40314. case 5:
  40315. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40316. }
  40317. }
  40318. return BABYLON.Vector3.Zero();
  40319. };
  40320. /**
  40321. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40322. * - fov = PI / 2
  40323. * - aspect ratio : 1.0
  40324. * - z-near and far equal to the active camera minZ and maxZ.
  40325. * Returns the PointLight.
  40326. */
  40327. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40328. var activeCamera = this.getScene().activeCamera;
  40329. if (!activeCamera) {
  40330. return;
  40331. }
  40332. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40333. };
  40334. PointLight.prototype._buildUniformLayout = function () {
  40335. this._uniformBuffer.addUniform("vLightData", 4);
  40336. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40337. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40338. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40339. this._uniformBuffer.addUniform("depthValues", 2);
  40340. this._uniformBuffer.create();
  40341. };
  40342. /**
  40343. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40344. * Returns the PointLight.
  40345. */
  40346. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40347. if (this.computeTransformedInformation()) {
  40348. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40349. return this;
  40350. }
  40351. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40352. return this;
  40353. };
  40354. __decorate([
  40355. BABYLON.serialize()
  40356. ], PointLight.prototype, "shadowAngle", null);
  40357. return PointLight;
  40358. }(BABYLON.ShadowLight));
  40359. BABYLON.PointLight = PointLight;
  40360. })(BABYLON || (BABYLON = {}));
  40361. //# sourceMappingURL=babylon.pointLight.js.map
  40362. var BABYLON;
  40363. (function (BABYLON) {
  40364. var DirectionalLight = /** @class */ (function (_super) {
  40365. __extends(DirectionalLight, _super);
  40366. /**
  40367. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40368. * The directional light is emitted from everywhere in the given direction.
  40369. * It can cast shawdows.
  40370. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40371. */
  40372. function DirectionalLight(name, direction, scene) {
  40373. var _this = _super.call(this, name, scene) || this;
  40374. _this._shadowFrustumSize = 0;
  40375. _this._shadowOrthoScale = 0.5;
  40376. _this.autoUpdateExtends = true;
  40377. // Cache
  40378. _this._orthoLeft = Number.MAX_VALUE;
  40379. _this._orthoRight = Number.MIN_VALUE;
  40380. _this._orthoTop = Number.MIN_VALUE;
  40381. _this._orthoBottom = Number.MAX_VALUE;
  40382. _this.position = direction.scale(-1.0);
  40383. _this.direction = direction;
  40384. return _this;
  40385. }
  40386. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40387. /**
  40388. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40389. */
  40390. get: function () {
  40391. return this._shadowFrustumSize;
  40392. },
  40393. /**
  40394. * Specifies a fix frustum size for the shadow generation.
  40395. */
  40396. set: function (value) {
  40397. this._shadowFrustumSize = value;
  40398. this.forceProjectionMatrixCompute();
  40399. },
  40400. enumerable: true,
  40401. configurable: true
  40402. });
  40403. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40404. get: function () {
  40405. return this._shadowOrthoScale;
  40406. },
  40407. set: function (value) {
  40408. this._shadowOrthoScale = value;
  40409. this.forceProjectionMatrixCompute();
  40410. },
  40411. enumerable: true,
  40412. configurable: true
  40413. });
  40414. /**
  40415. * Returns the string "DirectionalLight".
  40416. */
  40417. DirectionalLight.prototype.getClassName = function () {
  40418. return "DirectionalLight";
  40419. };
  40420. /**
  40421. * Returns the integer 1.
  40422. */
  40423. DirectionalLight.prototype.getTypeID = function () {
  40424. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40425. };
  40426. /**
  40427. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40428. * Returns the DirectionalLight Shadow projection matrix.
  40429. */
  40430. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40431. if (this.shadowFrustumSize > 0) {
  40432. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40433. }
  40434. else {
  40435. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40436. }
  40437. };
  40438. /**
  40439. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40440. * Returns the DirectionalLight Shadow projection matrix.
  40441. */
  40442. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40443. var activeCamera = this.getScene().activeCamera;
  40444. if (!activeCamera) {
  40445. return;
  40446. }
  40447. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40448. };
  40449. /**
  40450. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40451. * Returns the DirectionalLight Shadow projection matrix.
  40452. */
  40453. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40454. var activeCamera = this.getScene().activeCamera;
  40455. if (!activeCamera) {
  40456. return;
  40457. }
  40458. // Check extends
  40459. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40460. var tempVector3 = BABYLON.Vector3.Zero();
  40461. this._orthoLeft = Number.MAX_VALUE;
  40462. this._orthoRight = Number.MIN_VALUE;
  40463. this._orthoTop = Number.MIN_VALUE;
  40464. this._orthoBottom = Number.MAX_VALUE;
  40465. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40466. var mesh = renderList[meshIndex];
  40467. if (!mesh) {
  40468. continue;
  40469. }
  40470. var boundingInfo = mesh.getBoundingInfo();
  40471. var boundingBox = boundingInfo.boundingBox;
  40472. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40473. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40474. if (tempVector3.x < this._orthoLeft)
  40475. this._orthoLeft = tempVector3.x;
  40476. if (tempVector3.y < this._orthoBottom)
  40477. this._orthoBottom = tempVector3.y;
  40478. if (tempVector3.x > this._orthoRight)
  40479. this._orthoRight = tempVector3.x;
  40480. if (tempVector3.y > this._orthoTop)
  40481. this._orthoTop = tempVector3.y;
  40482. }
  40483. }
  40484. }
  40485. var xOffset = this._orthoRight - this._orthoLeft;
  40486. var yOffset = this._orthoTop - this._orthoBottom;
  40487. 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);
  40488. };
  40489. DirectionalLight.prototype._buildUniformLayout = function () {
  40490. this._uniformBuffer.addUniform("vLightData", 4);
  40491. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40492. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40493. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40494. this._uniformBuffer.addUniform("depthValues", 2);
  40495. this._uniformBuffer.create();
  40496. };
  40497. /**
  40498. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40499. * Returns the DirectionalLight.
  40500. */
  40501. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40502. if (this.computeTransformedInformation()) {
  40503. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40504. return this;
  40505. }
  40506. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40507. return this;
  40508. };
  40509. /**
  40510. * Gets the minZ used for shadow according to both the scene and the light.
  40511. *
  40512. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40513. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40514. * @param activeCamera
  40515. */
  40516. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40517. return 1;
  40518. };
  40519. /**
  40520. * Gets the maxZ used for shadow according to both the scene and the light.
  40521. *
  40522. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40523. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40524. * @param activeCamera
  40525. */
  40526. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40527. return 1;
  40528. };
  40529. __decorate([
  40530. BABYLON.serialize()
  40531. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40532. __decorate([
  40533. BABYLON.serialize()
  40534. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40535. __decorate([
  40536. BABYLON.serialize()
  40537. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40538. return DirectionalLight;
  40539. }(BABYLON.ShadowLight));
  40540. BABYLON.DirectionalLight = DirectionalLight;
  40541. })(BABYLON || (BABYLON = {}));
  40542. //# sourceMappingURL=babylon.directionalLight.js.map
  40543. var BABYLON;
  40544. (function (BABYLON) {
  40545. var SpotLight = /** @class */ (function (_super) {
  40546. __extends(SpotLight, _super);
  40547. /**
  40548. * Creates a SpotLight object in the scene with the passed parameters :
  40549. * - `position` (Vector3) is the initial SpotLight position,
  40550. * - `direction` (Vector3) is the initial SpotLight direction,
  40551. * - `angle` (float, in radians) is the spot light cone angle,
  40552. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40553. * A spot light is a simply light oriented cone.
  40554. * It can cast shadows.
  40555. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40556. */
  40557. function SpotLight(name, position, direction, angle, exponent, scene) {
  40558. var _this = _super.call(this, name, scene) || this;
  40559. _this.position = position;
  40560. _this.direction = direction;
  40561. _this.angle = angle;
  40562. _this.exponent = exponent;
  40563. return _this;
  40564. }
  40565. Object.defineProperty(SpotLight.prototype, "angle", {
  40566. get: function () {
  40567. return this._angle;
  40568. },
  40569. set: function (value) {
  40570. this._angle = value;
  40571. this.forceProjectionMatrixCompute();
  40572. },
  40573. enumerable: true,
  40574. configurable: true
  40575. });
  40576. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40577. get: function () {
  40578. return this._shadowAngleScale;
  40579. },
  40580. /**
  40581. * Allows scaling the angle of the light for shadow generation only.
  40582. */
  40583. set: function (value) {
  40584. this._shadowAngleScale = value;
  40585. this.forceProjectionMatrixCompute();
  40586. },
  40587. enumerable: true,
  40588. configurable: true
  40589. });
  40590. /**
  40591. * Returns the string "SpotLight".
  40592. */
  40593. SpotLight.prototype.getClassName = function () {
  40594. return "SpotLight";
  40595. };
  40596. /**
  40597. * Returns the integer 2.
  40598. */
  40599. SpotLight.prototype.getTypeID = function () {
  40600. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40601. };
  40602. /**
  40603. * 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.
  40604. * Returns the SpotLight.
  40605. */
  40606. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40607. var activeCamera = this.getScene().activeCamera;
  40608. if (!activeCamera) {
  40609. return;
  40610. }
  40611. this._shadowAngleScale = this._shadowAngleScale || 1;
  40612. var angle = this._shadowAngleScale * this._angle;
  40613. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40614. };
  40615. SpotLight.prototype._buildUniformLayout = function () {
  40616. this._uniformBuffer.addUniform("vLightData", 4);
  40617. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40618. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40619. this._uniformBuffer.addUniform("vLightDirection", 3);
  40620. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40621. this._uniformBuffer.addUniform("depthValues", 2);
  40622. this._uniformBuffer.create();
  40623. };
  40624. /**
  40625. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40626. * Return the SpotLight.
  40627. */
  40628. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40629. var normalizeDirection;
  40630. if (this.computeTransformedInformation()) {
  40631. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40632. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40633. }
  40634. else {
  40635. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40636. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40637. }
  40638. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40639. return this;
  40640. };
  40641. __decorate([
  40642. BABYLON.serialize()
  40643. ], SpotLight.prototype, "angle", null);
  40644. __decorate([
  40645. BABYLON.serialize()
  40646. /**
  40647. * Allows scaling the angle of the light for shadow generation only.
  40648. */
  40649. ], SpotLight.prototype, "shadowAngleScale", null);
  40650. __decorate([
  40651. BABYLON.serialize()
  40652. ], SpotLight.prototype, "exponent", void 0);
  40653. return SpotLight;
  40654. }(BABYLON.ShadowLight));
  40655. BABYLON.SpotLight = SpotLight;
  40656. })(BABYLON || (BABYLON = {}));
  40657. //# sourceMappingURL=babylon.spotLight.js.map
  40658. var BABYLON;
  40659. (function (BABYLON) {
  40660. var AnimationRange = /** @class */ (function () {
  40661. function AnimationRange(name, from, to) {
  40662. this.name = name;
  40663. this.from = from;
  40664. this.to = to;
  40665. }
  40666. AnimationRange.prototype.clone = function () {
  40667. return new AnimationRange(this.name, this.from, this.to);
  40668. };
  40669. return AnimationRange;
  40670. }());
  40671. BABYLON.AnimationRange = AnimationRange;
  40672. /**
  40673. * Composed of a frame, and an action function
  40674. */
  40675. var AnimationEvent = /** @class */ (function () {
  40676. function AnimationEvent(frame, action, onlyOnce) {
  40677. this.frame = frame;
  40678. this.action = action;
  40679. this.onlyOnce = onlyOnce;
  40680. this.isDone = false;
  40681. }
  40682. return AnimationEvent;
  40683. }());
  40684. BABYLON.AnimationEvent = AnimationEvent;
  40685. var PathCursor = /** @class */ (function () {
  40686. function PathCursor(path) {
  40687. this.path = path;
  40688. this._onchange = new Array();
  40689. this.value = 0;
  40690. this.animations = new Array();
  40691. }
  40692. PathCursor.prototype.getPoint = function () {
  40693. var point = this.path.getPointAtLengthPosition(this.value);
  40694. return new BABYLON.Vector3(point.x, 0, point.y);
  40695. };
  40696. PathCursor.prototype.moveAhead = function (step) {
  40697. if (step === void 0) { step = 0.002; }
  40698. this.move(step);
  40699. return this;
  40700. };
  40701. PathCursor.prototype.moveBack = function (step) {
  40702. if (step === void 0) { step = 0.002; }
  40703. this.move(-step);
  40704. return this;
  40705. };
  40706. PathCursor.prototype.move = function (step) {
  40707. if (Math.abs(step) > 1) {
  40708. throw "step size should be less than 1.";
  40709. }
  40710. this.value += step;
  40711. this.ensureLimits();
  40712. this.raiseOnChange();
  40713. return this;
  40714. };
  40715. PathCursor.prototype.ensureLimits = function () {
  40716. while (this.value > 1) {
  40717. this.value -= 1;
  40718. }
  40719. while (this.value < 0) {
  40720. this.value += 1;
  40721. }
  40722. return this;
  40723. };
  40724. // used by animation engine
  40725. PathCursor.prototype.raiseOnChange = function () {
  40726. var _this = this;
  40727. this._onchange.forEach(function (f) { return f(_this); });
  40728. return this;
  40729. };
  40730. PathCursor.prototype.onchange = function (f) {
  40731. this._onchange.push(f);
  40732. return this;
  40733. };
  40734. return PathCursor;
  40735. }());
  40736. BABYLON.PathCursor = PathCursor;
  40737. var Animation = /** @class */ (function () {
  40738. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40739. this.name = name;
  40740. this.targetProperty = targetProperty;
  40741. this.framePerSecond = framePerSecond;
  40742. this.dataType = dataType;
  40743. this.loopMode = loopMode;
  40744. this.enableBlending = enableBlending;
  40745. this._runtimeAnimations = new Array();
  40746. // The set of event that will be linked to this animation
  40747. this._events = new Array();
  40748. this.blendingSpeed = 0.01;
  40749. this._ranges = {};
  40750. this.targetPropertyPath = targetProperty.split(".");
  40751. this.dataType = dataType;
  40752. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40753. }
  40754. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40755. var dataType = undefined;
  40756. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40757. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40758. }
  40759. else if (from instanceof BABYLON.Quaternion) {
  40760. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40761. }
  40762. else if (from instanceof BABYLON.Vector3) {
  40763. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40764. }
  40765. else if (from instanceof BABYLON.Vector2) {
  40766. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40767. }
  40768. else if (from instanceof BABYLON.Color3) {
  40769. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40770. }
  40771. else if (from instanceof BABYLON.Size) {
  40772. dataType = Animation.ANIMATIONTYPE_SIZE;
  40773. }
  40774. if (dataType == undefined) {
  40775. return null;
  40776. }
  40777. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40778. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40779. animation.setKeys(keys);
  40780. if (easingFunction !== undefined) {
  40781. animation.setEasingFunction(easingFunction);
  40782. }
  40783. return animation;
  40784. };
  40785. /**
  40786. * Sets up an animation.
  40787. * @param property the property to animate
  40788. * @param animationType the animation type to apply
  40789. * @param easingFunction the easing function used in the animation
  40790. * @returns The created animation
  40791. */
  40792. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40793. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40794. animation.setEasingFunction(easingFunction);
  40795. return animation;
  40796. };
  40797. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40798. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40799. if (!animation) {
  40800. return null;
  40801. }
  40802. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40803. };
  40804. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40805. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40806. if (!animation) {
  40807. return null;
  40808. }
  40809. node.animations.push(animation);
  40810. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40811. };
  40812. /**
  40813. * Transition property of the Camera to the target Value.
  40814. * @param property The property to transition
  40815. * @param targetValue The target Value of the property
  40816. * @param host The object where the property to animate belongs
  40817. * @param scene Scene used to run the animation
  40818. * @param frameRate Framerate (in frame/s) to use
  40819. * @param transition The transition type we want to use
  40820. * @param duration The duration of the animation, in milliseconds
  40821. * @param onAnimationEnd Call back trigger at the end of the animation.
  40822. */
  40823. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40824. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40825. if (duration <= 0) {
  40826. host[property] = targetValue;
  40827. if (onAnimationEnd) {
  40828. onAnimationEnd();
  40829. }
  40830. return null;
  40831. }
  40832. var endFrame = frameRate * (duration / 1000);
  40833. transition.setKeys([{
  40834. frame: 0,
  40835. value: host[property].clone ? host[property].clone() : host[property]
  40836. },
  40837. {
  40838. frame: endFrame,
  40839. value: targetValue
  40840. }]);
  40841. if (!host.animations) {
  40842. host.animations = [];
  40843. }
  40844. host.animations.push(transition);
  40845. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40846. animation.onAnimationEnd = onAnimationEnd;
  40847. return animation;
  40848. };
  40849. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40850. /**
  40851. * Return the array of runtime animations currently using this animation
  40852. */
  40853. get: function () {
  40854. return this._runtimeAnimations;
  40855. },
  40856. enumerable: true,
  40857. configurable: true
  40858. });
  40859. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40860. get: function () {
  40861. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40862. var runtimeAnimation = _a[_i];
  40863. if (!runtimeAnimation.isStopped) {
  40864. return true;
  40865. }
  40866. }
  40867. return false;
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. // Methods
  40873. /**
  40874. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40875. */
  40876. Animation.prototype.toString = function (fullDetails) {
  40877. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40878. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40879. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40880. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40881. if (fullDetails) {
  40882. ret += ", Ranges: {";
  40883. var first = true;
  40884. for (var name in this._ranges) {
  40885. if (first) {
  40886. ret += ", ";
  40887. first = false;
  40888. }
  40889. ret += name;
  40890. }
  40891. ret += "}";
  40892. }
  40893. return ret;
  40894. };
  40895. /**
  40896. * Add an event to this animation.
  40897. */
  40898. Animation.prototype.addEvent = function (event) {
  40899. this._events.push(event);
  40900. };
  40901. /**
  40902. * Remove all events found at the given frame
  40903. * @param frame
  40904. */
  40905. Animation.prototype.removeEvents = function (frame) {
  40906. for (var index = 0; index < this._events.length; index++) {
  40907. if (this._events[index].frame === frame) {
  40908. this._events.splice(index, 1);
  40909. index--;
  40910. }
  40911. }
  40912. };
  40913. Animation.prototype.getEvents = function () {
  40914. return this._events;
  40915. };
  40916. Animation.prototype.createRange = function (name, from, to) {
  40917. // check name not already in use; could happen for bones after serialized
  40918. if (!this._ranges[name]) {
  40919. this._ranges[name] = new AnimationRange(name, from, to);
  40920. }
  40921. };
  40922. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40923. if (deleteFrames === void 0) { deleteFrames = true; }
  40924. var range = this._ranges[name];
  40925. if (!range) {
  40926. return;
  40927. }
  40928. if (deleteFrames) {
  40929. var from = range.from;
  40930. var to = range.to;
  40931. // this loop MUST go high to low for multiple splices to work
  40932. for (var key = this._keys.length - 1; key >= 0; key--) {
  40933. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40934. this._keys.splice(key, 1);
  40935. }
  40936. }
  40937. }
  40938. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40939. };
  40940. Animation.prototype.getRange = function (name) {
  40941. return this._ranges[name];
  40942. };
  40943. Animation.prototype.getKeys = function () {
  40944. return this._keys;
  40945. };
  40946. Animation.prototype.getHighestFrame = function () {
  40947. var ret = 0;
  40948. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40949. if (ret < this._keys[key].frame) {
  40950. ret = this._keys[key].frame;
  40951. }
  40952. }
  40953. return ret;
  40954. };
  40955. Animation.prototype.getEasingFunction = function () {
  40956. return this._easingFunction;
  40957. };
  40958. Animation.prototype.setEasingFunction = function (easingFunction) {
  40959. this._easingFunction = easingFunction;
  40960. };
  40961. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40962. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40963. };
  40964. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40965. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40966. };
  40967. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40968. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40969. };
  40970. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40971. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40972. };
  40973. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40974. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40975. };
  40976. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40977. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40978. };
  40979. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40980. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40981. };
  40982. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40983. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40984. };
  40985. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40986. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40987. };
  40988. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40989. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40990. };
  40991. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40992. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40993. };
  40994. Animation.prototype.clone = function () {
  40995. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40996. clone.enableBlending = this.enableBlending;
  40997. clone.blendingSpeed = this.blendingSpeed;
  40998. if (this._keys) {
  40999. clone.setKeys(this._keys);
  41000. }
  41001. if (this._ranges) {
  41002. clone._ranges = {};
  41003. for (var name in this._ranges) {
  41004. var range = this._ranges[name];
  41005. if (!range) {
  41006. continue;
  41007. }
  41008. clone._ranges[name] = range.clone();
  41009. }
  41010. }
  41011. return clone;
  41012. };
  41013. Animation.prototype.setKeys = function (values) {
  41014. this._keys = values.slice(0);
  41015. };
  41016. Animation.prototype.serialize = function () {
  41017. var serializationObject = {};
  41018. serializationObject.name = this.name;
  41019. serializationObject.property = this.targetProperty;
  41020. serializationObject.framePerSecond = this.framePerSecond;
  41021. serializationObject.dataType = this.dataType;
  41022. serializationObject.loopBehavior = this.loopMode;
  41023. serializationObject.enableBlending = this.enableBlending;
  41024. serializationObject.blendingSpeed = this.blendingSpeed;
  41025. var dataType = this.dataType;
  41026. serializationObject.keys = [];
  41027. var keys = this.getKeys();
  41028. for (var index = 0; index < keys.length; index++) {
  41029. var animationKey = keys[index];
  41030. var key = {};
  41031. key.frame = animationKey.frame;
  41032. switch (dataType) {
  41033. case Animation.ANIMATIONTYPE_FLOAT:
  41034. key.values = [animationKey.value];
  41035. break;
  41036. case Animation.ANIMATIONTYPE_QUATERNION:
  41037. case Animation.ANIMATIONTYPE_MATRIX:
  41038. case Animation.ANIMATIONTYPE_VECTOR3:
  41039. case Animation.ANIMATIONTYPE_COLOR3:
  41040. key.values = animationKey.value.asArray();
  41041. break;
  41042. }
  41043. serializationObject.keys.push(key);
  41044. }
  41045. serializationObject.ranges = [];
  41046. for (var name in this._ranges) {
  41047. var source = this._ranges[name];
  41048. if (!source) {
  41049. continue;
  41050. }
  41051. var range = {};
  41052. range.name = name;
  41053. range.from = source.from;
  41054. range.to = source.to;
  41055. serializationObject.ranges.push(range);
  41056. }
  41057. return serializationObject;
  41058. };
  41059. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41060. get: function () {
  41061. return Animation._ANIMATIONTYPE_FLOAT;
  41062. },
  41063. enumerable: true,
  41064. configurable: true
  41065. });
  41066. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41067. get: function () {
  41068. return Animation._ANIMATIONTYPE_VECTOR3;
  41069. },
  41070. enumerable: true,
  41071. configurable: true
  41072. });
  41073. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41074. get: function () {
  41075. return Animation._ANIMATIONTYPE_VECTOR2;
  41076. },
  41077. enumerable: true,
  41078. configurable: true
  41079. });
  41080. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41081. get: function () {
  41082. return Animation._ANIMATIONTYPE_SIZE;
  41083. },
  41084. enumerable: true,
  41085. configurable: true
  41086. });
  41087. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41088. get: function () {
  41089. return Animation._ANIMATIONTYPE_QUATERNION;
  41090. },
  41091. enumerable: true,
  41092. configurable: true
  41093. });
  41094. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41095. get: function () {
  41096. return Animation._ANIMATIONTYPE_MATRIX;
  41097. },
  41098. enumerable: true,
  41099. configurable: true
  41100. });
  41101. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41102. get: function () {
  41103. return Animation._ANIMATIONTYPE_COLOR3;
  41104. },
  41105. enumerable: true,
  41106. configurable: true
  41107. });
  41108. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41109. get: function () {
  41110. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41111. },
  41112. enumerable: true,
  41113. configurable: true
  41114. });
  41115. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41116. get: function () {
  41117. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41123. get: function () {
  41124. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41125. },
  41126. enumerable: true,
  41127. configurable: true
  41128. });
  41129. Animation.Parse = function (parsedAnimation) {
  41130. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41131. var dataType = parsedAnimation.dataType;
  41132. var keys = [];
  41133. var data;
  41134. var index;
  41135. if (parsedAnimation.enableBlending) {
  41136. animation.enableBlending = parsedAnimation.enableBlending;
  41137. }
  41138. if (parsedAnimation.blendingSpeed) {
  41139. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41140. }
  41141. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41142. var key = parsedAnimation.keys[index];
  41143. var inTangent;
  41144. var outTangent;
  41145. switch (dataType) {
  41146. case Animation.ANIMATIONTYPE_FLOAT:
  41147. data = key.values[0];
  41148. if (key.values.length >= 1) {
  41149. inTangent = key.values[1];
  41150. }
  41151. if (key.values.length >= 2) {
  41152. outTangent = key.values[2];
  41153. }
  41154. break;
  41155. case Animation.ANIMATIONTYPE_QUATERNION:
  41156. data = BABYLON.Quaternion.FromArray(key.values);
  41157. if (key.values.length >= 8) {
  41158. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41159. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41160. inTangent = _inTangent;
  41161. }
  41162. }
  41163. if (key.values.length >= 12) {
  41164. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41165. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41166. outTangent = _outTangent;
  41167. }
  41168. }
  41169. break;
  41170. case Animation.ANIMATIONTYPE_MATRIX:
  41171. data = BABYLON.Matrix.FromArray(key.values);
  41172. break;
  41173. case Animation.ANIMATIONTYPE_COLOR3:
  41174. data = BABYLON.Color3.FromArray(key.values);
  41175. break;
  41176. case Animation.ANIMATIONTYPE_VECTOR3:
  41177. default:
  41178. data = BABYLON.Vector3.FromArray(key.values);
  41179. break;
  41180. }
  41181. var keyData = {};
  41182. keyData.frame = key.frame;
  41183. keyData.value = data;
  41184. if (inTangent != undefined) {
  41185. keyData.inTangent = inTangent;
  41186. }
  41187. if (outTangent != undefined) {
  41188. keyData.outTangent = outTangent;
  41189. }
  41190. keys.push(keyData);
  41191. }
  41192. animation.setKeys(keys);
  41193. if (parsedAnimation.ranges) {
  41194. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41195. data = parsedAnimation.ranges[index];
  41196. animation.createRange(data.name, data.from, data.to);
  41197. }
  41198. }
  41199. return animation;
  41200. };
  41201. Animation.AppendSerializedAnimations = function (source, destination) {
  41202. if (source.animations) {
  41203. destination.animations = [];
  41204. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41205. var animation = source.animations[animationIndex];
  41206. destination.animations.push(animation.serialize());
  41207. }
  41208. }
  41209. };
  41210. Animation.AllowMatricesInterpolation = false;
  41211. // Statics
  41212. Animation._ANIMATIONTYPE_FLOAT = 0;
  41213. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41214. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41215. Animation._ANIMATIONTYPE_MATRIX = 3;
  41216. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41217. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41218. Animation._ANIMATIONTYPE_SIZE = 6;
  41219. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41220. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41221. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41222. return Animation;
  41223. }());
  41224. BABYLON.Animation = Animation;
  41225. })(BABYLON || (BABYLON = {}));
  41226. //# sourceMappingURL=babylon.animation.js.map
  41227. var BABYLON;
  41228. (function (BABYLON) {
  41229. var RuntimeAnimation = /** @class */ (function () {
  41230. function RuntimeAnimation(target, animation) {
  41231. this._offsetsCache = {};
  41232. this._highLimitsCache = {};
  41233. this._stopped = false;
  41234. this._blendingFactor = 0;
  41235. this._ratioOffset = 0;
  41236. this._animation = animation;
  41237. this._target = target;
  41238. animation._runtimeAnimations.push(this);
  41239. }
  41240. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41241. get: function () {
  41242. return this._animation;
  41243. },
  41244. enumerable: true,
  41245. configurable: true
  41246. });
  41247. RuntimeAnimation.prototype.reset = function () {
  41248. this._offsetsCache = {};
  41249. this._highLimitsCache = {};
  41250. this.currentFrame = 0;
  41251. this._blendingFactor = 0;
  41252. this._originalBlendValue = null;
  41253. };
  41254. RuntimeAnimation.prototype.isStopped = function () {
  41255. return this._stopped;
  41256. };
  41257. RuntimeAnimation.prototype.dispose = function () {
  41258. var index = this._animation.runtimeAnimations.indexOf(this);
  41259. if (index > -1) {
  41260. this._animation.runtimeAnimations.splice(index, 1);
  41261. }
  41262. };
  41263. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41264. if (typeof value === "function") {
  41265. return value();
  41266. }
  41267. return value;
  41268. };
  41269. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41270. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41271. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41272. }
  41273. this.currentFrame = currentFrame;
  41274. var keys = this._animation.getKeys();
  41275. // Try to get a hash to find the right key
  41276. 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));
  41277. if (keys[startKeyIndex].frame >= currentFrame) {
  41278. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41279. startKeyIndex--;
  41280. }
  41281. }
  41282. for (var key = startKeyIndex; key < keys.length; key++) {
  41283. var endKey = keys[key + 1];
  41284. if (endKey.frame >= currentFrame) {
  41285. var startKey = keys[key];
  41286. var startValue = this._getKeyValue(startKey.value);
  41287. var endValue = this._getKeyValue(endKey.value);
  41288. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41289. var frameDelta = endKey.frame - startKey.frame;
  41290. // gradient : percent of currentFrame between the frame inf and the frame sup
  41291. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41292. // check for easingFunction and correction of gradient
  41293. var easingFunction = this._animation.getEasingFunction();
  41294. if (easingFunction != null) {
  41295. gradient = easingFunction.ease(gradient);
  41296. }
  41297. switch (this._animation.dataType) {
  41298. // Float
  41299. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41300. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41301. switch (loopMode) {
  41302. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41303. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41304. return floatValue;
  41305. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41306. return offsetValue * repeatCount + floatValue;
  41307. }
  41308. break;
  41309. // Quaternion
  41310. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41311. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41312. switch (loopMode) {
  41313. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41314. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41315. return quatValue;
  41316. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41317. return quatValue.add(offsetValue.scale(repeatCount));
  41318. }
  41319. return quatValue;
  41320. // Vector3
  41321. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41322. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41323. switch (loopMode) {
  41324. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41325. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41326. return vec3Value;
  41327. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41328. return vec3Value.add(offsetValue.scale(repeatCount));
  41329. }
  41330. // Vector2
  41331. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41332. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41333. switch (loopMode) {
  41334. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41335. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41336. return vec2Value;
  41337. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41338. return vec2Value.add(offsetValue.scale(repeatCount));
  41339. }
  41340. // Size
  41341. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41342. switch (loopMode) {
  41343. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41344. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41345. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41346. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41347. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41348. }
  41349. // Color3
  41350. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41351. switch (loopMode) {
  41352. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41353. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41354. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41355. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41356. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41357. }
  41358. // Matrix
  41359. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41360. switch (loopMode) {
  41361. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41362. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41363. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41364. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41365. }
  41366. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41367. return startValue;
  41368. }
  41369. default:
  41370. break;
  41371. }
  41372. break;
  41373. }
  41374. }
  41375. return this._getKeyValue(keys[keys.length - 1].value);
  41376. };
  41377. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41378. if (blend === void 0) { blend = false; }
  41379. // Set value
  41380. var path;
  41381. var destination;
  41382. var targetPropertyPath = this._animation.targetPropertyPath;
  41383. if (targetPropertyPath.length > 1) {
  41384. var property = this._target[targetPropertyPath[0]];
  41385. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41386. property = property[targetPropertyPath[index]];
  41387. }
  41388. path = targetPropertyPath[targetPropertyPath.length - 1];
  41389. destination = property;
  41390. }
  41391. else {
  41392. path = targetPropertyPath[0];
  41393. destination = this._target;
  41394. }
  41395. // Blending
  41396. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41397. if (!this._originalBlendValue) {
  41398. if (destination[path].clone) {
  41399. this._originalBlendValue = destination[path].clone();
  41400. }
  41401. else {
  41402. this._originalBlendValue = destination[path];
  41403. }
  41404. }
  41405. if (this._originalBlendValue.prototype) {
  41406. if (this._originalBlendValue.prototype.Lerp) {
  41407. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41408. }
  41409. else {
  41410. destination[path] = currentValue;
  41411. }
  41412. }
  41413. else if (this._originalBlendValue.m) {
  41414. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41415. }
  41416. else {
  41417. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41418. }
  41419. this._blendingFactor += this._animation.blendingSpeed;
  41420. }
  41421. else {
  41422. destination[path] = currentValue;
  41423. }
  41424. if (this._target.markAsDirty) {
  41425. this._target.markAsDirty(this._animation.targetProperty);
  41426. }
  41427. };
  41428. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41429. var keys = this._animation.getKeys();
  41430. if (frame < keys[0].frame) {
  41431. frame = keys[0].frame;
  41432. }
  41433. else if (frame > keys[keys.length - 1].frame) {
  41434. frame = keys[keys.length - 1].frame;
  41435. }
  41436. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41437. this.setValue(currentValue);
  41438. };
  41439. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41440. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41441. this._ratioOffset = this._previousRatio - newRatio;
  41442. };
  41443. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41444. if (blend === void 0) { blend = false; }
  41445. var targetPropertyPath = this._animation.targetPropertyPath;
  41446. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41447. this._stopped = true;
  41448. return false;
  41449. }
  41450. var returnValue = true;
  41451. var keys = this._animation.getKeys();
  41452. // Adding a start key at frame 0 if missing
  41453. if (keys[0].frame !== 0) {
  41454. var newKey = { frame: 0, value: keys[0].value };
  41455. keys.splice(0, 0, newKey);
  41456. }
  41457. // Check limits
  41458. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41459. from = keys[0].frame;
  41460. }
  41461. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41462. to = keys[keys.length - 1].frame;
  41463. }
  41464. //to and from cannot be the same key
  41465. if (from === to) {
  41466. if (from > keys[0].frame) {
  41467. from--;
  41468. }
  41469. else if (to < keys[keys.length - 1].frame) {
  41470. to++;
  41471. }
  41472. }
  41473. // Compute ratio
  41474. var range = to - from;
  41475. var offsetValue;
  41476. // ratio represents the frame delta between from and to
  41477. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41478. var highLimitValue = 0;
  41479. this._previousDelay = delay;
  41480. this._previousRatio = ratio;
  41481. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41482. returnValue = false;
  41483. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41484. }
  41485. else {
  41486. // Get max value if required
  41487. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41488. var keyOffset = to.toString() + from.toString();
  41489. if (!this._offsetsCache[keyOffset]) {
  41490. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41491. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41492. switch (this._animation.dataType) {
  41493. // Float
  41494. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41495. this._offsetsCache[keyOffset] = toValue - fromValue;
  41496. break;
  41497. // Quaternion
  41498. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41499. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41500. break;
  41501. // Vector3
  41502. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41503. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41504. // Vector2
  41505. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41506. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41507. // Size
  41508. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41509. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41510. // Color3
  41511. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41512. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41513. default:
  41514. break;
  41515. }
  41516. this._highLimitsCache[keyOffset] = toValue;
  41517. }
  41518. highLimitValue = this._highLimitsCache[keyOffset];
  41519. offsetValue = this._offsetsCache[keyOffset];
  41520. }
  41521. }
  41522. if (offsetValue === undefined) {
  41523. switch (this._animation.dataType) {
  41524. // Float
  41525. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41526. offsetValue = 0;
  41527. break;
  41528. // Quaternion
  41529. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41530. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41531. break;
  41532. // Vector3
  41533. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41534. offsetValue = BABYLON.Vector3.Zero();
  41535. break;
  41536. // Vector2
  41537. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41538. offsetValue = BABYLON.Vector2.Zero();
  41539. break;
  41540. // Size
  41541. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41542. offsetValue = BABYLON.Size.Zero();
  41543. break;
  41544. // Color3
  41545. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41546. offsetValue = BABYLON.Color3.Black();
  41547. }
  41548. }
  41549. // Compute value
  41550. var repeatCount = (ratio / range) >> 0;
  41551. var currentFrame = returnValue ? from + ratio % range : to;
  41552. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41553. // Set value
  41554. this.setValue(currentValue);
  41555. // Check events
  41556. var events = this._animation.getEvents();
  41557. for (var index = 0; index < events.length; index++) {
  41558. // Make sure current frame has passed event frame and that event frame is within the current range
  41559. // Also, handle both forward and reverse animations
  41560. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41561. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41562. var event = events[index];
  41563. if (!event.isDone) {
  41564. // If event should be done only once, remove it.
  41565. if (event.onlyOnce) {
  41566. events.splice(index, 1);
  41567. index--;
  41568. }
  41569. event.isDone = true;
  41570. event.action();
  41571. } // Don't do anything if the event has already be done.
  41572. }
  41573. else if (events[index].isDone && !events[index].onlyOnce) {
  41574. // reset event, the animation is looping
  41575. events[index].isDone = false;
  41576. }
  41577. }
  41578. if (!returnValue) {
  41579. this._stopped = true;
  41580. }
  41581. return returnValue;
  41582. };
  41583. return RuntimeAnimation;
  41584. }());
  41585. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41586. })(BABYLON || (BABYLON = {}));
  41587. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41588. var BABYLON;
  41589. (function (BABYLON) {
  41590. var Animatable = /** @class */ (function () {
  41591. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41592. if (fromFrame === void 0) { fromFrame = 0; }
  41593. if (toFrame === void 0) { toFrame = 100; }
  41594. if (loopAnimation === void 0) { loopAnimation = false; }
  41595. if (speedRatio === void 0) { speedRatio = 1.0; }
  41596. this.target = target;
  41597. this.fromFrame = fromFrame;
  41598. this.toFrame = toFrame;
  41599. this.loopAnimation = loopAnimation;
  41600. this.onAnimationEnd = onAnimationEnd;
  41601. this._localDelayOffset = null;
  41602. this._pausedDelay = null;
  41603. this._runtimeAnimations = new Array();
  41604. this._paused = false;
  41605. this._speedRatio = 1;
  41606. this.animationStarted = false;
  41607. if (animations) {
  41608. this.appendAnimations(target, animations);
  41609. }
  41610. this._speedRatio = speedRatio;
  41611. this._scene = scene;
  41612. scene._activeAnimatables.push(this);
  41613. }
  41614. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41615. get: function () {
  41616. return this._speedRatio;
  41617. },
  41618. set: function (value) {
  41619. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41620. var animation = this._runtimeAnimations[index];
  41621. animation._prepareForSpeedRatioChange(value);
  41622. }
  41623. this._speedRatio = value;
  41624. },
  41625. enumerable: true,
  41626. configurable: true
  41627. });
  41628. // Methods
  41629. Animatable.prototype.getAnimations = function () {
  41630. return this._runtimeAnimations;
  41631. };
  41632. Animatable.prototype.appendAnimations = function (target, animations) {
  41633. for (var index = 0; index < animations.length; index++) {
  41634. var animation = animations[index];
  41635. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41636. }
  41637. };
  41638. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41639. var runtimeAnimations = this._runtimeAnimations;
  41640. for (var index = 0; index < runtimeAnimations.length; index++) {
  41641. if (runtimeAnimations[index].animation.targetProperty === property) {
  41642. return runtimeAnimations[index].animation;
  41643. }
  41644. }
  41645. return null;
  41646. };
  41647. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41648. var runtimeAnimations = this._runtimeAnimations;
  41649. for (var index = 0; index < runtimeAnimations.length; index++) {
  41650. if (runtimeAnimations[index].animation.targetProperty === property) {
  41651. return runtimeAnimations[index];
  41652. }
  41653. }
  41654. return null;
  41655. };
  41656. Animatable.prototype.reset = function () {
  41657. var runtimeAnimations = this._runtimeAnimations;
  41658. for (var index = 0; index < runtimeAnimations.length; index++) {
  41659. runtimeAnimations[index].reset();
  41660. }
  41661. this._localDelayOffset = null;
  41662. this._pausedDelay = null;
  41663. };
  41664. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41665. var runtimeAnimations = this._runtimeAnimations;
  41666. for (var index = 0; index < runtimeAnimations.length; index++) {
  41667. runtimeAnimations[index].animation.enableBlending = true;
  41668. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41669. }
  41670. };
  41671. Animatable.prototype.disableBlending = function () {
  41672. var runtimeAnimations = this._runtimeAnimations;
  41673. for (var index = 0; index < runtimeAnimations.length; index++) {
  41674. runtimeAnimations[index].animation.enableBlending = false;
  41675. }
  41676. };
  41677. Animatable.prototype.goToFrame = function (frame) {
  41678. var runtimeAnimations = this._runtimeAnimations;
  41679. if (runtimeAnimations[0]) {
  41680. var fps = runtimeAnimations[0].animation.framePerSecond;
  41681. var currentFrame = runtimeAnimations[0].currentFrame;
  41682. var adjustTime = frame - currentFrame;
  41683. var delay = adjustTime * 1000 / fps;
  41684. if (this._localDelayOffset === null) {
  41685. this._localDelayOffset = 0;
  41686. }
  41687. this._localDelayOffset -= delay;
  41688. }
  41689. for (var index = 0; index < runtimeAnimations.length; index++) {
  41690. runtimeAnimations[index].goToFrame(frame);
  41691. }
  41692. };
  41693. Animatable.prototype.pause = function () {
  41694. if (this._paused) {
  41695. return;
  41696. }
  41697. this._paused = true;
  41698. };
  41699. Animatable.prototype.restart = function () {
  41700. this._paused = false;
  41701. };
  41702. Animatable.prototype.stop = function (animationName) {
  41703. if (animationName) {
  41704. var idx = this._scene._activeAnimatables.indexOf(this);
  41705. if (idx > -1) {
  41706. var runtimeAnimations = this._runtimeAnimations;
  41707. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41708. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41709. continue;
  41710. }
  41711. runtimeAnimations[index].dispose();
  41712. runtimeAnimations.splice(index, 1);
  41713. }
  41714. if (runtimeAnimations.length == 0) {
  41715. this._scene._activeAnimatables.splice(idx, 1);
  41716. if (this.onAnimationEnd) {
  41717. this.onAnimationEnd();
  41718. }
  41719. }
  41720. }
  41721. }
  41722. else {
  41723. var index = this._scene._activeAnimatables.indexOf(this);
  41724. if (index > -1) {
  41725. this._scene._activeAnimatables.splice(index, 1);
  41726. var runtimeAnimations = this._runtimeAnimations;
  41727. for (var index = 0; index < runtimeAnimations.length; index++) {
  41728. runtimeAnimations[index].dispose();
  41729. }
  41730. if (this.onAnimationEnd) {
  41731. this.onAnimationEnd();
  41732. }
  41733. }
  41734. }
  41735. };
  41736. Animatable.prototype._animate = function (delay) {
  41737. if (this._paused) {
  41738. this.animationStarted = false;
  41739. if (this._pausedDelay === null) {
  41740. this._pausedDelay = delay;
  41741. }
  41742. return true;
  41743. }
  41744. if (this._localDelayOffset === null) {
  41745. this._localDelayOffset = delay;
  41746. }
  41747. else if (this._pausedDelay !== null) {
  41748. this._localDelayOffset += delay - this._pausedDelay;
  41749. this._pausedDelay = null;
  41750. }
  41751. // Animating
  41752. var running = false;
  41753. var runtimeAnimations = this._runtimeAnimations;
  41754. var index;
  41755. for (index = 0; index < runtimeAnimations.length; index++) {
  41756. var animation = runtimeAnimations[index];
  41757. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41758. running = running || isRunning;
  41759. }
  41760. this.animationStarted = running;
  41761. if (!running) {
  41762. // Remove from active animatables
  41763. index = this._scene._activeAnimatables.indexOf(this);
  41764. this._scene._activeAnimatables.splice(index, 1);
  41765. // Dispose all runtime animations
  41766. for (index = 0; index < runtimeAnimations.length; index++) {
  41767. runtimeAnimations[index].dispose();
  41768. }
  41769. }
  41770. if (!running && this.onAnimationEnd) {
  41771. this.onAnimationEnd();
  41772. this.onAnimationEnd = null;
  41773. }
  41774. return running;
  41775. };
  41776. return Animatable;
  41777. }());
  41778. BABYLON.Animatable = Animatable;
  41779. })(BABYLON || (BABYLON = {}));
  41780. //# sourceMappingURL=babylon.animatable.js.map
  41781. var BABYLON;
  41782. (function (BABYLON) {
  41783. var EasingFunction = /** @class */ (function () {
  41784. function EasingFunction() {
  41785. // Properties
  41786. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41787. }
  41788. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41789. get: function () {
  41790. return EasingFunction._EASINGMODE_EASEIN;
  41791. },
  41792. enumerable: true,
  41793. configurable: true
  41794. });
  41795. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41796. get: function () {
  41797. return EasingFunction._EASINGMODE_EASEOUT;
  41798. },
  41799. enumerable: true,
  41800. configurable: true
  41801. });
  41802. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41803. get: function () {
  41804. return EasingFunction._EASINGMODE_EASEINOUT;
  41805. },
  41806. enumerable: true,
  41807. configurable: true
  41808. });
  41809. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41810. var n = Math.min(Math.max(easingMode, 0), 2);
  41811. this._easingMode = n;
  41812. };
  41813. EasingFunction.prototype.getEasingMode = function () {
  41814. return this._easingMode;
  41815. };
  41816. EasingFunction.prototype.easeInCore = function (gradient) {
  41817. throw new Error('You must implement this method');
  41818. };
  41819. EasingFunction.prototype.ease = function (gradient) {
  41820. switch (this._easingMode) {
  41821. case EasingFunction.EASINGMODE_EASEIN:
  41822. return this.easeInCore(gradient);
  41823. case EasingFunction.EASINGMODE_EASEOUT:
  41824. return (1 - this.easeInCore(1 - gradient));
  41825. }
  41826. if (gradient >= 0.5) {
  41827. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41828. }
  41829. return (this.easeInCore(gradient * 2) * 0.5);
  41830. };
  41831. //Statics
  41832. EasingFunction._EASINGMODE_EASEIN = 0;
  41833. EasingFunction._EASINGMODE_EASEOUT = 1;
  41834. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41835. return EasingFunction;
  41836. }());
  41837. BABYLON.EasingFunction = EasingFunction;
  41838. var CircleEase = /** @class */ (function (_super) {
  41839. __extends(CircleEase, _super);
  41840. function CircleEase() {
  41841. return _super !== null && _super.apply(this, arguments) || this;
  41842. }
  41843. CircleEase.prototype.easeInCore = function (gradient) {
  41844. gradient = Math.max(0, Math.min(1, gradient));
  41845. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41846. };
  41847. return CircleEase;
  41848. }(EasingFunction));
  41849. BABYLON.CircleEase = CircleEase;
  41850. var BackEase = /** @class */ (function (_super) {
  41851. __extends(BackEase, _super);
  41852. function BackEase(amplitude) {
  41853. if (amplitude === void 0) { amplitude = 1; }
  41854. var _this = _super.call(this) || this;
  41855. _this.amplitude = amplitude;
  41856. return _this;
  41857. }
  41858. BackEase.prototype.easeInCore = function (gradient) {
  41859. var num = Math.max(0, this.amplitude);
  41860. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41861. };
  41862. return BackEase;
  41863. }(EasingFunction));
  41864. BABYLON.BackEase = BackEase;
  41865. var BounceEase = /** @class */ (function (_super) {
  41866. __extends(BounceEase, _super);
  41867. function BounceEase(bounces, bounciness) {
  41868. if (bounces === void 0) { bounces = 3; }
  41869. if (bounciness === void 0) { bounciness = 2; }
  41870. var _this = _super.call(this) || this;
  41871. _this.bounces = bounces;
  41872. _this.bounciness = bounciness;
  41873. return _this;
  41874. }
  41875. BounceEase.prototype.easeInCore = function (gradient) {
  41876. var y = Math.max(0.0, this.bounces);
  41877. var bounciness = this.bounciness;
  41878. if (bounciness <= 1.0) {
  41879. bounciness = 1.001;
  41880. }
  41881. var num9 = Math.pow(bounciness, y);
  41882. var num5 = 1.0 - bounciness;
  41883. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41884. var num15 = gradient * num4;
  41885. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41886. var num3 = Math.floor(num65);
  41887. var num13 = num3 + 1.0;
  41888. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41889. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41890. var num7 = (num8 + num12) * 0.5;
  41891. var num6 = gradient - num7;
  41892. var num2 = num7 - num8;
  41893. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41894. };
  41895. return BounceEase;
  41896. }(EasingFunction));
  41897. BABYLON.BounceEase = BounceEase;
  41898. var CubicEase = /** @class */ (function (_super) {
  41899. __extends(CubicEase, _super);
  41900. function CubicEase() {
  41901. return _super !== null && _super.apply(this, arguments) || this;
  41902. }
  41903. CubicEase.prototype.easeInCore = function (gradient) {
  41904. return (gradient * gradient * gradient);
  41905. };
  41906. return CubicEase;
  41907. }(EasingFunction));
  41908. BABYLON.CubicEase = CubicEase;
  41909. var ElasticEase = /** @class */ (function (_super) {
  41910. __extends(ElasticEase, _super);
  41911. function ElasticEase(oscillations, springiness) {
  41912. if (oscillations === void 0) { oscillations = 3; }
  41913. if (springiness === void 0) { springiness = 3; }
  41914. var _this = _super.call(this) || this;
  41915. _this.oscillations = oscillations;
  41916. _this.springiness = springiness;
  41917. return _this;
  41918. }
  41919. ElasticEase.prototype.easeInCore = function (gradient) {
  41920. var num2;
  41921. var num3 = Math.max(0.0, this.oscillations);
  41922. var num = Math.max(0.0, this.springiness);
  41923. if (num == 0) {
  41924. num2 = gradient;
  41925. }
  41926. else {
  41927. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41928. }
  41929. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41930. };
  41931. return ElasticEase;
  41932. }(EasingFunction));
  41933. BABYLON.ElasticEase = ElasticEase;
  41934. var ExponentialEase = /** @class */ (function (_super) {
  41935. __extends(ExponentialEase, _super);
  41936. function ExponentialEase(exponent) {
  41937. if (exponent === void 0) { exponent = 2; }
  41938. var _this = _super.call(this) || this;
  41939. _this.exponent = exponent;
  41940. return _this;
  41941. }
  41942. ExponentialEase.prototype.easeInCore = function (gradient) {
  41943. if (this.exponent <= 0) {
  41944. return gradient;
  41945. }
  41946. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41947. };
  41948. return ExponentialEase;
  41949. }(EasingFunction));
  41950. BABYLON.ExponentialEase = ExponentialEase;
  41951. var PowerEase = /** @class */ (function (_super) {
  41952. __extends(PowerEase, _super);
  41953. function PowerEase(power) {
  41954. if (power === void 0) { power = 2; }
  41955. var _this = _super.call(this) || this;
  41956. _this.power = power;
  41957. return _this;
  41958. }
  41959. PowerEase.prototype.easeInCore = function (gradient) {
  41960. var y = Math.max(0.0, this.power);
  41961. return Math.pow(gradient, y);
  41962. };
  41963. return PowerEase;
  41964. }(EasingFunction));
  41965. BABYLON.PowerEase = PowerEase;
  41966. var QuadraticEase = /** @class */ (function (_super) {
  41967. __extends(QuadraticEase, _super);
  41968. function QuadraticEase() {
  41969. return _super !== null && _super.apply(this, arguments) || this;
  41970. }
  41971. QuadraticEase.prototype.easeInCore = function (gradient) {
  41972. return (gradient * gradient);
  41973. };
  41974. return QuadraticEase;
  41975. }(EasingFunction));
  41976. BABYLON.QuadraticEase = QuadraticEase;
  41977. var QuarticEase = /** @class */ (function (_super) {
  41978. __extends(QuarticEase, _super);
  41979. function QuarticEase() {
  41980. return _super !== null && _super.apply(this, arguments) || this;
  41981. }
  41982. QuarticEase.prototype.easeInCore = function (gradient) {
  41983. return (gradient * gradient * gradient * gradient);
  41984. };
  41985. return QuarticEase;
  41986. }(EasingFunction));
  41987. BABYLON.QuarticEase = QuarticEase;
  41988. var QuinticEase = /** @class */ (function (_super) {
  41989. __extends(QuinticEase, _super);
  41990. function QuinticEase() {
  41991. return _super !== null && _super.apply(this, arguments) || this;
  41992. }
  41993. QuinticEase.prototype.easeInCore = function (gradient) {
  41994. return (gradient * gradient * gradient * gradient * gradient);
  41995. };
  41996. return QuinticEase;
  41997. }(EasingFunction));
  41998. BABYLON.QuinticEase = QuinticEase;
  41999. var SineEase = /** @class */ (function (_super) {
  42000. __extends(SineEase, _super);
  42001. function SineEase() {
  42002. return _super !== null && _super.apply(this, arguments) || this;
  42003. }
  42004. SineEase.prototype.easeInCore = function (gradient) {
  42005. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42006. };
  42007. return SineEase;
  42008. }(EasingFunction));
  42009. BABYLON.SineEase = SineEase;
  42010. var BezierCurveEase = /** @class */ (function (_super) {
  42011. __extends(BezierCurveEase, _super);
  42012. function BezierCurveEase(x1, y1, x2, y2) {
  42013. if (x1 === void 0) { x1 = 0; }
  42014. if (y1 === void 0) { y1 = 0; }
  42015. if (x2 === void 0) { x2 = 1; }
  42016. if (y2 === void 0) { y2 = 1; }
  42017. var _this = _super.call(this) || this;
  42018. _this.x1 = x1;
  42019. _this.y1 = y1;
  42020. _this.x2 = x2;
  42021. _this.y2 = y2;
  42022. return _this;
  42023. }
  42024. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42025. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42026. };
  42027. return BezierCurveEase;
  42028. }(EasingFunction));
  42029. BABYLON.BezierCurveEase = BezierCurveEase;
  42030. })(BABYLON || (BABYLON = {}));
  42031. //# sourceMappingURL=babylon.easing.js.map
  42032. var BABYLON;
  42033. (function (BABYLON) {
  42034. var Condition = /** @class */ (function () {
  42035. function Condition(actionManager) {
  42036. this._actionManager = actionManager;
  42037. }
  42038. Condition.prototype.isValid = function () {
  42039. return true;
  42040. };
  42041. Condition.prototype._getProperty = function (propertyPath) {
  42042. return this._actionManager._getProperty(propertyPath);
  42043. };
  42044. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42045. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42046. };
  42047. Condition.prototype.serialize = function () {
  42048. };
  42049. Condition.prototype._serialize = function (serializedCondition) {
  42050. return {
  42051. type: 2,
  42052. children: [],
  42053. name: serializedCondition.name,
  42054. properties: serializedCondition.properties
  42055. };
  42056. };
  42057. return Condition;
  42058. }());
  42059. BABYLON.Condition = Condition;
  42060. var ValueCondition = /** @class */ (function (_super) {
  42061. __extends(ValueCondition, _super);
  42062. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42063. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42064. var _this = _super.call(this, actionManager) || this;
  42065. _this.propertyPath = propertyPath;
  42066. _this.value = value;
  42067. _this.operator = operator;
  42068. _this._target = target;
  42069. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42070. _this._property = _this._getProperty(_this.propertyPath);
  42071. return _this;
  42072. }
  42073. Object.defineProperty(ValueCondition, "IsEqual", {
  42074. get: function () {
  42075. return ValueCondition._IsEqual;
  42076. },
  42077. enumerable: true,
  42078. configurable: true
  42079. });
  42080. Object.defineProperty(ValueCondition, "IsDifferent", {
  42081. get: function () {
  42082. return ValueCondition._IsDifferent;
  42083. },
  42084. enumerable: true,
  42085. configurable: true
  42086. });
  42087. Object.defineProperty(ValueCondition, "IsGreater", {
  42088. get: function () {
  42089. return ValueCondition._IsGreater;
  42090. },
  42091. enumerable: true,
  42092. configurable: true
  42093. });
  42094. Object.defineProperty(ValueCondition, "IsLesser", {
  42095. get: function () {
  42096. return ValueCondition._IsLesser;
  42097. },
  42098. enumerable: true,
  42099. configurable: true
  42100. });
  42101. // Methods
  42102. ValueCondition.prototype.isValid = function () {
  42103. switch (this.operator) {
  42104. case ValueCondition.IsGreater:
  42105. return this._effectiveTarget[this._property] > this.value;
  42106. case ValueCondition.IsLesser:
  42107. return this._effectiveTarget[this._property] < this.value;
  42108. case ValueCondition.IsEqual:
  42109. case ValueCondition.IsDifferent:
  42110. var check;
  42111. if (this.value.equals) {
  42112. check = this.value.equals(this._effectiveTarget[this._property]);
  42113. }
  42114. else {
  42115. check = this.value === this._effectiveTarget[this._property];
  42116. }
  42117. return this.operator === ValueCondition.IsEqual ? check : !check;
  42118. }
  42119. return false;
  42120. };
  42121. ValueCondition.prototype.serialize = function () {
  42122. return this._serialize({
  42123. name: "ValueCondition",
  42124. properties: [
  42125. BABYLON.Action._GetTargetProperty(this._target),
  42126. { name: "propertyPath", value: this.propertyPath },
  42127. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42128. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42129. ]
  42130. });
  42131. };
  42132. ValueCondition.GetOperatorName = function (operator) {
  42133. switch (operator) {
  42134. case ValueCondition._IsEqual: return "IsEqual";
  42135. case ValueCondition._IsDifferent: return "IsDifferent";
  42136. case ValueCondition._IsGreater: return "IsGreater";
  42137. case ValueCondition._IsLesser: return "IsLesser";
  42138. default: return "";
  42139. }
  42140. };
  42141. // Statics
  42142. ValueCondition._IsEqual = 0;
  42143. ValueCondition._IsDifferent = 1;
  42144. ValueCondition._IsGreater = 2;
  42145. ValueCondition._IsLesser = 3;
  42146. return ValueCondition;
  42147. }(Condition));
  42148. BABYLON.ValueCondition = ValueCondition;
  42149. var PredicateCondition = /** @class */ (function (_super) {
  42150. __extends(PredicateCondition, _super);
  42151. function PredicateCondition(actionManager, predicate) {
  42152. var _this = _super.call(this, actionManager) || this;
  42153. _this.predicate = predicate;
  42154. return _this;
  42155. }
  42156. PredicateCondition.prototype.isValid = function () {
  42157. return this.predicate();
  42158. };
  42159. return PredicateCondition;
  42160. }(Condition));
  42161. BABYLON.PredicateCondition = PredicateCondition;
  42162. var StateCondition = /** @class */ (function (_super) {
  42163. __extends(StateCondition, _super);
  42164. function StateCondition(actionManager, target, value) {
  42165. var _this = _super.call(this, actionManager) || this;
  42166. _this.value = value;
  42167. _this._target = target;
  42168. return _this;
  42169. }
  42170. // Methods
  42171. StateCondition.prototype.isValid = function () {
  42172. return this._target.state === this.value;
  42173. };
  42174. StateCondition.prototype.serialize = function () {
  42175. return this._serialize({
  42176. name: "StateCondition",
  42177. properties: [
  42178. BABYLON.Action._GetTargetProperty(this._target),
  42179. { name: "value", value: this.value }
  42180. ]
  42181. });
  42182. };
  42183. return StateCondition;
  42184. }(Condition));
  42185. BABYLON.StateCondition = StateCondition;
  42186. })(BABYLON || (BABYLON = {}));
  42187. //# sourceMappingURL=babylon.condition.js.map
  42188. var BABYLON;
  42189. (function (BABYLON) {
  42190. var Action = /** @class */ (function () {
  42191. function Action(triggerOptions, condition) {
  42192. this.triggerOptions = triggerOptions;
  42193. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42194. if (triggerOptions.parameter) {
  42195. this.trigger = triggerOptions.trigger;
  42196. this._triggerParameter = triggerOptions.parameter;
  42197. }
  42198. else {
  42199. this.trigger = triggerOptions;
  42200. }
  42201. this._nextActiveAction = this;
  42202. this._condition = condition;
  42203. }
  42204. // Methods
  42205. Action.prototype._prepare = function () {
  42206. };
  42207. Action.prototype.getTriggerParameter = function () {
  42208. return this._triggerParameter;
  42209. };
  42210. Action.prototype._executeCurrent = function (evt) {
  42211. if (this._nextActiveAction._condition) {
  42212. var condition = this._nextActiveAction._condition;
  42213. var currentRenderId = this._actionManager.getScene().getRenderId();
  42214. // We cache the current evaluation for the current frame
  42215. if (condition._evaluationId === currentRenderId) {
  42216. if (!condition._currentResult) {
  42217. return;
  42218. }
  42219. }
  42220. else {
  42221. condition._evaluationId = currentRenderId;
  42222. if (!condition.isValid()) {
  42223. condition._currentResult = false;
  42224. return;
  42225. }
  42226. condition._currentResult = true;
  42227. }
  42228. }
  42229. this.onBeforeExecuteObservable.notifyObservers(this);
  42230. this._nextActiveAction.execute(evt);
  42231. this.skipToNextActiveAction();
  42232. };
  42233. Action.prototype.execute = function (evt) {
  42234. };
  42235. Action.prototype.skipToNextActiveAction = function () {
  42236. if (this._nextActiveAction._child) {
  42237. if (!this._nextActiveAction._child._actionManager) {
  42238. this._nextActiveAction._child._actionManager = this._actionManager;
  42239. }
  42240. this._nextActiveAction = this._nextActiveAction._child;
  42241. }
  42242. else {
  42243. this._nextActiveAction = this;
  42244. }
  42245. };
  42246. Action.prototype.then = function (action) {
  42247. this._child = action;
  42248. action._actionManager = this._actionManager;
  42249. action._prepare();
  42250. return action;
  42251. };
  42252. Action.prototype._getProperty = function (propertyPath) {
  42253. return this._actionManager._getProperty(propertyPath);
  42254. };
  42255. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42256. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42257. };
  42258. Action.prototype.serialize = function (parent) {
  42259. };
  42260. // Called by BABYLON.Action objects in serialize(...). Internal use
  42261. Action.prototype._serialize = function (serializedAction, parent) {
  42262. var serializationObject = {
  42263. type: 1,
  42264. children: [],
  42265. name: serializedAction.name,
  42266. properties: serializedAction.properties || []
  42267. };
  42268. // Serialize child
  42269. if (this._child) {
  42270. this._child.serialize(serializationObject);
  42271. }
  42272. // Check if "this" has a condition
  42273. if (this._condition) {
  42274. var serializedCondition = this._condition.serialize();
  42275. serializedCondition.children.push(serializationObject);
  42276. if (parent) {
  42277. parent.children.push(serializedCondition);
  42278. }
  42279. return serializedCondition;
  42280. }
  42281. if (parent) {
  42282. parent.children.push(serializationObject);
  42283. }
  42284. return serializationObject;
  42285. };
  42286. Action._SerializeValueAsString = function (value) {
  42287. if (typeof value === "number") {
  42288. return value.toString();
  42289. }
  42290. if (typeof value === "boolean") {
  42291. return value ? "true" : "false";
  42292. }
  42293. if (value instanceof BABYLON.Vector2) {
  42294. return value.x + ", " + value.y;
  42295. }
  42296. if (value instanceof BABYLON.Vector3) {
  42297. return value.x + ", " + value.y + ", " + value.z;
  42298. }
  42299. if (value instanceof BABYLON.Color3) {
  42300. return value.r + ", " + value.g + ", " + value.b;
  42301. }
  42302. if (value instanceof BABYLON.Color4) {
  42303. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42304. }
  42305. return value; // string
  42306. };
  42307. Action._GetTargetProperty = function (target) {
  42308. return {
  42309. name: "target",
  42310. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42311. : target instanceof BABYLON.Light ? "LightProperties"
  42312. : target instanceof BABYLON.Camera ? "CameraProperties"
  42313. : "SceneProperties",
  42314. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42315. };
  42316. };
  42317. return Action;
  42318. }());
  42319. BABYLON.Action = Action;
  42320. })(BABYLON || (BABYLON = {}));
  42321. //# sourceMappingURL=babylon.action.js.map
  42322. var BABYLON;
  42323. (function (BABYLON) {
  42324. /**
  42325. * ActionEvent is the event beint sent when an action is triggered.
  42326. */
  42327. var ActionEvent = /** @class */ (function () {
  42328. /**
  42329. * @param source The mesh or sprite that triggered the action.
  42330. * @param pointerX The X mouse cursor position at the time of the event
  42331. * @param pointerY The Y mouse cursor position at the time of the event
  42332. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42333. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42334. */
  42335. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42336. this.source = source;
  42337. this.pointerX = pointerX;
  42338. this.pointerY = pointerY;
  42339. this.meshUnderPointer = meshUnderPointer;
  42340. this.sourceEvent = sourceEvent;
  42341. this.additionalData = additionalData;
  42342. }
  42343. /**
  42344. * Helper function to auto-create an ActionEvent from a source mesh.
  42345. * @param source The source mesh that triggered the event
  42346. * @param evt {Event} The original (browser) event
  42347. */
  42348. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42349. var scene = source.getScene();
  42350. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42351. };
  42352. /**
  42353. * Helper function to auto-create an ActionEvent from a source mesh.
  42354. * @param source The source sprite that triggered the event
  42355. * @param scene Scene associated with the sprite
  42356. * @param evt {Event} The original (browser) event
  42357. */
  42358. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42359. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42360. };
  42361. /**
  42362. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42363. * @param scene the scene where the event occurred
  42364. * @param evt {Event} The original (browser) event
  42365. */
  42366. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42367. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42368. };
  42369. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42370. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42371. };
  42372. return ActionEvent;
  42373. }());
  42374. BABYLON.ActionEvent = ActionEvent;
  42375. /**
  42376. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42377. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42378. */
  42379. var ActionManager = /** @class */ (function () {
  42380. function ActionManager(scene) {
  42381. // Members
  42382. this.actions = new Array();
  42383. this.hoverCursor = '';
  42384. this._scene = scene;
  42385. scene._actionManagers.push(this);
  42386. }
  42387. Object.defineProperty(ActionManager, "NothingTrigger", {
  42388. get: function () {
  42389. return ActionManager._NothingTrigger;
  42390. },
  42391. enumerable: true,
  42392. configurable: true
  42393. });
  42394. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42395. get: function () {
  42396. return ActionManager._OnPickTrigger;
  42397. },
  42398. enumerable: true,
  42399. configurable: true
  42400. });
  42401. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42402. get: function () {
  42403. return ActionManager._OnLeftPickTrigger;
  42404. },
  42405. enumerable: true,
  42406. configurable: true
  42407. });
  42408. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42409. get: function () {
  42410. return ActionManager._OnRightPickTrigger;
  42411. },
  42412. enumerable: true,
  42413. configurable: true
  42414. });
  42415. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42416. get: function () {
  42417. return ActionManager._OnCenterPickTrigger;
  42418. },
  42419. enumerable: true,
  42420. configurable: true
  42421. });
  42422. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42423. get: function () {
  42424. return ActionManager._OnPickDownTrigger;
  42425. },
  42426. enumerable: true,
  42427. configurable: true
  42428. });
  42429. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42430. get: function () {
  42431. return ActionManager._OnDoublePickTrigger;
  42432. },
  42433. enumerable: true,
  42434. configurable: true
  42435. });
  42436. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42437. get: function () {
  42438. return ActionManager._OnPickUpTrigger;
  42439. },
  42440. enumerable: true,
  42441. configurable: true
  42442. });
  42443. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42444. /// This trigger will only be raised if you also declared a OnPickDown
  42445. get: function () {
  42446. return ActionManager._OnPickOutTrigger;
  42447. },
  42448. enumerable: true,
  42449. configurable: true
  42450. });
  42451. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42452. get: function () {
  42453. return ActionManager._OnLongPressTrigger;
  42454. },
  42455. enumerable: true,
  42456. configurable: true
  42457. });
  42458. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42459. get: function () {
  42460. return ActionManager._OnPointerOverTrigger;
  42461. },
  42462. enumerable: true,
  42463. configurable: true
  42464. });
  42465. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42466. get: function () {
  42467. return ActionManager._OnPointerOutTrigger;
  42468. },
  42469. enumerable: true,
  42470. configurable: true
  42471. });
  42472. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42473. get: function () {
  42474. return ActionManager._OnEveryFrameTrigger;
  42475. },
  42476. enumerable: true,
  42477. configurable: true
  42478. });
  42479. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42480. get: function () {
  42481. return ActionManager._OnIntersectionEnterTrigger;
  42482. },
  42483. enumerable: true,
  42484. configurable: true
  42485. });
  42486. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42487. get: function () {
  42488. return ActionManager._OnIntersectionExitTrigger;
  42489. },
  42490. enumerable: true,
  42491. configurable: true
  42492. });
  42493. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42494. get: function () {
  42495. return ActionManager._OnKeyDownTrigger;
  42496. },
  42497. enumerable: true,
  42498. configurable: true
  42499. });
  42500. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42501. get: function () {
  42502. return ActionManager._OnKeyUpTrigger;
  42503. },
  42504. enumerable: true,
  42505. configurable: true
  42506. });
  42507. // Methods
  42508. ActionManager.prototype.dispose = function () {
  42509. var index = this._scene._actionManagers.indexOf(this);
  42510. for (var i = 0; i < this.actions.length; i++) {
  42511. var action = this.actions[i];
  42512. ActionManager.Triggers[action.trigger]--;
  42513. if (ActionManager.Triggers[action.trigger] === 0) {
  42514. delete ActionManager.Triggers[action.trigger];
  42515. }
  42516. }
  42517. if (index > -1) {
  42518. this._scene._actionManagers.splice(index, 1);
  42519. }
  42520. };
  42521. ActionManager.prototype.getScene = function () {
  42522. return this._scene;
  42523. };
  42524. /**
  42525. * Does this action manager handles actions of any of the given triggers
  42526. * @param {number[]} triggers - the triggers to be tested
  42527. * @return {boolean} whether one (or more) of the triggers is handeled
  42528. */
  42529. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42530. for (var index = 0; index < this.actions.length; index++) {
  42531. var action = this.actions[index];
  42532. if (triggers.indexOf(action.trigger) > -1) {
  42533. return true;
  42534. }
  42535. }
  42536. return false;
  42537. };
  42538. /**
  42539. * Does this action manager handles actions of a given trigger
  42540. * @param {number} trigger - the trigger to be tested
  42541. * @return {boolean} whether the trigger is handeled
  42542. */
  42543. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42544. for (var index = 0; index < this.actions.length; index++) {
  42545. var action = this.actions[index];
  42546. if (action.trigger === trigger) {
  42547. return true;
  42548. }
  42549. }
  42550. return false;
  42551. };
  42552. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42553. /**
  42554. * Does this action manager has pointer triggers
  42555. * @return {boolean} whether or not it has pointer triggers
  42556. */
  42557. get: function () {
  42558. for (var index = 0; index < this.actions.length; index++) {
  42559. var action = this.actions[index];
  42560. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42561. return true;
  42562. }
  42563. }
  42564. return false;
  42565. },
  42566. enumerable: true,
  42567. configurable: true
  42568. });
  42569. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42570. /**
  42571. * Does this action manager has pick triggers
  42572. * @return {boolean} whether or not it has pick triggers
  42573. */
  42574. get: function () {
  42575. for (var index = 0; index < this.actions.length; index++) {
  42576. var action = this.actions[index];
  42577. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42578. return true;
  42579. }
  42580. }
  42581. return false;
  42582. },
  42583. enumerable: true,
  42584. configurable: true
  42585. });
  42586. Object.defineProperty(ActionManager, "HasTriggers", {
  42587. /**
  42588. * Does exist one action manager with at least one trigger
  42589. * @return {boolean} whether or not it exists one action manager with one trigger
  42590. **/
  42591. get: function () {
  42592. for (var t in ActionManager.Triggers) {
  42593. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42594. return true;
  42595. }
  42596. }
  42597. return false;
  42598. },
  42599. enumerable: true,
  42600. configurable: true
  42601. });
  42602. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42603. /**
  42604. * Does exist one action manager with at least one pick trigger
  42605. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42606. **/
  42607. get: function () {
  42608. for (var t in ActionManager.Triggers) {
  42609. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42610. var t_int = parseInt(t);
  42611. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42612. return true;
  42613. }
  42614. }
  42615. }
  42616. return false;
  42617. },
  42618. enumerable: true,
  42619. configurable: true
  42620. });
  42621. /**
  42622. * Does exist one action manager that handles actions of a given trigger
  42623. * @param {number} trigger - the trigger to be tested
  42624. * @return {boolean} whether the trigger is handeled by at least one action manager
  42625. **/
  42626. ActionManager.HasSpecificTrigger = function (trigger) {
  42627. for (var t in ActionManager.Triggers) {
  42628. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42629. var t_int = parseInt(t);
  42630. if (t_int === trigger) {
  42631. return true;
  42632. }
  42633. }
  42634. }
  42635. return false;
  42636. };
  42637. /**
  42638. * Registers an action to this action manager
  42639. * @param {BABYLON.Action} action - the action to be registered
  42640. * @return {BABYLON.Action} the action amended (prepared) after registration
  42641. */
  42642. ActionManager.prototype.registerAction = function (action) {
  42643. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42644. if (this.getScene().actionManager !== this) {
  42645. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42646. return null;
  42647. }
  42648. }
  42649. this.actions.push(action);
  42650. if (ActionManager.Triggers[action.trigger]) {
  42651. ActionManager.Triggers[action.trigger]++;
  42652. }
  42653. else {
  42654. ActionManager.Triggers[action.trigger] = 1;
  42655. }
  42656. action._actionManager = this;
  42657. action._prepare();
  42658. return action;
  42659. };
  42660. /**
  42661. * Process a specific trigger
  42662. * @param {number} trigger - the trigger to process
  42663. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42664. */
  42665. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42666. for (var index = 0; index < this.actions.length; index++) {
  42667. var action = this.actions[index];
  42668. if (action.trigger === trigger) {
  42669. if (evt) {
  42670. if (trigger === ActionManager.OnKeyUpTrigger
  42671. || trigger === ActionManager.OnKeyDownTrigger) {
  42672. var parameter = action.getTriggerParameter();
  42673. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42674. if (!parameter.toLowerCase) {
  42675. continue;
  42676. }
  42677. var lowerCase = parameter.toLowerCase();
  42678. if (lowerCase !== evt.sourceEvent.key) {
  42679. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42680. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42681. if (actualkey !== lowerCase) {
  42682. continue;
  42683. }
  42684. }
  42685. }
  42686. }
  42687. }
  42688. action._executeCurrent(evt);
  42689. }
  42690. }
  42691. };
  42692. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42693. var properties = propertyPath.split(".");
  42694. for (var index = 0; index < properties.length - 1; index++) {
  42695. target = target[properties[index]];
  42696. }
  42697. return target;
  42698. };
  42699. ActionManager.prototype._getProperty = function (propertyPath) {
  42700. var properties = propertyPath.split(".");
  42701. return properties[properties.length - 1];
  42702. };
  42703. ActionManager.prototype.serialize = function (name) {
  42704. var root = {
  42705. children: new Array(),
  42706. name: name,
  42707. type: 3,
  42708. properties: new Array() // Empty for root but required
  42709. };
  42710. for (var i = 0; i < this.actions.length; i++) {
  42711. var triggerObject = {
  42712. type: 0,
  42713. children: new Array(),
  42714. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42715. properties: new Array()
  42716. };
  42717. var triggerOptions = this.actions[i].triggerOptions;
  42718. if (triggerOptions && typeof triggerOptions !== "number") {
  42719. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42720. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42721. }
  42722. else {
  42723. var parameter = {};
  42724. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42725. if (triggerOptions.parameter.mesh) {
  42726. parameter._meshId = triggerOptions.parameter.mesh.id;
  42727. }
  42728. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42729. }
  42730. }
  42731. // Serialize child action, recursively
  42732. this.actions[i].serialize(triggerObject);
  42733. // Add serialized trigger
  42734. root.children.push(triggerObject);
  42735. }
  42736. return root;
  42737. };
  42738. ActionManager.Parse = function (parsedActions, object, scene) {
  42739. var actionManager = new BABYLON.ActionManager(scene);
  42740. if (object === null)
  42741. scene.actionManager = actionManager;
  42742. else
  42743. object.actionManager = actionManager;
  42744. // instanciate a new object
  42745. var instanciate = function (name, params) {
  42746. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42747. newInstance.constructor.apply(newInstance, params);
  42748. return newInstance;
  42749. };
  42750. var parseParameter = function (name, value, target, propertyPath) {
  42751. if (propertyPath === null) {
  42752. // String, boolean or float
  42753. var floatValue = parseFloat(value);
  42754. if (value === "true" || value === "false")
  42755. return value === "true";
  42756. else
  42757. return isNaN(floatValue) ? value : floatValue;
  42758. }
  42759. var effectiveTarget = propertyPath.split(".");
  42760. var values = value.split(",");
  42761. // Get effective Target
  42762. for (var i = 0; i < effectiveTarget.length; i++) {
  42763. target = target[effectiveTarget[i]];
  42764. }
  42765. // Return appropriate value with its type
  42766. if (typeof (target) === "boolean")
  42767. return values[0] === "true";
  42768. if (typeof (target) === "string")
  42769. return values[0];
  42770. // Parameters with multiple values such as Vector3 etc.
  42771. var split = new Array();
  42772. for (var i = 0; i < values.length; i++)
  42773. split.push(parseFloat(values[i]));
  42774. if (target instanceof BABYLON.Vector3)
  42775. return BABYLON.Vector3.FromArray(split);
  42776. if (target instanceof BABYLON.Vector4)
  42777. return BABYLON.Vector4.FromArray(split);
  42778. if (target instanceof BABYLON.Color3)
  42779. return BABYLON.Color3.FromArray(split);
  42780. if (target instanceof BABYLON.Color4)
  42781. return BABYLON.Color4.FromArray(split);
  42782. return parseFloat(values[0]);
  42783. };
  42784. // traverse graph per trigger
  42785. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42786. if (combineArray === void 0) { combineArray = null; }
  42787. if (parsedAction.detached)
  42788. return;
  42789. var parameters = new Array();
  42790. var target = null;
  42791. var propertyPath = null;
  42792. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42793. // Parameters
  42794. if (parsedAction.type === 2)
  42795. parameters.push(actionManager);
  42796. else
  42797. parameters.push(trigger);
  42798. if (combine) {
  42799. var actions = new Array();
  42800. for (var j = 0; j < parsedAction.combine.length; j++) {
  42801. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42802. }
  42803. parameters.push(actions);
  42804. }
  42805. else {
  42806. for (var i = 0; i < parsedAction.properties.length; i++) {
  42807. var value = parsedAction.properties[i].value;
  42808. var name = parsedAction.properties[i].name;
  42809. var targetType = parsedAction.properties[i].targetType;
  42810. if (name === "target")
  42811. if (targetType !== null && targetType === "SceneProperties")
  42812. value = target = scene;
  42813. else
  42814. value = target = scene.getNodeByName(value);
  42815. else if (name === "parent")
  42816. value = scene.getNodeByName(value);
  42817. else if (name === "sound")
  42818. value = scene.getSoundByName(value);
  42819. else if (name !== "propertyPath") {
  42820. if (parsedAction.type === 2 && name === "operator")
  42821. value = BABYLON.ValueCondition[value];
  42822. else
  42823. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42824. }
  42825. else {
  42826. propertyPath = value;
  42827. }
  42828. parameters.push(value);
  42829. }
  42830. }
  42831. if (combineArray === null) {
  42832. parameters.push(condition);
  42833. }
  42834. else {
  42835. parameters.push(null);
  42836. }
  42837. // If interpolate value action
  42838. if (parsedAction.name === "InterpolateValueAction") {
  42839. var param = parameters[parameters.length - 2];
  42840. parameters[parameters.length - 1] = param;
  42841. parameters[parameters.length - 2] = condition;
  42842. }
  42843. // Action or condition(s) and not CombineAction
  42844. var newAction = instanciate(parsedAction.name, parameters);
  42845. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42846. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42847. if (action)
  42848. action.then(nothing);
  42849. else
  42850. actionManager.registerAction(nothing);
  42851. action = nothing;
  42852. }
  42853. if (combineArray === null) {
  42854. if (newAction instanceof BABYLON.Condition) {
  42855. condition = newAction;
  42856. newAction = action;
  42857. }
  42858. else {
  42859. condition = null;
  42860. if (action)
  42861. action.then(newAction);
  42862. else
  42863. actionManager.registerAction(newAction);
  42864. }
  42865. }
  42866. else {
  42867. combineArray.push(newAction);
  42868. }
  42869. for (var i = 0; i < parsedAction.children.length; i++)
  42870. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42871. };
  42872. // triggers
  42873. for (var i = 0; i < parsedActions.children.length; i++) {
  42874. var triggerParams;
  42875. var trigger = parsedActions.children[i];
  42876. if (trigger.properties.length > 0) {
  42877. var param = trigger.properties[0].value;
  42878. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42879. if (value._meshId) {
  42880. value.mesh = scene.getMeshByID(value._meshId);
  42881. }
  42882. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42883. }
  42884. else
  42885. triggerParams = ActionManager[trigger.name];
  42886. for (var j = 0; j < trigger.children.length; j++) {
  42887. if (!trigger.detached)
  42888. traverse(trigger.children[j], triggerParams, null, null);
  42889. }
  42890. }
  42891. };
  42892. ActionManager.GetTriggerName = function (trigger) {
  42893. switch (trigger) {
  42894. case 0: return "NothingTrigger";
  42895. case 1: return "OnPickTrigger";
  42896. case 2: return "OnLeftPickTrigger";
  42897. case 3: return "OnRightPickTrigger";
  42898. case 4: return "OnCenterPickTrigger";
  42899. case 5: return "OnPickDownTrigger";
  42900. case 6: return "OnPickUpTrigger";
  42901. case 7: return "OnLongPressTrigger";
  42902. case 8: return "OnPointerOverTrigger";
  42903. case 9: return "OnPointerOutTrigger";
  42904. case 10: return "OnEveryFrameTrigger";
  42905. case 11: return "OnIntersectionEnterTrigger";
  42906. case 12: return "OnIntersectionExitTrigger";
  42907. case 13: return "OnKeyDownTrigger";
  42908. case 14: return "OnKeyUpTrigger";
  42909. case 15: return "OnPickOutTrigger";
  42910. default: return "";
  42911. }
  42912. };
  42913. // Statics
  42914. ActionManager._NothingTrigger = 0;
  42915. ActionManager._OnPickTrigger = 1;
  42916. ActionManager._OnLeftPickTrigger = 2;
  42917. ActionManager._OnRightPickTrigger = 3;
  42918. ActionManager._OnCenterPickTrigger = 4;
  42919. ActionManager._OnPickDownTrigger = 5;
  42920. ActionManager._OnDoublePickTrigger = 6;
  42921. ActionManager._OnPickUpTrigger = 7;
  42922. ActionManager._OnLongPressTrigger = 8;
  42923. ActionManager._OnPointerOverTrigger = 9;
  42924. ActionManager._OnPointerOutTrigger = 10;
  42925. ActionManager._OnEveryFrameTrigger = 11;
  42926. ActionManager._OnIntersectionEnterTrigger = 12;
  42927. ActionManager._OnIntersectionExitTrigger = 13;
  42928. ActionManager._OnKeyDownTrigger = 14;
  42929. ActionManager._OnKeyUpTrigger = 15;
  42930. ActionManager._OnPickOutTrigger = 16;
  42931. ActionManager.Triggers = {};
  42932. return ActionManager;
  42933. }());
  42934. BABYLON.ActionManager = ActionManager;
  42935. })(BABYLON || (BABYLON = {}));
  42936. //# sourceMappingURL=babylon.actionManager.js.map
  42937. var BABYLON;
  42938. (function (BABYLON) {
  42939. var InterpolateValueAction = /** @class */ (function (_super) {
  42940. __extends(InterpolateValueAction, _super);
  42941. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42942. if (duration === void 0) { duration = 1000; }
  42943. var _this = _super.call(this, triggerOptions, condition) || this;
  42944. _this.propertyPath = propertyPath;
  42945. _this.value = value;
  42946. _this.duration = duration;
  42947. _this.stopOtherAnimations = stopOtherAnimations;
  42948. _this.onInterpolationDone = onInterpolationDone;
  42949. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42950. _this._target = _this._effectiveTarget = target;
  42951. return _this;
  42952. }
  42953. InterpolateValueAction.prototype._prepare = function () {
  42954. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42955. this._property = this._getProperty(this.propertyPath);
  42956. };
  42957. InterpolateValueAction.prototype.execute = function () {
  42958. var _this = this;
  42959. var scene = this._actionManager.getScene();
  42960. var keys = [
  42961. {
  42962. frame: 0,
  42963. value: this._effectiveTarget[this._property]
  42964. }, {
  42965. frame: 100,
  42966. value: this.value
  42967. }
  42968. ];
  42969. var dataType;
  42970. if (typeof this.value === "number") {
  42971. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42972. }
  42973. else if (this.value instanceof BABYLON.Color3) {
  42974. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42975. }
  42976. else if (this.value instanceof BABYLON.Vector3) {
  42977. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42978. }
  42979. else if (this.value instanceof BABYLON.Matrix) {
  42980. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42981. }
  42982. else if (this.value instanceof BABYLON.Quaternion) {
  42983. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42984. }
  42985. else {
  42986. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42987. return;
  42988. }
  42989. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42990. animation.setKeys(keys);
  42991. if (this.stopOtherAnimations) {
  42992. scene.stopAnimation(this._effectiveTarget);
  42993. }
  42994. var wrapper = function () {
  42995. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42996. if (_this.onInterpolationDone) {
  42997. _this.onInterpolationDone();
  42998. }
  42999. };
  43000. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43001. };
  43002. InterpolateValueAction.prototype.serialize = function (parent) {
  43003. return _super.prototype._serialize.call(this, {
  43004. name: "InterpolateValueAction",
  43005. properties: [
  43006. BABYLON.Action._GetTargetProperty(this._target),
  43007. { name: "propertyPath", value: this.propertyPath },
  43008. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43009. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43010. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43011. ]
  43012. }, parent);
  43013. };
  43014. return InterpolateValueAction;
  43015. }(BABYLON.Action));
  43016. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43017. })(BABYLON || (BABYLON = {}));
  43018. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43019. var BABYLON;
  43020. (function (BABYLON) {
  43021. var SwitchBooleanAction = /** @class */ (function (_super) {
  43022. __extends(SwitchBooleanAction, _super);
  43023. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43024. var _this = _super.call(this, triggerOptions, condition) || this;
  43025. _this.propertyPath = propertyPath;
  43026. _this._target = _this._effectiveTarget = target;
  43027. return _this;
  43028. }
  43029. SwitchBooleanAction.prototype._prepare = function () {
  43030. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43031. this._property = this._getProperty(this.propertyPath);
  43032. };
  43033. SwitchBooleanAction.prototype.execute = function () {
  43034. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43035. };
  43036. SwitchBooleanAction.prototype.serialize = function (parent) {
  43037. return _super.prototype._serialize.call(this, {
  43038. name: "SwitchBooleanAction",
  43039. properties: [
  43040. BABYLON.Action._GetTargetProperty(this._target),
  43041. { name: "propertyPath", value: this.propertyPath }
  43042. ]
  43043. }, parent);
  43044. };
  43045. return SwitchBooleanAction;
  43046. }(BABYLON.Action));
  43047. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43048. var SetStateAction = /** @class */ (function (_super) {
  43049. __extends(SetStateAction, _super);
  43050. function SetStateAction(triggerOptions, target, value, condition) {
  43051. var _this = _super.call(this, triggerOptions, condition) || this;
  43052. _this.value = value;
  43053. _this._target = target;
  43054. return _this;
  43055. }
  43056. SetStateAction.prototype.execute = function () {
  43057. this._target.state = this.value;
  43058. };
  43059. SetStateAction.prototype.serialize = function (parent) {
  43060. return _super.prototype._serialize.call(this, {
  43061. name: "SetStateAction",
  43062. properties: [
  43063. BABYLON.Action._GetTargetProperty(this._target),
  43064. { name: "value", value: this.value }
  43065. ]
  43066. }, parent);
  43067. };
  43068. return SetStateAction;
  43069. }(BABYLON.Action));
  43070. BABYLON.SetStateAction = SetStateAction;
  43071. var SetValueAction = /** @class */ (function (_super) {
  43072. __extends(SetValueAction, _super);
  43073. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43074. var _this = _super.call(this, triggerOptions, condition) || this;
  43075. _this.propertyPath = propertyPath;
  43076. _this.value = value;
  43077. _this._target = _this._effectiveTarget = target;
  43078. return _this;
  43079. }
  43080. SetValueAction.prototype._prepare = function () {
  43081. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43082. this._property = this._getProperty(this.propertyPath);
  43083. };
  43084. SetValueAction.prototype.execute = function () {
  43085. this._effectiveTarget[this._property] = this.value;
  43086. if (this._target.markAsDirty) {
  43087. this._target.markAsDirty(this._property);
  43088. }
  43089. };
  43090. SetValueAction.prototype.serialize = function (parent) {
  43091. return _super.prototype._serialize.call(this, {
  43092. name: "SetValueAction",
  43093. properties: [
  43094. BABYLON.Action._GetTargetProperty(this._target),
  43095. { name: "propertyPath", value: this.propertyPath },
  43096. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43097. ]
  43098. }, parent);
  43099. };
  43100. return SetValueAction;
  43101. }(BABYLON.Action));
  43102. BABYLON.SetValueAction = SetValueAction;
  43103. var IncrementValueAction = /** @class */ (function (_super) {
  43104. __extends(IncrementValueAction, _super);
  43105. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43106. var _this = _super.call(this, triggerOptions, condition) || this;
  43107. _this.propertyPath = propertyPath;
  43108. _this.value = value;
  43109. _this._target = _this._effectiveTarget = target;
  43110. return _this;
  43111. }
  43112. IncrementValueAction.prototype._prepare = function () {
  43113. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43114. this._property = this._getProperty(this.propertyPath);
  43115. if (typeof this._effectiveTarget[this._property] !== "number") {
  43116. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43117. }
  43118. };
  43119. IncrementValueAction.prototype.execute = function () {
  43120. this._effectiveTarget[this._property] += this.value;
  43121. if (this._target.markAsDirty) {
  43122. this._target.markAsDirty(this._property);
  43123. }
  43124. };
  43125. IncrementValueAction.prototype.serialize = function (parent) {
  43126. return _super.prototype._serialize.call(this, {
  43127. name: "IncrementValueAction",
  43128. properties: [
  43129. BABYLON.Action._GetTargetProperty(this._target),
  43130. { name: "propertyPath", value: this.propertyPath },
  43131. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43132. ]
  43133. }, parent);
  43134. };
  43135. return IncrementValueAction;
  43136. }(BABYLON.Action));
  43137. BABYLON.IncrementValueAction = IncrementValueAction;
  43138. var PlayAnimationAction = /** @class */ (function (_super) {
  43139. __extends(PlayAnimationAction, _super);
  43140. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43141. var _this = _super.call(this, triggerOptions, condition) || this;
  43142. _this.from = from;
  43143. _this.to = to;
  43144. _this.loop = loop;
  43145. _this._target = target;
  43146. return _this;
  43147. }
  43148. PlayAnimationAction.prototype._prepare = function () {
  43149. };
  43150. PlayAnimationAction.prototype.execute = function () {
  43151. var scene = this._actionManager.getScene();
  43152. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43153. };
  43154. PlayAnimationAction.prototype.serialize = function (parent) {
  43155. return _super.prototype._serialize.call(this, {
  43156. name: "PlayAnimationAction",
  43157. properties: [
  43158. BABYLON.Action._GetTargetProperty(this._target),
  43159. { name: "from", value: String(this.from) },
  43160. { name: "to", value: String(this.to) },
  43161. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43162. ]
  43163. }, parent);
  43164. };
  43165. return PlayAnimationAction;
  43166. }(BABYLON.Action));
  43167. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43168. var StopAnimationAction = /** @class */ (function (_super) {
  43169. __extends(StopAnimationAction, _super);
  43170. function StopAnimationAction(triggerOptions, target, condition) {
  43171. var _this = _super.call(this, triggerOptions, condition) || this;
  43172. _this._target = target;
  43173. return _this;
  43174. }
  43175. StopAnimationAction.prototype._prepare = function () {
  43176. };
  43177. StopAnimationAction.prototype.execute = function () {
  43178. var scene = this._actionManager.getScene();
  43179. scene.stopAnimation(this._target);
  43180. };
  43181. StopAnimationAction.prototype.serialize = function (parent) {
  43182. return _super.prototype._serialize.call(this, {
  43183. name: "StopAnimationAction",
  43184. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43185. }, parent);
  43186. };
  43187. return StopAnimationAction;
  43188. }(BABYLON.Action));
  43189. BABYLON.StopAnimationAction = StopAnimationAction;
  43190. var DoNothingAction = /** @class */ (function (_super) {
  43191. __extends(DoNothingAction, _super);
  43192. function DoNothingAction(triggerOptions, condition) {
  43193. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43194. return _super.call(this, triggerOptions, condition) || this;
  43195. }
  43196. DoNothingAction.prototype.execute = function () {
  43197. };
  43198. DoNothingAction.prototype.serialize = function (parent) {
  43199. return _super.prototype._serialize.call(this, {
  43200. name: "DoNothingAction",
  43201. properties: []
  43202. }, parent);
  43203. };
  43204. return DoNothingAction;
  43205. }(BABYLON.Action));
  43206. BABYLON.DoNothingAction = DoNothingAction;
  43207. var CombineAction = /** @class */ (function (_super) {
  43208. __extends(CombineAction, _super);
  43209. function CombineAction(triggerOptions, children, condition) {
  43210. var _this = _super.call(this, triggerOptions, condition) || this;
  43211. _this.children = children;
  43212. return _this;
  43213. }
  43214. CombineAction.prototype._prepare = function () {
  43215. for (var index = 0; index < this.children.length; index++) {
  43216. this.children[index]._actionManager = this._actionManager;
  43217. this.children[index]._prepare();
  43218. }
  43219. };
  43220. CombineAction.prototype.execute = function (evt) {
  43221. for (var index = 0; index < this.children.length; index++) {
  43222. this.children[index].execute(evt);
  43223. }
  43224. };
  43225. CombineAction.prototype.serialize = function (parent) {
  43226. var serializationObject = _super.prototype._serialize.call(this, {
  43227. name: "CombineAction",
  43228. properties: [],
  43229. combine: []
  43230. }, parent);
  43231. for (var i = 0; i < this.children.length; i++) {
  43232. serializationObject.combine.push(this.children[i].serialize(null));
  43233. }
  43234. return serializationObject;
  43235. };
  43236. return CombineAction;
  43237. }(BABYLON.Action));
  43238. BABYLON.CombineAction = CombineAction;
  43239. var ExecuteCodeAction = /** @class */ (function (_super) {
  43240. __extends(ExecuteCodeAction, _super);
  43241. function ExecuteCodeAction(triggerOptions, func, condition) {
  43242. var _this = _super.call(this, triggerOptions, condition) || this;
  43243. _this.func = func;
  43244. return _this;
  43245. }
  43246. ExecuteCodeAction.prototype.execute = function (evt) {
  43247. this.func(evt);
  43248. };
  43249. return ExecuteCodeAction;
  43250. }(BABYLON.Action));
  43251. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43252. var SetParentAction = /** @class */ (function (_super) {
  43253. __extends(SetParentAction, _super);
  43254. function SetParentAction(triggerOptions, target, parent, condition) {
  43255. var _this = _super.call(this, triggerOptions, condition) || this;
  43256. _this._target = target;
  43257. _this._parent = parent;
  43258. return _this;
  43259. }
  43260. SetParentAction.prototype._prepare = function () {
  43261. };
  43262. SetParentAction.prototype.execute = function () {
  43263. if (this._target.parent === this._parent) {
  43264. return;
  43265. }
  43266. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43267. invertParentWorldMatrix.invert();
  43268. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43269. this._target.parent = this._parent;
  43270. };
  43271. SetParentAction.prototype.serialize = function (parent) {
  43272. return _super.prototype._serialize.call(this, {
  43273. name: "SetParentAction",
  43274. properties: [
  43275. BABYLON.Action._GetTargetProperty(this._target),
  43276. BABYLON.Action._GetTargetProperty(this._parent),
  43277. ]
  43278. }, parent);
  43279. };
  43280. return SetParentAction;
  43281. }(BABYLON.Action));
  43282. BABYLON.SetParentAction = SetParentAction;
  43283. var PlaySoundAction = /** @class */ (function (_super) {
  43284. __extends(PlaySoundAction, _super);
  43285. function PlaySoundAction(triggerOptions, sound, condition) {
  43286. var _this = _super.call(this, triggerOptions, condition) || this;
  43287. _this._sound = sound;
  43288. return _this;
  43289. }
  43290. PlaySoundAction.prototype._prepare = function () {
  43291. };
  43292. PlaySoundAction.prototype.execute = function () {
  43293. if (this._sound !== undefined)
  43294. this._sound.play();
  43295. };
  43296. PlaySoundAction.prototype.serialize = function (parent) {
  43297. return _super.prototype._serialize.call(this, {
  43298. name: "PlaySoundAction",
  43299. properties: [{ name: "sound", value: this._sound.name }]
  43300. }, parent);
  43301. };
  43302. return PlaySoundAction;
  43303. }(BABYLON.Action));
  43304. BABYLON.PlaySoundAction = PlaySoundAction;
  43305. var StopSoundAction = /** @class */ (function (_super) {
  43306. __extends(StopSoundAction, _super);
  43307. function StopSoundAction(triggerOptions, sound, condition) {
  43308. var _this = _super.call(this, triggerOptions, condition) || this;
  43309. _this._sound = sound;
  43310. return _this;
  43311. }
  43312. StopSoundAction.prototype._prepare = function () {
  43313. };
  43314. StopSoundAction.prototype.execute = function () {
  43315. if (this._sound !== undefined)
  43316. this._sound.stop();
  43317. };
  43318. StopSoundAction.prototype.serialize = function (parent) {
  43319. return _super.prototype._serialize.call(this, {
  43320. name: "StopSoundAction",
  43321. properties: [{ name: "sound", value: this._sound.name }]
  43322. }, parent);
  43323. };
  43324. return StopSoundAction;
  43325. }(BABYLON.Action));
  43326. BABYLON.StopSoundAction = StopSoundAction;
  43327. })(BABYLON || (BABYLON = {}));
  43328. //# sourceMappingURL=babylon.directActions.js.map
  43329. var BABYLON;
  43330. (function (BABYLON) {
  43331. var SpriteManager = /** @class */ (function () {
  43332. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43333. if (epsilon === void 0) { epsilon = 0.01; }
  43334. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43335. this.name = name;
  43336. this.sprites = new Array();
  43337. this.renderingGroupId = 0;
  43338. this.layerMask = 0x0FFFFFFF;
  43339. this.fogEnabled = true;
  43340. this.isPickable = false;
  43341. /**
  43342. * An event triggered when the manager is disposed.
  43343. * @type {BABYLON.Observable}
  43344. */
  43345. this.onDisposeObservable = new BABYLON.Observable();
  43346. this._vertexBuffers = {};
  43347. this._capacity = capacity;
  43348. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43349. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43350. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43351. if (cellSize.width && cellSize.height) {
  43352. this.cellWidth = cellSize.width;
  43353. this.cellHeight = cellSize.height;
  43354. }
  43355. else if (cellSize !== undefined) {
  43356. this.cellWidth = cellSize;
  43357. this.cellHeight = cellSize;
  43358. }
  43359. else {
  43360. return;
  43361. }
  43362. this._epsilon = epsilon;
  43363. this._scene = scene;
  43364. this._scene.spriteManagers.push(this);
  43365. var indices = [];
  43366. var index = 0;
  43367. for (var count = 0; count < capacity; count++) {
  43368. indices.push(index);
  43369. indices.push(index + 1);
  43370. indices.push(index + 2);
  43371. indices.push(index);
  43372. indices.push(index + 2);
  43373. indices.push(index + 3);
  43374. index += 4;
  43375. }
  43376. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43377. // VBO
  43378. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43379. this._vertexData = new Float32Array(capacity * 16 * 4);
  43380. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43381. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43382. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43383. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43384. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43386. this._vertexBuffers["options"] = options;
  43387. this._vertexBuffers["cellInfo"] = cellInfo;
  43388. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43389. // Effects
  43390. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43391. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43392. }
  43393. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43394. set: function (callback) {
  43395. if (this._onDisposeObserver) {
  43396. this.onDisposeObservable.remove(this._onDisposeObserver);
  43397. }
  43398. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43399. },
  43400. enumerable: true,
  43401. configurable: true
  43402. });
  43403. Object.defineProperty(SpriteManager.prototype, "texture", {
  43404. get: function () {
  43405. return this._spriteTexture;
  43406. },
  43407. set: function (value) {
  43408. this._spriteTexture = value;
  43409. },
  43410. enumerable: true,
  43411. configurable: true
  43412. });
  43413. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43414. var arrayOffset = index * 16;
  43415. if (offsetX === 0)
  43416. offsetX = this._epsilon;
  43417. else if (offsetX === 1)
  43418. offsetX = 1 - this._epsilon;
  43419. if (offsetY === 0)
  43420. offsetY = this._epsilon;
  43421. else if (offsetY === 1)
  43422. offsetY = 1 - this._epsilon;
  43423. this._vertexData[arrayOffset] = sprite.position.x;
  43424. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43425. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43426. this._vertexData[arrayOffset + 3] = sprite.angle;
  43427. this._vertexData[arrayOffset + 4] = sprite.width;
  43428. this._vertexData[arrayOffset + 5] = sprite.height;
  43429. this._vertexData[arrayOffset + 6] = offsetX;
  43430. this._vertexData[arrayOffset + 7] = offsetY;
  43431. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43432. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43433. var offset = (sprite.cellIndex / rowSize) >> 0;
  43434. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43435. this._vertexData[arrayOffset + 11] = offset;
  43436. // Color
  43437. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43438. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43439. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43440. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43441. };
  43442. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43443. var count = Math.min(this._capacity, this.sprites.length);
  43444. var min = BABYLON.Vector3.Zero();
  43445. var max = BABYLON.Vector3.Zero();
  43446. var distance = Number.MAX_VALUE;
  43447. var currentSprite = null;
  43448. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43449. var cameraView = camera.getViewMatrix();
  43450. for (var index = 0; index < count; index++) {
  43451. var sprite = this.sprites[index];
  43452. if (!sprite) {
  43453. continue;
  43454. }
  43455. if (predicate) {
  43456. if (!predicate(sprite)) {
  43457. continue;
  43458. }
  43459. }
  43460. else if (!sprite.isPickable) {
  43461. continue;
  43462. }
  43463. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43464. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43465. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43466. if (ray.intersectsBoxMinMax(min, max)) {
  43467. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43468. if (distance > currentDistance) {
  43469. distance = currentDistance;
  43470. currentSprite = sprite;
  43471. if (fastCheck) {
  43472. break;
  43473. }
  43474. }
  43475. }
  43476. }
  43477. if (currentSprite) {
  43478. var result = new BABYLON.PickingInfo();
  43479. result.hit = true;
  43480. result.pickedSprite = currentSprite;
  43481. result.distance = distance;
  43482. return result;
  43483. }
  43484. return null;
  43485. };
  43486. SpriteManager.prototype.render = function () {
  43487. // Check
  43488. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43489. return;
  43490. var engine = this._scene.getEngine();
  43491. var baseSize = this._spriteTexture.getBaseSize();
  43492. // Sprites
  43493. var deltaTime = engine.getDeltaTime();
  43494. var max = Math.min(this._capacity, this.sprites.length);
  43495. var rowSize = baseSize.width / this.cellWidth;
  43496. var offset = 0;
  43497. for (var index = 0; index < max; index++) {
  43498. var sprite = this.sprites[index];
  43499. if (!sprite) {
  43500. continue;
  43501. }
  43502. sprite._animate(deltaTime);
  43503. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43504. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43505. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43506. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43507. }
  43508. this._buffer.update(this._vertexData);
  43509. // Render
  43510. var effect = this._effectBase;
  43511. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43512. effect = this._effectFog;
  43513. }
  43514. engine.enableEffect(effect);
  43515. var viewMatrix = this._scene.getViewMatrix();
  43516. effect.setTexture("diffuseSampler", this._spriteTexture);
  43517. effect.setMatrix("view", viewMatrix);
  43518. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43519. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43520. // Fog
  43521. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43522. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43523. effect.setColor3("vFogColor", this._scene.fogColor);
  43524. }
  43525. // VBOs
  43526. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43527. // Draw order
  43528. engine.setDepthFunctionToLessOrEqual();
  43529. effect.setBool("alphaTest", true);
  43530. engine.setColorWrite(false);
  43531. engine.draw(true, 0, max * 6);
  43532. engine.setColorWrite(true);
  43533. effect.setBool("alphaTest", false);
  43534. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43535. engine.draw(true, 0, max * 6);
  43536. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43537. };
  43538. SpriteManager.prototype.dispose = function () {
  43539. if (this._buffer) {
  43540. this._buffer.dispose();
  43541. this._buffer = null;
  43542. }
  43543. if (this._indexBuffer) {
  43544. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43545. this._indexBuffer = null;
  43546. }
  43547. if (this._spriteTexture) {
  43548. this._spriteTexture.dispose();
  43549. this._spriteTexture = null;
  43550. }
  43551. // Remove from scene
  43552. var index = this._scene.spriteManagers.indexOf(this);
  43553. this._scene.spriteManagers.splice(index, 1);
  43554. // Callback
  43555. this.onDisposeObservable.notifyObservers(this);
  43556. this.onDisposeObservable.clear();
  43557. };
  43558. return SpriteManager;
  43559. }());
  43560. BABYLON.SpriteManager = SpriteManager;
  43561. })(BABYLON || (BABYLON = {}));
  43562. //# sourceMappingURL=babylon.spriteManager.js.map
  43563. var BABYLON;
  43564. (function (BABYLON) {
  43565. var Sprite = /** @class */ (function () {
  43566. function Sprite(name, manager) {
  43567. this.name = name;
  43568. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43569. this.width = 1.0;
  43570. this.height = 1.0;
  43571. this.angle = 0;
  43572. this.cellIndex = 0;
  43573. this.invertU = 0;
  43574. this.invertV = 0;
  43575. this.animations = new Array();
  43576. this.isPickable = false;
  43577. this._animationStarted = false;
  43578. this._loopAnimation = false;
  43579. this._fromIndex = 0;
  43580. this._toIndex = 0;
  43581. this._delay = 0;
  43582. this._direction = 1;
  43583. this._time = 0;
  43584. this._manager = manager;
  43585. this._manager.sprites.push(this);
  43586. this.position = BABYLON.Vector3.Zero();
  43587. }
  43588. Object.defineProperty(Sprite.prototype, "size", {
  43589. get: function () {
  43590. return this.width;
  43591. },
  43592. set: function (value) {
  43593. this.width = value;
  43594. this.height = value;
  43595. },
  43596. enumerable: true,
  43597. configurable: true
  43598. });
  43599. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43600. this._fromIndex = from;
  43601. this._toIndex = to;
  43602. this._loopAnimation = loop;
  43603. this._delay = delay;
  43604. this._animationStarted = true;
  43605. this._direction = from < to ? 1 : -1;
  43606. this.cellIndex = from;
  43607. this._time = 0;
  43608. this._onAnimationEnd = onAnimationEnd;
  43609. };
  43610. Sprite.prototype.stopAnimation = function () {
  43611. this._animationStarted = false;
  43612. };
  43613. Sprite.prototype._animate = function (deltaTime) {
  43614. if (!this._animationStarted)
  43615. return;
  43616. this._time += deltaTime;
  43617. if (this._time > this._delay) {
  43618. this._time = this._time % this._delay;
  43619. this.cellIndex += this._direction;
  43620. if (this.cellIndex > this._toIndex) {
  43621. if (this._loopAnimation) {
  43622. this.cellIndex = this._fromIndex;
  43623. }
  43624. else {
  43625. this.cellIndex = this._toIndex;
  43626. this._animationStarted = false;
  43627. if (this._onAnimationEnd) {
  43628. this._onAnimationEnd();
  43629. }
  43630. if (this.disposeWhenFinishedAnimating) {
  43631. this.dispose();
  43632. }
  43633. }
  43634. }
  43635. }
  43636. };
  43637. Sprite.prototype.dispose = function () {
  43638. for (var i = 0; i < this._manager.sprites.length; i++) {
  43639. if (this._manager.sprites[i] == this) {
  43640. this._manager.sprites.splice(i, 1);
  43641. }
  43642. }
  43643. };
  43644. return Sprite;
  43645. }());
  43646. BABYLON.Sprite = Sprite;
  43647. })(BABYLON || (BABYLON = {}));
  43648. //# sourceMappingURL=babylon.sprite.js.map
  43649. var BABYLON;
  43650. (function (BABYLON) {
  43651. var IntersectionInfo = /** @class */ (function () {
  43652. function IntersectionInfo(bu, bv, distance) {
  43653. this.bu = bu;
  43654. this.bv = bv;
  43655. this.distance = distance;
  43656. this.faceId = 0;
  43657. this.subMeshId = 0;
  43658. }
  43659. return IntersectionInfo;
  43660. }());
  43661. BABYLON.IntersectionInfo = IntersectionInfo;
  43662. var PickingInfo = /** @class */ (function () {
  43663. function PickingInfo() {
  43664. this.hit = false;
  43665. this.distance = 0;
  43666. this.pickedPoint = null;
  43667. this.pickedMesh = null;
  43668. this.bu = 0;
  43669. this.bv = 0;
  43670. this.faceId = -1;
  43671. this.subMeshId = 0;
  43672. this.pickedSprite = null;
  43673. }
  43674. // Methods
  43675. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43676. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43677. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43678. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43679. return null;
  43680. }
  43681. var indices = this.pickedMesh.getIndices();
  43682. if (!indices) {
  43683. return null;
  43684. }
  43685. var result;
  43686. if (useVerticesNormals) {
  43687. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43688. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43689. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43690. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43691. normal0 = normal0.scale(this.bu);
  43692. normal1 = normal1.scale(this.bv);
  43693. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43694. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43695. }
  43696. else {
  43697. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43698. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43699. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43700. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43701. var p1p2 = vertex1.subtract(vertex2);
  43702. var p3p2 = vertex3.subtract(vertex2);
  43703. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43704. }
  43705. if (useWorldCoordinates) {
  43706. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43707. }
  43708. return BABYLON.Vector3.Normalize(result);
  43709. };
  43710. PickingInfo.prototype.getTextureCoordinates = function () {
  43711. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43712. return null;
  43713. }
  43714. var indices = this.pickedMesh.getIndices();
  43715. if (!indices) {
  43716. return null;
  43717. }
  43718. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43719. if (!uvs) {
  43720. return null;
  43721. }
  43722. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43723. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43724. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43725. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43726. uv1 = uv1.scale(this.bu);
  43727. uv2 = uv2.scale(this.bv);
  43728. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43729. };
  43730. return PickingInfo;
  43731. }());
  43732. BABYLON.PickingInfo = PickingInfo;
  43733. })(BABYLON || (BABYLON = {}));
  43734. //# sourceMappingURL=babylon.pickingInfo.js.map
  43735. var BABYLON;
  43736. (function (BABYLON) {
  43737. var Ray = /** @class */ (function () {
  43738. function Ray(origin, direction, length) {
  43739. if (length === void 0) { length = Number.MAX_VALUE; }
  43740. this.origin = origin;
  43741. this.direction = direction;
  43742. this.length = length;
  43743. }
  43744. // Methods
  43745. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43746. var d = 0.0;
  43747. var maxValue = Number.MAX_VALUE;
  43748. var inv;
  43749. var min;
  43750. var max;
  43751. var temp;
  43752. if (Math.abs(this.direction.x) < 0.0000001) {
  43753. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43754. return false;
  43755. }
  43756. }
  43757. else {
  43758. inv = 1.0 / this.direction.x;
  43759. min = (minimum.x - this.origin.x) * inv;
  43760. max = (maximum.x - this.origin.x) * inv;
  43761. if (max === -Infinity) {
  43762. max = Infinity;
  43763. }
  43764. if (min > max) {
  43765. temp = min;
  43766. min = max;
  43767. max = temp;
  43768. }
  43769. d = Math.max(min, d);
  43770. maxValue = Math.min(max, maxValue);
  43771. if (d > maxValue) {
  43772. return false;
  43773. }
  43774. }
  43775. if (Math.abs(this.direction.y) < 0.0000001) {
  43776. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43777. return false;
  43778. }
  43779. }
  43780. else {
  43781. inv = 1.0 / this.direction.y;
  43782. min = (minimum.y - this.origin.y) * inv;
  43783. max = (maximum.y - this.origin.y) * inv;
  43784. if (max === -Infinity) {
  43785. max = Infinity;
  43786. }
  43787. if (min > max) {
  43788. temp = min;
  43789. min = max;
  43790. max = temp;
  43791. }
  43792. d = Math.max(min, d);
  43793. maxValue = Math.min(max, maxValue);
  43794. if (d > maxValue) {
  43795. return false;
  43796. }
  43797. }
  43798. if (Math.abs(this.direction.z) < 0.0000001) {
  43799. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43800. return false;
  43801. }
  43802. }
  43803. else {
  43804. inv = 1.0 / this.direction.z;
  43805. min = (minimum.z - this.origin.z) * inv;
  43806. max = (maximum.z - this.origin.z) * inv;
  43807. if (max === -Infinity) {
  43808. max = Infinity;
  43809. }
  43810. if (min > max) {
  43811. temp = min;
  43812. min = max;
  43813. max = temp;
  43814. }
  43815. d = Math.max(min, d);
  43816. maxValue = Math.min(max, maxValue);
  43817. if (d > maxValue) {
  43818. return false;
  43819. }
  43820. }
  43821. return true;
  43822. };
  43823. Ray.prototype.intersectsBox = function (box) {
  43824. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43825. };
  43826. Ray.prototype.intersectsSphere = function (sphere) {
  43827. var x = sphere.center.x - this.origin.x;
  43828. var y = sphere.center.y - this.origin.y;
  43829. var z = sphere.center.z - this.origin.z;
  43830. var pyth = (x * x) + (y * y) + (z * z);
  43831. var rr = sphere.radius * sphere.radius;
  43832. if (pyth <= rr) {
  43833. return true;
  43834. }
  43835. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43836. if (dot < 0.0) {
  43837. return false;
  43838. }
  43839. var temp = pyth - (dot * dot);
  43840. return temp <= rr;
  43841. };
  43842. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43843. if (!this._edge1) {
  43844. this._edge1 = BABYLON.Vector3.Zero();
  43845. this._edge2 = BABYLON.Vector3.Zero();
  43846. this._pvec = BABYLON.Vector3.Zero();
  43847. this._tvec = BABYLON.Vector3.Zero();
  43848. this._qvec = BABYLON.Vector3.Zero();
  43849. }
  43850. vertex1.subtractToRef(vertex0, this._edge1);
  43851. vertex2.subtractToRef(vertex0, this._edge2);
  43852. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43853. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43854. if (det === 0) {
  43855. return null;
  43856. }
  43857. var invdet = 1 / det;
  43858. this.origin.subtractToRef(vertex0, this._tvec);
  43859. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43860. if (bu < 0 || bu > 1.0) {
  43861. return null;
  43862. }
  43863. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43864. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43865. if (bv < 0 || bu + bv > 1.0) {
  43866. return null;
  43867. }
  43868. //check if the distance is longer than the predefined length.
  43869. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43870. if (distance > this.length) {
  43871. return null;
  43872. }
  43873. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43874. };
  43875. Ray.prototype.intersectsPlane = function (plane) {
  43876. var distance;
  43877. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43878. if (Math.abs(result1) < 9.99999997475243E-07) {
  43879. return null;
  43880. }
  43881. else {
  43882. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43883. distance = (-plane.d - result2) / result1;
  43884. if (distance < 0.0) {
  43885. if (distance < -9.99999997475243E-07) {
  43886. return null;
  43887. }
  43888. else {
  43889. return 0;
  43890. }
  43891. }
  43892. return distance;
  43893. }
  43894. };
  43895. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43896. var tm = BABYLON.Tmp.Matrix[0];
  43897. mesh.getWorldMatrix().invertToRef(tm);
  43898. if (this._tmpRay) {
  43899. Ray.TransformToRef(this, tm, this._tmpRay);
  43900. }
  43901. else {
  43902. this._tmpRay = Ray.Transform(this, tm);
  43903. }
  43904. return mesh.intersects(this._tmpRay, fastCheck);
  43905. };
  43906. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43907. if (results) {
  43908. results.length = 0;
  43909. }
  43910. else {
  43911. results = [];
  43912. }
  43913. for (var i = 0; i < meshes.length; i++) {
  43914. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43915. if (pickInfo.hit) {
  43916. results.push(pickInfo);
  43917. }
  43918. }
  43919. results.sort(this._comparePickingInfo);
  43920. return results;
  43921. };
  43922. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43923. if (pickingInfoA.distance < pickingInfoB.distance) {
  43924. return -1;
  43925. }
  43926. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43927. return 1;
  43928. }
  43929. else {
  43930. return 0;
  43931. }
  43932. };
  43933. /**
  43934. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43935. * @param sega the first point of the segment to test the intersection against
  43936. * @param segb the second point of the segment to test the intersection against
  43937. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43938. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43939. */
  43940. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43941. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43942. var u = segb.subtract(sega);
  43943. var v = rsegb.subtract(this.origin);
  43944. var w = sega.subtract(this.origin);
  43945. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43946. var b = BABYLON.Vector3.Dot(u, v);
  43947. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43948. var d = BABYLON.Vector3.Dot(u, w);
  43949. var e = BABYLON.Vector3.Dot(v, w);
  43950. var D = a * c - b * b; // always >= 0
  43951. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43952. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43953. // compute the line parameters of the two closest points
  43954. if (D < Ray.smallnum) {
  43955. sN = 0.0; // force using point P0 on segment S1
  43956. sD = 1.0; // to prevent possible division by 0.0 later
  43957. tN = e;
  43958. tD = c;
  43959. }
  43960. else {
  43961. sN = (b * e - c * d);
  43962. tN = (a * e - b * d);
  43963. if (sN < 0.0) {
  43964. sN = 0.0;
  43965. tN = e;
  43966. tD = c;
  43967. }
  43968. else if (sN > sD) {
  43969. sN = sD;
  43970. tN = e + b;
  43971. tD = c;
  43972. }
  43973. }
  43974. if (tN < 0.0) {
  43975. tN = 0.0;
  43976. // recompute sc for this edge
  43977. if (-d < 0.0) {
  43978. sN = 0.0;
  43979. }
  43980. else if (-d > a)
  43981. sN = sD;
  43982. else {
  43983. sN = -d;
  43984. sD = a;
  43985. }
  43986. }
  43987. else if (tN > tD) {
  43988. tN = tD;
  43989. // recompute sc for this edge
  43990. if ((-d + b) < 0.0) {
  43991. sN = 0;
  43992. }
  43993. else if ((-d + b) > a) {
  43994. sN = sD;
  43995. }
  43996. else {
  43997. sN = (-d + b);
  43998. sD = a;
  43999. }
  44000. }
  44001. // finally do the division to get sc and tc
  44002. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44003. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44004. // get the difference of the two closest points
  44005. var qtc = v.multiplyByFloats(tc, tc, tc);
  44006. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44007. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44008. if (isIntersected) {
  44009. return qtc.length();
  44010. }
  44011. return -1;
  44012. };
  44013. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44014. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44015. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44016. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44017. this.direction.normalize();
  44018. return this;
  44019. };
  44020. // Statics
  44021. Ray.Zero = function () {
  44022. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44023. };
  44024. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44025. var result = Ray.Zero();
  44026. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44027. };
  44028. /**
  44029. * 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
  44030. * transformed to the given world matrix.
  44031. * @param origin The origin point
  44032. * @param end The end point
  44033. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44034. */
  44035. Ray.CreateNewFromTo = function (origin, end, world) {
  44036. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44037. var direction = end.subtract(origin);
  44038. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44039. direction.normalize();
  44040. return Ray.Transform(new Ray(origin, direction, length), world);
  44041. };
  44042. Ray.Transform = function (ray, matrix) {
  44043. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44044. Ray.TransformToRef(ray, matrix, result);
  44045. return result;
  44046. };
  44047. Ray.TransformToRef = function (ray, matrix, result) {
  44048. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44049. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44050. result.length = ray.length;
  44051. var dir = result.direction;
  44052. var len = dir.length();
  44053. if (!(len === 0 || len === 1)) {
  44054. var num = 1.0 / len;
  44055. dir.x *= num;
  44056. dir.y *= num;
  44057. dir.z *= num;
  44058. result.length *= len;
  44059. }
  44060. };
  44061. Ray.smallnum = 0.00000001;
  44062. Ray.rayl = 10e8;
  44063. return Ray;
  44064. }());
  44065. BABYLON.Ray = Ray;
  44066. })(BABYLON || (BABYLON = {}));
  44067. //# sourceMappingURL=babylon.ray.js.map
  44068. var BABYLON;
  44069. (function (BABYLON) {
  44070. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44071. if (boxMin.x > sphereCenter.x + sphereRadius)
  44072. return false;
  44073. if (sphereCenter.x - sphereRadius > boxMax.x)
  44074. return false;
  44075. if (boxMin.y > sphereCenter.y + sphereRadius)
  44076. return false;
  44077. if (sphereCenter.y - sphereRadius > boxMax.y)
  44078. return false;
  44079. if (boxMin.z > sphereCenter.z + sphereRadius)
  44080. return false;
  44081. if (sphereCenter.z - sphereRadius > boxMax.z)
  44082. return false;
  44083. return true;
  44084. };
  44085. var getLowestRoot = (function () {
  44086. var result = { root: 0, found: false };
  44087. return function (a, b, c, maxR) {
  44088. result.root = 0;
  44089. result.found = false;
  44090. var determinant = b * b - 4.0 * a * c;
  44091. if (determinant < 0)
  44092. return result;
  44093. var sqrtD = Math.sqrt(determinant);
  44094. var r1 = (-b - sqrtD) / (2.0 * a);
  44095. var r2 = (-b + sqrtD) / (2.0 * a);
  44096. if (r1 > r2) {
  44097. var temp = r2;
  44098. r2 = r1;
  44099. r1 = temp;
  44100. }
  44101. if (r1 > 0 && r1 < maxR) {
  44102. result.root = r1;
  44103. result.found = true;
  44104. return result;
  44105. }
  44106. if (r2 > 0 && r2 < maxR) {
  44107. result.root = r2;
  44108. result.found = true;
  44109. return result;
  44110. }
  44111. return result;
  44112. };
  44113. })();
  44114. var Collider = /** @class */ (function () {
  44115. function Collider() {
  44116. this.radius = BABYLON.Vector3.One();
  44117. this.retry = 0;
  44118. this.basePointWorld = BABYLON.Vector3.Zero();
  44119. this.velocityWorld = BABYLON.Vector3.Zero();
  44120. this.normalizedVelocity = BABYLON.Vector3.Zero();
  44121. this._collisionPoint = BABYLON.Vector3.Zero();
  44122. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44123. this._tempVector = BABYLON.Vector3.Zero();
  44124. this._tempVector2 = BABYLON.Vector3.Zero();
  44125. this._tempVector3 = BABYLON.Vector3.Zero();
  44126. this._tempVector4 = BABYLON.Vector3.Zero();
  44127. this._edge = BABYLON.Vector3.Zero();
  44128. this._baseToVertex = BABYLON.Vector3.Zero();
  44129. this._destinationPoint = BABYLON.Vector3.Zero();
  44130. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44131. this._displacementVector = BABYLON.Vector3.Zero();
  44132. this._collisionMask = -1;
  44133. }
  44134. Object.defineProperty(Collider.prototype, "collisionMask", {
  44135. get: function () {
  44136. return this._collisionMask;
  44137. },
  44138. set: function (mask) {
  44139. this._collisionMask = !isNaN(mask) ? mask : -1;
  44140. },
  44141. enumerable: true,
  44142. configurable: true
  44143. });
  44144. // Methods
  44145. Collider.prototype._initialize = function (source, dir, e) {
  44146. this.velocity = dir;
  44147. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  44148. this.basePoint = source;
  44149. source.multiplyToRef(this.radius, this.basePointWorld);
  44150. dir.multiplyToRef(this.radius, this.velocityWorld);
  44151. this.velocityWorldLength = this.velocityWorld.length();
  44152. this.epsilon = e;
  44153. this.collisionFound = false;
  44154. };
  44155. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44156. pa.subtractToRef(point, this._tempVector);
  44157. pb.subtractToRef(point, this._tempVector2);
  44158. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44159. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44160. if (d < 0)
  44161. return false;
  44162. pc.subtractToRef(point, this._tempVector3);
  44163. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44164. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44165. if (d < 0)
  44166. return false;
  44167. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44168. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44169. return d >= 0;
  44170. };
  44171. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44172. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  44173. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  44174. if (distance > this.velocityWorldLength + max + sphereRadius) {
  44175. return false;
  44176. }
  44177. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  44178. return false;
  44179. return true;
  44180. };
  44181. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44182. var t0;
  44183. var embeddedInPlane = false;
  44184. //defensive programming, actually not needed.
  44185. if (!trianglePlaneArray) {
  44186. trianglePlaneArray = [];
  44187. }
  44188. if (!trianglePlaneArray[faceIndex]) {
  44189. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44190. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44191. }
  44192. var trianglePlane = trianglePlaneArray[faceIndex];
  44193. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  44194. return;
  44195. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  44196. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  44197. if (normalDotVelocity == 0) {
  44198. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44199. return;
  44200. embeddedInPlane = true;
  44201. t0 = 0;
  44202. }
  44203. else {
  44204. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44205. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44206. if (t0 > t1) {
  44207. var temp = t1;
  44208. t1 = t0;
  44209. t0 = temp;
  44210. }
  44211. if (t0 > 1.0 || t1 < 0.0)
  44212. return;
  44213. if (t0 < 0)
  44214. t0 = 0;
  44215. if (t0 > 1.0)
  44216. t0 = 1.0;
  44217. }
  44218. this._collisionPoint.copyFromFloats(0, 0, 0);
  44219. var found = false;
  44220. var t = 1.0;
  44221. if (!embeddedInPlane) {
  44222. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44223. this.velocity.scaleToRef(t0, this._tempVector);
  44224. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44225. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44226. found = true;
  44227. t = t0;
  44228. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44229. }
  44230. }
  44231. if (!found) {
  44232. var velocitySquaredLength = this.velocity.lengthSquared();
  44233. var a = velocitySquaredLength;
  44234. this.basePoint.subtractToRef(p1, this._tempVector);
  44235. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44236. var c = this._tempVector.lengthSquared() - 1.0;
  44237. var lowestRoot = getLowestRoot(a, b, c, t);
  44238. if (lowestRoot.found) {
  44239. t = lowestRoot.root;
  44240. found = true;
  44241. this._collisionPoint.copyFrom(p1);
  44242. }
  44243. this.basePoint.subtractToRef(p2, this._tempVector);
  44244. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44245. c = this._tempVector.lengthSquared() - 1.0;
  44246. lowestRoot = getLowestRoot(a, b, c, t);
  44247. if (lowestRoot.found) {
  44248. t = lowestRoot.root;
  44249. found = true;
  44250. this._collisionPoint.copyFrom(p2);
  44251. }
  44252. this.basePoint.subtractToRef(p3, this._tempVector);
  44253. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44254. c = this._tempVector.lengthSquared() - 1.0;
  44255. lowestRoot = getLowestRoot(a, b, c, t);
  44256. if (lowestRoot.found) {
  44257. t = lowestRoot.root;
  44258. found = true;
  44259. this._collisionPoint.copyFrom(p3);
  44260. }
  44261. p2.subtractToRef(p1, this._edge);
  44262. p1.subtractToRef(this.basePoint, this._baseToVertex);
  44263. var edgeSquaredLength = this._edge.lengthSquared();
  44264. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44265. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44266. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44267. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44268. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44269. lowestRoot = getLowestRoot(a, b, c, t);
  44270. if (lowestRoot.found) {
  44271. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44272. if (f >= 0.0 && f <= 1.0) {
  44273. t = lowestRoot.root;
  44274. found = true;
  44275. this._edge.scaleInPlace(f);
  44276. p1.addToRef(this._edge, this._collisionPoint);
  44277. }
  44278. }
  44279. p3.subtractToRef(p2, this._edge);
  44280. p2.subtractToRef(this.basePoint, this._baseToVertex);
  44281. edgeSquaredLength = this._edge.lengthSquared();
  44282. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44283. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44284. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44285. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44286. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44287. lowestRoot = getLowestRoot(a, b, c, t);
  44288. if (lowestRoot.found) {
  44289. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44290. if (f >= 0.0 && f <= 1.0) {
  44291. t = lowestRoot.root;
  44292. found = true;
  44293. this._edge.scaleInPlace(f);
  44294. p2.addToRef(this._edge, this._collisionPoint);
  44295. }
  44296. }
  44297. p1.subtractToRef(p3, this._edge);
  44298. p3.subtractToRef(this.basePoint, this._baseToVertex);
  44299. edgeSquaredLength = this._edge.lengthSquared();
  44300. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44301. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44302. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44303. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44304. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44305. lowestRoot = getLowestRoot(a, b, c, t);
  44306. if (lowestRoot.found) {
  44307. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44308. if (f >= 0.0 && f <= 1.0) {
  44309. t = lowestRoot.root;
  44310. found = true;
  44311. this._edge.scaleInPlace(f);
  44312. p3.addToRef(this._edge, this._collisionPoint);
  44313. }
  44314. }
  44315. }
  44316. if (found) {
  44317. var distToCollision = t * this.velocity.length();
  44318. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  44319. if (!this.intersectionPoint) {
  44320. this.intersectionPoint = this._collisionPoint.clone();
  44321. }
  44322. else {
  44323. this.intersectionPoint.copyFrom(this._collisionPoint);
  44324. }
  44325. this.nearestDistance = distToCollision;
  44326. this.collisionFound = true;
  44327. }
  44328. }
  44329. };
  44330. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44331. for (var i = indexStart; i < indexEnd; i += 3) {
  44332. var p1 = pts[indices[i] - decal];
  44333. var p2 = pts[indices[i + 1] - decal];
  44334. var p3 = pts[indices[i + 2] - decal];
  44335. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44336. }
  44337. };
  44338. Collider.prototype._getResponse = function (pos, vel) {
  44339. pos.addToRef(vel, this._destinationPoint);
  44340. vel.scaleInPlace((this.nearestDistance / vel.length()));
  44341. this.basePoint.addToRef(vel, pos);
  44342. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44343. this._slidePlaneNormal.normalize();
  44344. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  44345. pos.addInPlace(this._displacementVector);
  44346. this.intersectionPoint.addInPlace(this._displacementVector);
  44347. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44348. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44349. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44350. };
  44351. return Collider;
  44352. }());
  44353. BABYLON.Collider = Collider;
  44354. })(BABYLON || (BABYLON = {}));
  44355. //# sourceMappingURL=babylon.collider.js.map
  44356. var BABYLON;
  44357. (function (BABYLON) {
  44358. //WebWorker code will be inserted to this variable.
  44359. BABYLON.CollisionWorker = "";
  44360. var WorkerTaskType;
  44361. (function (WorkerTaskType) {
  44362. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44363. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44364. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44365. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44366. var WorkerReplyType;
  44367. (function (WorkerReplyType) {
  44368. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44369. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44370. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44371. var CollisionCoordinatorWorker = /** @class */ (function () {
  44372. function CollisionCoordinatorWorker() {
  44373. var _this = this;
  44374. this._scaledPosition = BABYLON.Vector3.Zero();
  44375. this._scaledVelocity = BABYLON.Vector3.Zero();
  44376. this.onMeshUpdated = function (transformNode) {
  44377. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  44378. };
  44379. this.onGeometryUpdated = function (geometry) {
  44380. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44381. };
  44382. this._afterRender = function () {
  44383. if (!_this._init)
  44384. return;
  44385. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44386. return;
  44387. }
  44388. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44389. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44390. if (_this._runningUpdated > 4) {
  44391. return;
  44392. }
  44393. ++_this._runningUpdated;
  44394. var payload = {
  44395. updatedMeshes: _this._addUpdateMeshesList,
  44396. updatedGeometries: _this._addUpdateGeometriesList,
  44397. removedGeometries: _this._toRemoveGeometryArray,
  44398. removedMeshes: _this._toRemoveMeshesArray
  44399. };
  44400. var message = {
  44401. payload: payload,
  44402. taskType: WorkerTaskType.UPDATE
  44403. };
  44404. var serializable = [];
  44405. for (var id in payload.updatedGeometries) {
  44406. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44407. //prepare transferables
  44408. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44409. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44410. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44411. }
  44412. }
  44413. _this._worker.postMessage(message, serializable);
  44414. _this._addUpdateMeshesList = {};
  44415. _this._addUpdateGeometriesList = {};
  44416. _this._toRemoveGeometryArray = [];
  44417. _this._toRemoveMeshesArray = [];
  44418. };
  44419. this._onMessageFromWorker = function (e) {
  44420. var returnData = e.data;
  44421. if (returnData.error != WorkerReplyType.SUCCESS) {
  44422. //TODO what errors can be returned from the worker?
  44423. BABYLON.Tools.Warn("error returned from worker!");
  44424. return;
  44425. }
  44426. switch (returnData.taskType) {
  44427. case WorkerTaskType.INIT:
  44428. _this._init = true;
  44429. //Update the worked with ALL of the scene's current state
  44430. _this._scene.meshes.forEach(function (mesh) {
  44431. _this.onMeshAdded(mesh);
  44432. });
  44433. _this._scene.getGeometries().forEach(function (geometry) {
  44434. _this.onGeometryAdded(geometry);
  44435. });
  44436. break;
  44437. case WorkerTaskType.UPDATE:
  44438. _this._runningUpdated--;
  44439. break;
  44440. case WorkerTaskType.COLLIDE:
  44441. var returnPayload = returnData.payload;
  44442. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44443. return;
  44444. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44445. if (callback) {
  44446. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44447. if (mesh) {
  44448. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44449. }
  44450. }
  44451. //cleanup
  44452. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44453. break;
  44454. }
  44455. };
  44456. this._collisionsCallbackArray = [];
  44457. this._init = false;
  44458. this._runningUpdated = 0;
  44459. this._addUpdateMeshesList = {};
  44460. this._addUpdateGeometriesList = {};
  44461. this._toRemoveGeometryArray = [];
  44462. this._toRemoveMeshesArray = [];
  44463. }
  44464. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44465. if (!this._init)
  44466. return;
  44467. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44468. return;
  44469. position.divideToRef(collider.radius, this._scaledPosition);
  44470. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44471. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44472. var payload = {
  44473. collider: {
  44474. position: this._scaledPosition.asArray(),
  44475. velocity: this._scaledVelocity.asArray(),
  44476. radius: collider.radius.asArray()
  44477. },
  44478. collisionId: collisionIndex,
  44479. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44480. maximumRetry: maximumRetry
  44481. };
  44482. var message = {
  44483. payload: payload,
  44484. taskType: WorkerTaskType.COLLIDE
  44485. };
  44486. this._worker.postMessage(message);
  44487. };
  44488. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44489. this._scene = scene;
  44490. this._scene.registerAfterRender(this._afterRender);
  44491. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44492. this._worker = new Worker(workerUrl);
  44493. this._worker.onmessage = this._onMessageFromWorker;
  44494. var message = {
  44495. payload: {},
  44496. taskType: WorkerTaskType.INIT
  44497. };
  44498. this._worker.postMessage(message);
  44499. };
  44500. CollisionCoordinatorWorker.prototype.destroy = function () {
  44501. this._scene.unregisterAfterRender(this._afterRender);
  44502. this._worker.terminate();
  44503. };
  44504. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44505. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44506. this.onMeshUpdated(mesh);
  44507. };
  44508. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44509. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44510. };
  44511. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44512. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44513. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44514. this.onGeometryUpdated(geometry);
  44515. };
  44516. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44517. this._toRemoveGeometryArray.push(geometry.id);
  44518. };
  44519. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44520. var submeshes = [];
  44521. if (mesh.subMeshes) {
  44522. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44523. var boundingInfo = sm.getBoundingInfo();
  44524. return {
  44525. position: idx,
  44526. verticesStart: sm.verticesStart,
  44527. verticesCount: sm.verticesCount,
  44528. indexStart: sm.indexStart,
  44529. indexCount: sm.indexCount,
  44530. hasMaterial: !!sm.getMaterial(),
  44531. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44532. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44533. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44534. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44535. };
  44536. });
  44537. }
  44538. var geometryId = null;
  44539. if (mesh instanceof BABYLON.Mesh) {
  44540. var geometry = mesh.geometry;
  44541. geometryId = geometry ? geometry.id : null;
  44542. }
  44543. else if (mesh instanceof BABYLON.InstancedMesh) {
  44544. var geometry = mesh.sourceMesh.geometry;
  44545. geometryId = geometry ? geometry.id : null;
  44546. }
  44547. var boundingInfo = mesh.getBoundingInfo();
  44548. return {
  44549. uniqueId: mesh.uniqueId,
  44550. id: mesh.id,
  44551. name: mesh.name,
  44552. geometryId: geometryId,
  44553. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44554. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44555. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44556. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44557. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44558. subMeshes: submeshes,
  44559. checkCollisions: mesh.checkCollisions
  44560. };
  44561. };
  44562. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44563. return {
  44564. id: geometry.id,
  44565. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44566. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44567. indices: new Uint32Array(geometry.getIndices() || []),
  44568. };
  44569. };
  44570. return CollisionCoordinatorWorker;
  44571. }());
  44572. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44573. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44574. function CollisionCoordinatorLegacy() {
  44575. this._scaledPosition = BABYLON.Vector3.Zero();
  44576. this._scaledVelocity = BABYLON.Vector3.Zero();
  44577. this._finalPosition = BABYLON.Vector3.Zero();
  44578. }
  44579. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44580. position.divideToRef(collider.radius, this._scaledPosition);
  44581. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44582. collider.collidedMesh = null;
  44583. collider.retry = 0;
  44584. collider.initialVelocity = this._scaledVelocity;
  44585. collider.initialPosition = this._scaledPosition;
  44586. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44587. this._finalPosition.multiplyInPlace(collider.radius);
  44588. //run the callback
  44589. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44590. };
  44591. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44592. this._scene = scene;
  44593. };
  44594. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44595. //Legacy need no destruction method.
  44596. };
  44597. //No update in legacy mode
  44598. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44599. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44600. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44601. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44602. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44603. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44604. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44605. if (excludedMesh === void 0) { excludedMesh = null; }
  44606. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44607. if (collider.retry >= maximumRetry) {
  44608. finalPosition.copyFrom(position);
  44609. return;
  44610. }
  44611. // Check if this is a mesh else camera or -1
  44612. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44613. collider._initialize(position, velocity, closeDistance);
  44614. // Check all meshes
  44615. for (var index = 0; index < this._scene.meshes.length; index++) {
  44616. var mesh = this._scene.meshes[index];
  44617. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44618. mesh._checkCollision(collider);
  44619. }
  44620. }
  44621. if (!collider.collisionFound) {
  44622. position.addToRef(velocity, finalPosition);
  44623. return;
  44624. }
  44625. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44626. collider._getResponse(position, velocity);
  44627. }
  44628. if (velocity.length() <= closeDistance) {
  44629. finalPosition.copyFrom(position);
  44630. return;
  44631. }
  44632. collider.retry++;
  44633. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44634. };
  44635. return CollisionCoordinatorLegacy;
  44636. }());
  44637. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44638. })(BABYLON || (BABYLON = {}));
  44639. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44640. var BABYLON;
  44641. (function (BABYLON) {
  44642. var Particle = /** @class */ (function () {
  44643. function Particle(particleSystem) {
  44644. this.particleSystem = particleSystem;
  44645. this.position = BABYLON.Vector3.Zero();
  44646. this.direction = BABYLON.Vector3.Zero();
  44647. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44648. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44649. this.lifeTime = 1.0;
  44650. this.age = 0;
  44651. this.size = 0;
  44652. this.angle = 0;
  44653. this.angularSpeed = 0;
  44654. this._currentFrameCounter = 0;
  44655. this.cellIndex = 0;
  44656. if (!this.particleSystem.isAnimationSheetEnabled) {
  44657. return;
  44658. }
  44659. this.cellIndex = this.particleSystem.startSpriteCellID;
  44660. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44661. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44662. }
  44663. else {
  44664. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44665. }
  44666. }
  44667. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44668. // (ageOffset / scaledUpdateSpeed) / available cells
  44669. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44670. this._currentFrameCounter += scaledUpdateSpeed;
  44671. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44672. this._currentFrameCounter = 0;
  44673. this.cellIndex++;
  44674. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44675. this.cellIndex = this.particleSystem.endSpriteCellID;
  44676. }
  44677. }
  44678. };
  44679. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44680. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44681. this.cellIndex++;
  44682. this._currentFrameCounter = 0;
  44683. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44684. if (this.particleSystem.spriteCellLoop) {
  44685. this.cellIndex = this.particleSystem.startSpriteCellID;
  44686. }
  44687. else {
  44688. this.cellIndex = this.particleSystem.endSpriteCellID;
  44689. }
  44690. }
  44691. }
  44692. else {
  44693. this._currentFrameCounter++;
  44694. }
  44695. };
  44696. Particle.prototype.copyTo = function (other) {
  44697. other.position.copyFrom(this.position);
  44698. other.direction.copyFrom(this.direction);
  44699. other.color.copyFrom(this.color);
  44700. other.colorStep.copyFrom(this.colorStep);
  44701. other.lifeTime = this.lifeTime;
  44702. other.age = this.age;
  44703. other.size = this.size;
  44704. other.angle = this.angle;
  44705. other.angularSpeed = this.angularSpeed;
  44706. other.particleSystem = this.particleSystem;
  44707. other.cellIndex = this.cellIndex;
  44708. };
  44709. return Particle;
  44710. }());
  44711. BABYLON.Particle = Particle;
  44712. })(BABYLON || (BABYLON = {}));
  44713. //# sourceMappingURL=babylon.particle.js.map
  44714. var BABYLON;
  44715. (function (BABYLON) {
  44716. var randomNumber = function (min, max) {
  44717. if (min === max) {
  44718. return (min);
  44719. }
  44720. var random = Math.random();
  44721. return ((random * (max - min)) + min);
  44722. };
  44723. var ParticleSystem = /** @class */ (function () {
  44724. // end of sheet animation
  44725. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44726. if (customEffect === void 0) { customEffect = null; }
  44727. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44728. if (epsilon === void 0) { epsilon = 0.01; }
  44729. var _this = this;
  44730. this.name = name;
  44731. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44732. // Members
  44733. this.animations = [];
  44734. this.renderingGroupId = 0;
  44735. this.emitter = null;
  44736. this.emitRate = 10;
  44737. this.manualEmitCount = -1;
  44738. this.updateSpeed = 0.01;
  44739. this.targetStopDuration = 0;
  44740. this.disposeOnStop = false;
  44741. this.minEmitPower = 1;
  44742. this.maxEmitPower = 1;
  44743. this.minLifeTime = 1;
  44744. this.maxLifeTime = 1;
  44745. this.minSize = 1;
  44746. this.maxSize = 1;
  44747. this.minAngularSpeed = 0;
  44748. this.maxAngularSpeed = 0;
  44749. this.layerMask = 0x0FFFFFFF;
  44750. this.customShader = null;
  44751. this.preventAutoStart = false;
  44752. /**
  44753. * An event triggered when the system is disposed.
  44754. * @type {BABYLON.Observable}
  44755. */
  44756. this.onDisposeObservable = new BABYLON.Observable();
  44757. this.onAnimationEnd = null;
  44758. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44759. this.forceDepthWrite = false;
  44760. this.gravity = BABYLON.Vector3.Zero();
  44761. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44762. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44763. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44764. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44765. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44766. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44767. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44768. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44769. this.particles = new Array();
  44770. this._stockParticles = new Array();
  44771. this._newPartsExcess = 0;
  44772. this._vertexBuffers = {};
  44773. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44774. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44775. this._scaledDirection = BABYLON.Vector3.Zero();
  44776. this._scaledGravity = BABYLON.Vector3.Zero();
  44777. this._currentRenderId = -1;
  44778. this._started = false;
  44779. this._stopped = false;
  44780. this._actualFrame = 0;
  44781. // sheet animation
  44782. this.startSpriteCellID = 0;
  44783. this.endSpriteCellID = 0;
  44784. this.spriteCellLoop = true;
  44785. this.spriteCellChangeSpeed = 0;
  44786. this.spriteCellWidth = 0;
  44787. this.spriteCellHeight = 0;
  44788. this._vertexBufferSize = 11;
  44789. this.appendParticleVertexes = null;
  44790. this.id = name;
  44791. this._capacity = capacity;
  44792. this._epsilon = epsilon;
  44793. if (_isAnimationSheetEnabled) {
  44794. this._vertexBufferSize = 12;
  44795. }
  44796. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44797. this._customEffect = customEffect;
  44798. scene.particleSystems.push(this);
  44799. this._createIndexBuffer();
  44800. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44801. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44802. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44803. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44804. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44805. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44806. if (this._isAnimationSheetEnabled) {
  44807. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44808. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44809. }
  44810. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44811. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44812. this._vertexBuffers["options"] = options;
  44813. // Default behaviors
  44814. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44815. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44816. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44817. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44818. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44819. };
  44820. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44821. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44822. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44823. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44825. };
  44826. this.updateFunction = function (particles) {
  44827. for (var index = 0; index < particles.length; index++) {
  44828. var particle = particles[index];
  44829. particle.age += _this._scaledUpdateSpeed;
  44830. if (particle.age >= particle.lifeTime) {
  44831. _this.recycleParticle(particle);
  44832. index--;
  44833. continue;
  44834. }
  44835. else {
  44836. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44837. particle.color.addInPlace(_this._scaledColorStep);
  44838. if (particle.color.a < 0)
  44839. particle.color.a = 0;
  44840. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44841. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44842. particle.position.addInPlace(_this._scaledDirection);
  44843. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44844. particle.direction.addInPlace(_this._scaledGravity);
  44845. if (_this._isAnimationSheetEnabled) {
  44846. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44847. }
  44848. }
  44849. }
  44850. };
  44851. }
  44852. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44853. set: function (callback) {
  44854. if (this._onDisposeObserver) {
  44855. this.onDisposeObservable.remove(this._onDisposeObserver);
  44856. }
  44857. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44858. },
  44859. enumerable: true,
  44860. configurable: true
  44861. });
  44862. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44863. get: function () {
  44864. return this._isAnimationSheetEnabled;
  44865. },
  44866. enumerable: true,
  44867. configurable: true
  44868. });
  44869. ParticleSystem.prototype._createIndexBuffer = function () {
  44870. var indices = [];
  44871. var index = 0;
  44872. for (var count = 0; count < this._capacity; count++) {
  44873. indices.push(index);
  44874. indices.push(index + 1);
  44875. indices.push(index + 2);
  44876. indices.push(index);
  44877. indices.push(index + 2);
  44878. indices.push(index + 3);
  44879. index += 4;
  44880. }
  44881. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44882. };
  44883. ParticleSystem.prototype.recycleParticle = function (particle) {
  44884. var lastParticle = this.particles.pop();
  44885. if (lastParticle !== particle) {
  44886. lastParticle.copyTo(particle);
  44887. this._stockParticles.push(lastParticle);
  44888. }
  44889. };
  44890. ParticleSystem.prototype.getCapacity = function () {
  44891. return this._capacity;
  44892. };
  44893. ParticleSystem.prototype.isAlive = function () {
  44894. return this._alive;
  44895. };
  44896. ParticleSystem.prototype.isStarted = function () {
  44897. return this._started;
  44898. };
  44899. ParticleSystem.prototype.start = function () {
  44900. this._started = true;
  44901. this._stopped = false;
  44902. this._actualFrame = 0;
  44903. };
  44904. ParticleSystem.prototype.stop = function () {
  44905. this._stopped = true;
  44906. };
  44907. // animation sheet
  44908. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44909. var offset = index * this._vertexBufferSize;
  44910. this._vertexData[offset] = particle.position.x;
  44911. this._vertexData[offset + 1] = particle.position.y;
  44912. this._vertexData[offset + 2] = particle.position.z;
  44913. this._vertexData[offset + 3] = particle.color.r;
  44914. this._vertexData[offset + 4] = particle.color.g;
  44915. this._vertexData[offset + 5] = particle.color.b;
  44916. this._vertexData[offset + 6] = particle.color.a;
  44917. this._vertexData[offset + 7] = particle.angle;
  44918. this._vertexData[offset + 8] = particle.size;
  44919. this._vertexData[offset + 9] = offsetX;
  44920. this._vertexData[offset + 10] = offsetY;
  44921. };
  44922. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44923. if (offsetX === 0)
  44924. offsetX = this._epsilon;
  44925. else if (offsetX === 1)
  44926. offsetX = 1 - this._epsilon;
  44927. if (offsetY === 0)
  44928. offsetY = this._epsilon;
  44929. else if (offsetY === 1)
  44930. offsetY = 1 - this._epsilon;
  44931. var offset = index * this._vertexBufferSize;
  44932. this._vertexData[offset] = particle.position.x;
  44933. this._vertexData[offset + 1] = particle.position.y;
  44934. this._vertexData[offset + 2] = particle.position.z;
  44935. this._vertexData[offset + 3] = particle.color.r;
  44936. this._vertexData[offset + 4] = particle.color.g;
  44937. this._vertexData[offset + 5] = particle.color.b;
  44938. this._vertexData[offset + 6] = particle.color.a;
  44939. this._vertexData[offset + 7] = particle.angle;
  44940. this._vertexData[offset + 8] = particle.size;
  44941. this._vertexData[offset + 9] = offsetX;
  44942. this._vertexData[offset + 10] = offsetY;
  44943. this._vertexData[offset + 11] = particle.cellIndex;
  44944. };
  44945. ParticleSystem.prototype._update = function (newParticles) {
  44946. // Update current
  44947. this._alive = this.particles.length > 0;
  44948. this.updateFunction(this.particles);
  44949. // Add new ones
  44950. var worldMatrix;
  44951. if (this.emitter.position) {
  44952. var emitterMesh = this.emitter;
  44953. worldMatrix = emitterMesh.getWorldMatrix();
  44954. }
  44955. else {
  44956. var emitterPosition = this.emitter;
  44957. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44958. }
  44959. var particle;
  44960. for (var index = 0; index < newParticles; index++) {
  44961. if (this.particles.length === this._capacity) {
  44962. break;
  44963. }
  44964. if (this._stockParticles.length !== 0) {
  44965. particle = this._stockParticles.pop();
  44966. particle.age = 0;
  44967. particle.cellIndex = this.startSpriteCellID;
  44968. }
  44969. else {
  44970. particle = new BABYLON.Particle(this);
  44971. }
  44972. this.particles.push(particle);
  44973. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44974. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44975. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44976. particle.size = randomNumber(this.minSize, this.maxSize);
  44977. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44978. this.startPositionFunction(worldMatrix, particle.position, particle);
  44979. var step = randomNumber(0, 1.0);
  44980. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44981. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44982. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44983. }
  44984. };
  44985. ParticleSystem.prototype._getEffect = function () {
  44986. if (this._customEffect) {
  44987. return this._customEffect;
  44988. }
  44989. ;
  44990. var defines = [];
  44991. if (this._scene.clipPlane) {
  44992. defines.push("#define CLIPPLANE");
  44993. }
  44994. if (this._isAnimationSheetEnabled) {
  44995. defines.push("#define ANIMATESHEET");
  44996. }
  44997. // Effect
  44998. var join = defines.join("\n");
  44999. if (this._cachedDefines !== join) {
  45000. this._cachedDefines = join;
  45001. var attributesNamesOrOptions;
  45002. var effectCreationOption;
  45003. if (this._isAnimationSheetEnabled) {
  45004. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45005. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45006. }
  45007. else {
  45008. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45009. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45010. }
  45011. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45012. }
  45013. return this._effect;
  45014. };
  45015. ParticleSystem.prototype.animate = function () {
  45016. if (!this._started)
  45017. return;
  45018. var effect = this._getEffect();
  45019. // Check
  45020. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45021. return;
  45022. if (this._currentRenderId === this._scene.getRenderId()) {
  45023. return;
  45024. }
  45025. this._currentRenderId = this._scene.getRenderId();
  45026. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45027. // determine the number of particles we need to create
  45028. var newParticles;
  45029. if (this.manualEmitCount > -1) {
  45030. newParticles = this.manualEmitCount;
  45031. this._newPartsExcess = 0;
  45032. this.manualEmitCount = 0;
  45033. }
  45034. else {
  45035. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45036. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45037. }
  45038. if (this._newPartsExcess > 1.0) {
  45039. newParticles += this._newPartsExcess >> 0;
  45040. this._newPartsExcess -= this._newPartsExcess >> 0;
  45041. }
  45042. this._alive = false;
  45043. if (!this._stopped) {
  45044. this._actualFrame += this._scaledUpdateSpeed;
  45045. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45046. this.stop();
  45047. }
  45048. else {
  45049. newParticles = 0;
  45050. }
  45051. this._update(newParticles);
  45052. // Stopped?
  45053. if (this._stopped) {
  45054. if (!this._alive) {
  45055. this._started = false;
  45056. if (this.onAnimationEnd) {
  45057. this.onAnimationEnd();
  45058. }
  45059. if (this.disposeOnStop) {
  45060. this._scene._toBeDisposed.push(this);
  45061. }
  45062. }
  45063. }
  45064. // Animation sheet
  45065. if (this._isAnimationSheetEnabled) {
  45066. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45067. }
  45068. else {
  45069. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45070. }
  45071. // Update VBO
  45072. var offset = 0;
  45073. for (var index = 0; index < this.particles.length; index++) {
  45074. var particle = this.particles[index];
  45075. this.appendParticleVertexes(offset, particle);
  45076. offset += 4;
  45077. }
  45078. if (this._vertexBuffer) {
  45079. this._vertexBuffer.update(this._vertexData);
  45080. }
  45081. };
  45082. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45083. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45084. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45085. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45086. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45087. };
  45088. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45089. this._appendParticleVertex(offset++, particle, 0, 0);
  45090. this._appendParticleVertex(offset++, particle, 1, 0);
  45091. this._appendParticleVertex(offset++, particle, 1, 1);
  45092. this._appendParticleVertex(offset++, particle, 0, 1);
  45093. };
  45094. ParticleSystem.prototype.rebuild = function () {
  45095. this._createIndexBuffer();
  45096. if (this._vertexBuffer) {
  45097. this._vertexBuffer._rebuild();
  45098. }
  45099. };
  45100. ParticleSystem.prototype.render = function () {
  45101. var effect = this._getEffect();
  45102. // Check
  45103. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45104. return 0;
  45105. var engine = this._scene.getEngine();
  45106. // Render
  45107. engine.enableEffect(effect);
  45108. engine.setState(false);
  45109. var viewMatrix = this._scene.getViewMatrix();
  45110. effect.setTexture("diffuseSampler", this.particleTexture);
  45111. effect.setMatrix("view", viewMatrix);
  45112. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45113. if (this._isAnimationSheetEnabled) {
  45114. var baseSize = this.particleTexture.getBaseSize();
  45115. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45116. }
  45117. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45118. if (this._scene.clipPlane) {
  45119. var clipPlane = this._scene.clipPlane;
  45120. var invView = viewMatrix.clone();
  45121. invView.invert();
  45122. effect.setMatrix("invView", invView);
  45123. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45124. }
  45125. // VBOs
  45126. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45127. // Draw order
  45128. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45129. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45130. }
  45131. else {
  45132. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45133. }
  45134. if (this.forceDepthWrite) {
  45135. engine.setDepthWrite(true);
  45136. }
  45137. engine.draw(true, 0, this.particles.length * 6);
  45138. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45139. return this.particles.length;
  45140. };
  45141. ParticleSystem.prototype.dispose = function () {
  45142. if (this._vertexBuffer) {
  45143. this._vertexBuffer.dispose();
  45144. this._vertexBuffer = null;
  45145. }
  45146. if (this._indexBuffer) {
  45147. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45148. this._indexBuffer = null;
  45149. }
  45150. if (this.particleTexture) {
  45151. this.particleTexture.dispose();
  45152. this.particleTexture = null;
  45153. }
  45154. // Remove from scene
  45155. var index = this._scene.particleSystems.indexOf(this);
  45156. if (index > -1) {
  45157. this._scene.particleSystems.splice(index, 1);
  45158. }
  45159. // Callback
  45160. this.onDisposeObservable.notifyObservers(this);
  45161. this.onDisposeObservable.clear();
  45162. };
  45163. // Clone
  45164. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45165. var custom = null;
  45166. var program = null;
  45167. if (this.customShader != null) {
  45168. program = this.customShader;
  45169. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45170. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45171. }
  45172. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45173. result.customShader = program;
  45174. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45175. if (newEmitter === undefined) {
  45176. newEmitter = this.emitter;
  45177. }
  45178. result.emitter = newEmitter;
  45179. if (this.particleTexture) {
  45180. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45181. }
  45182. if (!this.preventAutoStart) {
  45183. result.start();
  45184. }
  45185. return result;
  45186. };
  45187. ParticleSystem.prototype.serialize = function () {
  45188. var serializationObject = {};
  45189. serializationObject.name = this.name;
  45190. serializationObject.id = this.id;
  45191. // Emitter
  45192. if (this.emitter.position) {
  45193. var emitterMesh = this.emitter;
  45194. serializationObject.emitterId = emitterMesh.id;
  45195. }
  45196. else {
  45197. var emitterPosition = this.emitter;
  45198. serializationObject.emitter = emitterPosition.asArray();
  45199. }
  45200. serializationObject.capacity = this.getCapacity();
  45201. if (this.particleTexture) {
  45202. serializationObject.textureName = this.particleTexture.name;
  45203. }
  45204. // Animations
  45205. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45206. // Particle system
  45207. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45208. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45209. serializationObject.minSize = this.minSize;
  45210. serializationObject.maxSize = this.maxSize;
  45211. serializationObject.minEmitPower = this.minEmitPower;
  45212. serializationObject.maxEmitPower = this.maxEmitPower;
  45213. serializationObject.minLifeTime = this.minLifeTime;
  45214. serializationObject.maxLifeTime = this.maxLifeTime;
  45215. serializationObject.emitRate = this.emitRate;
  45216. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45217. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45218. serializationObject.gravity = this.gravity.asArray();
  45219. serializationObject.direction1 = this.direction1.asArray();
  45220. serializationObject.direction2 = this.direction2.asArray();
  45221. serializationObject.color1 = this.color1.asArray();
  45222. serializationObject.color2 = this.color2.asArray();
  45223. serializationObject.colorDead = this.colorDead.asArray();
  45224. serializationObject.updateSpeed = this.updateSpeed;
  45225. serializationObject.targetStopDuration = this.targetStopDuration;
  45226. serializationObject.textureMask = this.textureMask.asArray();
  45227. serializationObject.blendMode = this.blendMode;
  45228. serializationObject.customShader = this.customShader;
  45229. serializationObject.preventAutoStart = this.preventAutoStart;
  45230. return serializationObject;
  45231. };
  45232. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45233. var name = parsedParticleSystem.name;
  45234. var custom = null;
  45235. var program = null;
  45236. if (parsedParticleSystem.customShader) {
  45237. program = parsedParticleSystem.customShader;
  45238. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45239. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45240. }
  45241. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  45242. particleSystem.customShader = program;
  45243. if (parsedParticleSystem.id) {
  45244. particleSystem.id = parsedParticleSystem.id;
  45245. }
  45246. // Auto start
  45247. if (parsedParticleSystem.preventAutoStart) {
  45248. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45249. }
  45250. // Texture
  45251. if (parsedParticleSystem.textureName) {
  45252. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45253. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45254. }
  45255. // Emitter
  45256. if (parsedParticleSystem.emitterId) {
  45257. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45258. }
  45259. else {
  45260. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45261. }
  45262. // Animations
  45263. if (parsedParticleSystem.animations) {
  45264. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45265. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45266. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45267. }
  45268. }
  45269. if (parsedParticleSystem.autoAnimate) {
  45270. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45271. }
  45272. // Particle system
  45273. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45274. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45275. particleSystem.minSize = parsedParticleSystem.minSize;
  45276. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45277. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45278. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45279. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45280. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45281. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45282. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45283. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45284. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45285. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45286. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45287. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45288. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45289. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45290. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45291. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45292. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45293. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45294. if (!particleSystem.preventAutoStart) {
  45295. particleSystem.start();
  45296. }
  45297. return particleSystem;
  45298. };
  45299. // Statics
  45300. ParticleSystem.BLENDMODE_ONEONE = 0;
  45301. ParticleSystem.BLENDMODE_STANDARD = 1;
  45302. return ParticleSystem;
  45303. }());
  45304. BABYLON.ParticleSystem = ParticleSystem;
  45305. })(BABYLON || (BABYLON = {}));
  45306. //# sourceMappingURL=babylon.particleSystem.js.map
  45307. var BABYLON;
  45308. (function (BABYLON) {
  45309. var GPUParticleSystem = /** @class */ (function () {
  45310. function GPUParticleSystem(name, capacity, scene) {
  45311. this.name = name;
  45312. this.emitter = null;
  45313. this.renderingGroupId = 0;
  45314. this.layerMask = 0x0FFFFFFF; // TODO
  45315. this._updateVertexBuffers = {};
  45316. this._renderVertexBuffers = {};
  45317. this._currentRenderId = -1;
  45318. this._started = true;
  45319. /**
  45320. * An event triggered when the system is disposed.
  45321. * @type {BABYLON.Observable}
  45322. */
  45323. this.onDisposeObservable = new BABYLON.Observable();
  45324. this.id = name;
  45325. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45326. this._capacity = capacity;
  45327. this._engine = this._scene.getEngine();
  45328. this._scene.particleSystems.push(this);
  45329. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  45330. var updateEffectOptions = {
  45331. attributes: ["position", "age", "life", "velocity"],
  45332. uniformsNames: [],
  45333. uniformBuffersNames: [],
  45334. samplers: [],
  45335. defines: "",
  45336. fallbacks: null,
  45337. onCompiled: null,
  45338. onError: null,
  45339. indexParameters: null,
  45340. maxSimultaneousLights: 0,
  45341. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  45342. };
  45343. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  45344. }
  45345. GPUParticleSystem.prototype.isStarted = function () {
  45346. return this._started;
  45347. };
  45348. GPUParticleSystem.prototype.start = function () {
  45349. this._started = true;
  45350. };
  45351. GPUParticleSystem.prototype.stop = function () {
  45352. this._started = false;
  45353. };
  45354. GPUParticleSystem.prototype.animate = function () {
  45355. // Do nothing
  45356. };
  45357. GPUParticleSystem.prototype._initialize = function () {
  45358. if (this._renderVAO) {
  45359. return;
  45360. }
  45361. var data = new Array();
  45362. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  45363. // position
  45364. data.push(0.0);
  45365. data.push(0.0);
  45366. data.push(0.0);
  45367. var life = 1 + Math.random() * 10; // TODO: var
  45368. data.push(life + 1); // create the particle as a dead one to create a new one at start
  45369. data.push(life);
  45370. // velocity
  45371. data.push(0.0);
  45372. data.push(0.0);
  45373. data.push(0.0);
  45374. }
  45375. // Update VAO
  45376. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  45377. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  45378. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  45379. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  45380. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  45381. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  45382. this._engine.bindArrayBuffer(null);
  45383. // Render VAO
  45384. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  45385. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  45386. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  45387. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  45388. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  45389. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  45390. this._engine.bindArrayBuffer(null);
  45391. // Links
  45392. this._sourceVAO = this._updateVAO;
  45393. this._targetVAO = this._renderVAO;
  45394. this._sourceBuffer = this._updateBuffer;
  45395. this._targetBuffer = this._renderBuffer;
  45396. };
  45397. GPUParticleSystem.prototype.render = function () {
  45398. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  45399. return 0;
  45400. }
  45401. // Get everything ready to render
  45402. this._initialize();
  45403. if (this._currentRenderId === this._scene.getRenderId()) {
  45404. return 0;
  45405. }
  45406. this._currentRenderId = this._scene.getRenderId();
  45407. // Enable update effect
  45408. this._engine.enableEffect(this._updateEffect);
  45409. this._engine.setState(false);
  45410. // Bind source VAO
  45411. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  45412. // Update
  45413. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  45414. this._engine.setRasterizerState(false);
  45415. this._engine.beginTransformFeedback();
  45416. this._engine.drawPointClouds(0, this._capacity);
  45417. this._engine.endTransformFeedback();
  45418. this._engine.setRasterizerState(true);
  45419. this._engine.bindTransformFeedbackBuffer(null);
  45420. // Enable render effect
  45421. this._engine.enableEffect(this._renderEffect);
  45422. // Bind source VAO
  45423. this._engine.bindVertexArrayObject(this._targetVAO, null);
  45424. // Render
  45425. this._engine.drawPointClouds(0, this._capacity);
  45426. // Switch VAOs
  45427. var tmpVAO = this._sourceVAO;
  45428. this._sourceVAO = this._targetVAO;
  45429. this._targetVAO = tmpVAO;
  45430. // Switch buffers
  45431. var tmpBuffer = this._sourceBuffer;
  45432. this._sourceBuffer = this._targetBuffer;
  45433. this._targetBuffer = tmpBuffer;
  45434. return 0;
  45435. };
  45436. GPUParticleSystem.prototype.rebuild = function () {
  45437. };
  45438. GPUParticleSystem.prototype.dispose = function () {
  45439. var index = this._scene.particleSystems.indexOf(this);
  45440. if (index > -1) {
  45441. this._scene.particleSystems.splice(index, 1);
  45442. }
  45443. //TODO: this._dataBuffer.dispose();
  45444. // Callback
  45445. this.onDisposeObservable.notifyObservers(this);
  45446. this.onDisposeObservable.clear();
  45447. };
  45448. //TODO: Clone / Parse / serialize
  45449. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  45450. return null;
  45451. };
  45452. GPUParticleSystem.prototype.serialize = function () {
  45453. };
  45454. return GPUParticleSystem;
  45455. }());
  45456. BABYLON.GPUParticleSystem = GPUParticleSystem;
  45457. })(BABYLON || (BABYLON = {}));
  45458. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  45459. var BABYLON;
  45460. (function (BABYLON) {
  45461. var SolidParticle = /** @class */ (function () {
  45462. /**
  45463. * Creates a Solid Particle object.
  45464. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45465. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45466. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45467. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45468. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45469. * `shapeId` (integer) is the model shape identifier in the SPS.
  45470. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45471. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45472. */
  45473. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45474. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45475. this.idx = 0; // particle global index
  45476. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45477. this.position = BABYLON.Vector3.Zero(); // position
  45478. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45479. this.scaling = BABYLON.Vector3.One(); // scaling
  45480. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45481. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45482. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45483. this.alive = true; // alive
  45484. this.isVisible = true; // visibility
  45485. this._pos = 0; // index of this particle in the global "positions" array
  45486. this._ind = 0; // index of this particle in the global "indices" array
  45487. this.shapeId = 0; // model shape id
  45488. this.idxInShape = 0; // index of the particle in its shape id
  45489. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45490. this.idx = particleIndex;
  45491. this._pos = positionIndex;
  45492. this._ind = indiceIndex;
  45493. this._model = model;
  45494. this.shapeId = shapeId;
  45495. this.idxInShape = idxInShape;
  45496. this._sps = sps;
  45497. if (modelBoundingInfo) {
  45498. this._modelBoundingInfo = modelBoundingInfo;
  45499. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45500. }
  45501. }
  45502. Object.defineProperty(SolidParticle.prototype, "scale", {
  45503. /**
  45504. * legacy support, changed scale to scaling
  45505. */
  45506. get: function () {
  45507. return this.scaling;
  45508. },
  45509. set: function (scale) {
  45510. this.scaling = scale;
  45511. },
  45512. enumerable: true,
  45513. configurable: true
  45514. });
  45515. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45516. /**
  45517. * legacy support, changed quaternion to rotationQuaternion
  45518. */
  45519. get: function () {
  45520. return this.rotationQuaternion;
  45521. },
  45522. set: function (q) {
  45523. this.rotationQuaternion = q;
  45524. },
  45525. enumerable: true,
  45526. configurable: true
  45527. });
  45528. /**
  45529. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45530. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45531. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45532. */
  45533. SolidParticle.prototype.intersectsMesh = function (target) {
  45534. if (!this._boundingInfo || !target._boundingInfo) {
  45535. return false;
  45536. }
  45537. if (this._sps._bSphereOnly) {
  45538. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45539. }
  45540. return this._boundingInfo.intersects(target._boundingInfo, false);
  45541. };
  45542. return SolidParticle;
  45543. }());
  45544. BABYLON.SolidParticle = SolidParticle;
  45545. var ModelShape = /** @class */ (function () {
  45546. /**
  45547. * 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.
  45548. * SPS internal tool, don't use it manually.
  45549. */
  45550. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45551. this._indicesLength = 0; // length of the shape in the model indices array
  45552. this.shapeID = id;
  45553. this._shape = shape;
  45554. this._indicesLength = indicesLength;
  45555. this._shapeUV = shapeUV;
  45556. this._positionFunction = posFunction;
  45557. this._vertexFunction = vtxFunction;
  45558. }
  45559. return ModelShape;
  45560. }());
  45561. BABYLON.ModelShape = ModelShape;
  45562. var DepthSortedParticle = /** @class */ (function () {
  45563. function DepthSortedParticle() {
  45564. this.ind = 0; // index of the particle in the "indices" array
  45565. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45566. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45567. }
  45568. return DepthSortedParticle;
  45569. }());
  45570. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45571. })(BABYLON || (BABYLON = {}));
  45572. //# sourceMappingURL=babylon.solidParticle.js.map
  45573. var BABYLON;
  45574. (function (BABYLON) {
  45575. /**
  45576. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45577. */
  45578. var SolidParticleSystem = /** @class */ (function () {
  45579. /**
  45580. * Creates a SPS (Solid Particle System) object.
  45581. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45582. * `scene` (Scene) is the scene in which the SPS is added.
  45583. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45584. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45585. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45586. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45587. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45588. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45589. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45590. */
  45591. function SolidParticleSystem(name, scene, options) {
  45592. // public members
  45593. /**
  45594. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45595. * Example : var p = SPS.particles[i];
  45596. */
  45597. this.particles = new Array();
  45598. /**
  45599. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45600. */
  45601. this.nbParticles = 0;
  45602. /**
  45603. * If the particles must ever face the camera (default false). Useful for planar particles.
  45604. */
  45605. this.billboard = false;
  45606. /**
  45607. * Recompute normals when adding a shape
  45608. */
  45609. this.recomputeNormals = true;
  45610. /**
  45611. * This a counter ofr your own usage. It's not set by any SPS functions.
  45612. */
  45613. this.counter = 0;
  45614. /**
  45615. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45616. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45617. */
  45618. this.vars = {};
  45619. this._positions = new Array();
  45620. this._indices = new Array();
  45621. this._normals = new Array();
  45622. this._colors = new Array();
  45623. this._uvs = new Array();
  45624. this._index = 0; // indices index
  45625. this._updatable = true;
  45626. this._pickable = false;
  45627. this._isVisibilityBoxLocked = false;
  45628. this._alwaysVisible = false;
  45629. this._depthSort = false;
  45630. this._shapeCounter = 0;
  45631. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45632. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45633. this._computeParticleColor = true;
  45634. this._computeParticleTexture = true;
  45635. this._computeParticleRotation = true;
  45636. this._computeParticleVertex = false;
  45637. this._computeBoundingBox = false;
  45638. this._depthSortParticles = true;
  45639. this._cam_axisZ = BABYLON.Vector3.Zero();
  45640. this._cam_axisY = BABYLON.Vector3.Zero();
  45641. this._cam_axisX = BABYLON.Vector3.Zero();
  45642. this._axisZ = BABYLON.Axis.Z;
  45643. this._camDir = BABYLON.Vector3.Zero();
  45644. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45645. this._rotMatrix = new BABYLON.Matrix();
  45646. this._invertMatrix = new BABYLON.Matrix();
  45647. this._rotated = BABYLON.Vector3.Zero();
  45648. this._quaternion = new BABYLON.Quaternion();
  45649. this._vertex = BABYLON.Vector3.Zero();
  45650. this._normal = BABYLON.Vector3.Zero();
  45651. this._yaw = 0.0;
  45652. this._pitch = 0.0;
  45653. this._roll = 0.0;
  45654. this._halfroll = 0.0;
  45655. this._halfpitch = 0.0;
  45656. this._halfyaw = 0.0;
  45657. this._sinRoll = 0.0;
  45658. this._cosRoll = 0.0;
  45659. this._sinPitch = 0.0;
  45660. this._cosPitch = 0.0;
  45661. this._sinYaw = 0.0;
  45662. this._cosYaw = 0.0;
  45663. this._mustUnrotateFixedNormals = false;
  45664. this._minimum = BABYLON.Tmp.Vector3[0];
  45665. this._maximum = BABYLON.Tmp.Vector3[1];
  45666. this._minBbox = BABYLON.Tmp.Vector3[4];
  45667. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45668. this._particlesIntersect = false;
  45669. this._depthSortFunction = function (p1, p2) {
  45670. return (p2.sqDistance - p1.sqDistance);
  45671. };
  45672. this._needs32Bits = false;
  45673. this._bSphereOnly = false;
  45674. this._bSphereRadiusFactor = 1.0;
  45675. this.name = name;
  45676. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45677. this._camera = scene.activeCamera;
  45678. this._pickable = options ? options.isPickable : false;
  45679. this._depthSort = options ? options.enableDepthSort : false;
  45680. this._particlesIntersect = options ? options.particleIntersection : false;
  45681. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45682. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45683. if (options && options.updatable) {
  45684. this._updatable = options.updatable;
  45685. }
  45686. else {
  45687. this._updatable = true;
  45688. }
  45689. if (this._pickable) {
  45690. this.pickedParticles = [];
  45691. }
  45692. if (this._depthSort) {
  45693. this.depthSortedParticles = [];
  45694. }
  45695. }
  45696. /**
  45697. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45698. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45699. */
  45700. SolidParticleSystem.prototype.buildMesh = function () {
  45701. if (this.nbParticles === 0) {
  45702. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45703. this.addShape(triangle, 1);
  45704. triangle.dispose();
  45705. }
  45706. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45707. this._positions32 = new Float32Array(this._positions);
  45708. this._uvs32 = new Float32Array(this._uvs);
  45709. this._colors32 = new Float32Array(this._colors);
  45710. if (this.recomputeNormals) {
  45711. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45712. }
  45713. this._normals32 = new Float32Array(this._normals);
  45714. this._fixedNormal32 = new Float32Array(this._normals);
  45715. if (this._mustUnrotateFixedNormals) {
  45716. this._unrotateFixedNormals();
  45717. }
  45718. var vertexData = new BABYLON.VertexData();
  45719. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  45720. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45721. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45722. if (this._uvs32) {
  45723. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45724. ;
  45725. }
  45726. if (this._colors32) {
  45727. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45728. }
  45729. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45730. vertexData.applyToMesh(mesh, this._updatable);
  45731. this.mesh = mesh;
  45732. this.mesh.isPickable = this._pickable;
  45733. // free memory
  45734. if (!this._depthSort) {
  45735. this._indices = null;
  45736. }
  45737. this._positions = null;
  45738. this._normals = null;
  45739. this._uvs = null;
  45740. this._colors = null;
  45741. if (!this._updatable) {
  45742. this.particles.length = 0;
  45743. }
  45744. return mesh;
  45745. };
  45746. /**
  45747. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45748. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45749. * Thus the particles generated from `digest()` have their property `position` set yet.
  45750. * `mesh` ( Mesh ) is the mesh to be digested
  45751. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45752. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45753. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45754. */
  45755. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45756. var size = (options && options.facetNb) || 1;
  45757. var number = (options && options.number) || 0;
  45758. var delta = (options && options.delta) || 0;
  45759. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45760. var meshInd = mesh.getIndices();
  45761. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45762. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45763. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45764. var f = 0; // facet counter
  45765. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45766. // compute size from number
  45767. if (number) {
  45768. number = (number > totalFacets) ? totalFacets : number;
  45769. size = Math.round(totalFacets / number);
  45770. delta = 0;
  45771. }
  45772. else {
  45773. size = (size > totalFacets) ? totalFacets : size;
  45774. }
  45775. var facetPos = []; // submesh positions
  45776. var facetInd = []; // submesh indices
  45777. var facetUV = []; // submesh UV
  45778. var facetCol = []; // submesh colors
  45779. var barycenter = BABYLON.Tmp.Vector3[0];
  45780. var sizeO = size;
  45781. while (f < totalFacets) {
  45782. size = sizeO + Math.floor((1 + delta) * Math.random());
  45783. if (f > totalFacets - size) {
  45784. size = totalFacets - f;
  45785. }
  45786. // reset temp arrays
  45787. facetPos.length = 0;
  45788. facetInd.length = 0;
  45789. facetUV.length = 0;
  45790. facetCol.length = 0;
  45791. // iterate over "size" facets
  45792. var fi = 0;
  45793. for (var j = f * 3; j < (f + size) * 3; j++) {
  45794. facetInd.push(fi);
  45795. var i = meshInd[j];
  45796. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45797. if (meshUV) {
  45798. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45799. }
  45800. if (meshCol) {
  45801. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45802. }
  45803. fi++;
  45804. }
  45805. // create a model shape for each single particle
  45806. var idx = this.nbParticles;
  45807. var shape = this._posToShape(facetPos);
  45808. var shapeUV = this._uvsToShapeUV(facetUV);
  45809. // compute the barycenter of the shape
  45810. var v;
  45811. for (v = 0; v < shape.length; v++) {
  45812. barycenter.addInPlace(shape[v]);
  45813. }
  45814. barycenter.scaleInPlace(1 / shape.length);
  45815. // shift the shape from its barycenter to the origin
  45816. for (v = 0; v < shape.length; v++) {
  45817. shape[v].subtractInPlace(barycenter);
  45818. }
  45819. var bInfo;
  45820. if (this._particlesIntersect) {
  45821. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45822. }
  45823. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45824. // add the particle in the SPS
  45825. var currentPos = this._positions.length;
  45826. var currentInd = this._indices.length;
  45827. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45828. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45829. // initialize the particle position
  45830. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45831. this._index += shape.length;
  45832. idx++;
  45833. this.nbParticles++;
  45834. this._shapeCounter++;
  45835. f += size;
  45836. }
  45837. return this;
  45838. };
  45839. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45840. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45841. var index = 0;
  45842. var idx = 0;
  45843. for (var p = 0; p < this.particles.length; p++) {
  45844. this._particle = this.particles[p];
  45845. this._shape = this._particle._model._shape;
  45846. if (this._particle.rotationQuaternion) {
  45847. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45848. }
  45849. else {
  45850. this._yaw = this._particle.rotation.y;
  45851. this._pitch = this._particle.rotation.x;
  45852. this._roll = this._particle.rotation.z;
  45853. this._quaternionRotationYPR();
  45854. }
  45855. this._quaternionToRotationMatrix();
  45856. this._rotMatrix.invertToRef(this._invertMatrix);
  45857. for (var pt = 0; pt < this._shape.length; pt++) {
  45858. idx = index + pt * 3;
  45859. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45860. this._fixedNormal32[idx] = this._normal.x;
  45861. this._fixedNormal32[idx + 1] = this._normal.y;
  45862. this._fixedNormal32[idx + 2] = this._normal.z;
  45863. }
  45864. index = idx + 3;
  45865. }
  45866. };
  45867. //reset copy
  45868. SolidParticleSystem.prototype._resetCopy = function () {
  45869. this._copy.position.x = 0;
  45870. this._copy.position.y = 0;
  45871. this._copy.position.z = 0;
  45872. this._copy.rotation.x = 0;
  45873. this._copy.rotation.y = 0;
  45874. this._copy.rotation.z = 0;
  45875. this._copy.rotationQuaternion = null;
  45876. this._copy.scaling.x = 1.0;
  45877. this._copy.scaling.y = 1.0;
  45878. this._copy.scaling.z = 1.0;
  45879. this._copy.uvs.x = 0;
  45880. this._copy.uvs.y = 0;
  45881. this._copy.uvs.z = 1.0;
  45882. this._copy.uvs.w = 1.0;
  45883. this._copy.color = null;
  45884. };
  45885. // _meshBuilder : inserts the shape model in the global SPS mesh
  45886. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45887. var i;
  45888. var u = 0;
  45889. var c = 0;
  45890. var n = 0;
  45891. this._resetCopy();
  45892. if (options && options.positionFunction) {
  45893. options.positionFunction(this._copy, idx, idxInShape);
  45894. this._mustUnrotateFixedNormals = true;
  45895. }
  45896. if (this._copy.rotationQuaternion) {
  45897. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45898. }
  45899. else {
  45900. this._yaw = this._copy.rotation.y;
  45901. this._pitch = this._copy.rotation.x;
  45902. this._roll = this._copy.rotation.z;
  45903. this._quaternionRotationYPR();
  45904. }
  45905. this._quaternionToRotationMatrix();
  45906. for (i = 0; i < shape.length; i++) {
  45907. this._vertex.x = shape[i].x;
  45908. this._vertex.y = shape[i].y;
  45909. this._vertex.z = shape[i].z;
  45910. if (options && options.vertexFunction) {
  45911. options.vertexFunction(this._copy, this._vertex, i);
  45912. }
  45913. this._vertex.x *= this._copy.scaling.x;
  45914. this._vertex.y *= this._copy.scaling.y;
  45915. this._vertex.z *= this._copy.scaling.z;
  45916. this._vertex.x += this._copy.pivot.x;
  45917. this._vertex.y += this._copy.pivot.y;
  45918. this._vertex.z += this._copy.pivot.z;
  45919. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45920. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45921. if (meshUV) {
  45922. 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);
  45923. u += 2;
  45924. }
  45925. if (this._copy.color) {
  45926. this._color = this._copy.color;
  45927. }
  45928. else if (meshCol && meshCol[c] !== undefined) {
  45929. this._color.r = meshCol[c];
  45930. this._color.g = meshCol[c + 1];
  45931. this._color.b = meshCol[c + 2];
  45932. this._color.a = meshCol[c + 3];
  45933. }
  45934. else {
  45935. this._color.r = 1.0;
  45936. this._color.g = 1.0;
  45937. this._color.b = 1.0;
  45938. this._color.a = 1.0;
  45939. }
  45940. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45941. c += 4;
  45942. if (!this.recomputeNormals && meshNor) {
  45943. this._normal.x = meshNor[n];
  45944. this._normal.y = meshNor[n + 1];
  45945. this._normal.z = meshNor[n + 2];
  45946. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45947. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45948. n += 3;
  45949. }
  45950. }
  45951. for (i = 0; i < meshInd.length; i++) {
  45952. var current_ind = p + meshInd[i];
  45953. indices.push(current_ind);
  45954. if (current_ind > 65535) {
  45955. this._needs32Bits = true;
  45956. }
  45957. }
  45958. if (this._pickable) {
  45959. var nbfaces = meshInd.length / 3;
  45960. for (i = 0; i < nbfaces; i++) {
  45961. this.pickedParticles.push({ idx: idx, faceId: i });
  45962. }
  45963. }
  45964. if (this._depthSort) {
  45965. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45966. }
  45967. return this._copy;
  45968. };
  45969. // returns a shape array from positions array
  45970. SolidParticleSystem.prototype._posToShape = function (positions) {
  45971. var shape = [];
  45972. for (var i = 0; i < positions.length; i += 3) {
  45973. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45974. }
  45975. return shape;
  45976. };
  45977. // returns a shapeUV array from a Vector4 uvs
  45978. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45979. var shapeUV = [];
  45980. if (uvs) {
  45981. for (var i = 0; i < uvs.length; i++)
  45982. shapeUV.push(uvs[i]);
  45983. }
  45984. return shapeUV;
  45985. };
  45986. // adds a new particle object in the particles array
  45987. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45988. if (bInfo === void 0) { bInfo = null; }
  45989. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45990. this.particles.push(sp);
  45991. return sp;
  45992. };
  45993. /**
  45994. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45995. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45996. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45997. * `nb` (positive integer) the number of particles to be created from this model
  45998. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45999. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  46000. */
  46001. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  46002. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46003. var meshInd = mesh.getIndices();
  46004. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46005. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46006. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46007. var bbInfo;
  46008. if (this._particlesIntersect) {
  46009. bbInfo = mesh.getBoundingInfo();
  46010. }
  46011. var shape = this._posToShape(meshPos);
  46012. var shapeUV = this._uvsToShapeUV(meshUV);
  46013. var posfunc = options ? options.positionFunction : null;
  46014. var vtxfunc = options ? options.vertexFunction : null;
  46015. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  46016. // particles
  46017. var sp;
  46018. var currentCopy;
  46019. var idx = this.nbParticles;
  46020. for (var i = 0; i < nb; i++) {
  46021. var currentPos = this._positions.length;
  46022. var currentInd = this._indices.length;
  46023. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  46024. if (this._updatable) {
  46025. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  46026. sp.position.copyFrom(currentCopy.position);
  46027. sp.rotation.copyFrom(currentCopy.rotation);
  46028. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  46029. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  46030. }
  46031. if (currentCopy.color && sp.color) {
  46032. sp.color.copyFrom(currentCopy.color);
  46033. }
  46034. sp.scaling.copyFrom(currentCopy.scaling);
  46035. sp.uvs.copyFrom(currentCopy.uvs);
  46036. }
  46037. this._index += shape.length;
  46038. idx++;
  46039. }
  46040. this.nbParticles += nb;
  46041. this._shapeCounter++;
  46042. return this._shapeCounter - 1;
  46043. };
  46044. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  46045. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  46046. this._resetCopy();
  46047. if (particle._model._positionFunction) {
  46048. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  46049. }
  46050. if (this._copy.rotationQuaternion) {
  46051. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46052. }
  46053. else {
  46054. this._yaw = this._copy.rotation.y;
  46055. this._pitch = this._copy.rotation.x;
  46056. this._roll = this._copy.rotation.z;
  46057. this._quaternionRotationYPR();
  46058. }
  46059. this._quaternionToRotationMatrix();
  46060. this._shape = particle._model._shape;
  46061. for (var pt = 0; pt < this._shape.length; pt++) {
  46062. this._vertex.x = this._shape[pt].x;
  46063. this._vertex.y = this._shape[pt].y;
  46064. this._vertex.z = this._shape[pt].z;
  46065. if (particle._model._vertexFunction) {
  46066. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  46067. }
  46068. this._vertex.x *= this._copy.scaling.x;
  46069. this._vertex.y *= this._copy.scaling.y;
  46070. this._vertex.z *= this._copy.scaling.z;
  46071. this._vertex.x += this._copy.pivot.x;
  46072. this._vertex.y += this._copy.pivot.y;
  46073. this._vertex.z += this._copy.pivot.z;
  46074. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46075. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  46076. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  46077. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  46078. }
  46079. particle.position.x = 0.0;
  46080. particle.position.y = 0.0;
  46081. particle.position.z = 0.0;
  46082. particle.rotation.x = 0.0;
  46083. particle.rotation.y = 0.0;
  46084. particle.rotation.z = 0.0;
  46085. particle.rotationQuaternion = null;
  46086. particle.scaling.x = 1.0;
  46087. particle.scaling.y = 1.0;
  46088. particle.scaling.z = 1.0;
  46089. };
  46090. /**
  46091. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  46092. * Returns the SPS.
  46093. */
  46094. SolidParticleSystem.prototype.rebuildMesh = function () {
  46095. for (var p = 0; p < this.particles.length; p++) {
  46096. this._rebuildParticle(this.particles[p]);
  46097. }
  46098. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46099. return this;
  46100. };
  46101. /**
  46102. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  46103. * This method calls `updateParticle()` for each particle of the SPS.
  46104. * For an animated SPS, it is usually called within the render loop.
  46105. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  46106. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  46107. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  46108. * Returns the SPS.
  46109. */
  46110. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46111. if (start === void 0) { start = 0; }
  46112. if (end === void 0) { end = this.nbParticles - 1; }
  46113. if (update === void 0) { update = true; }
  46114. if (!this._updatable) {
  46115. return this;
  46116. }
  46117. // custom beforeUpdate
  46118. this.beforeUpdateParticles(start, end, update);
  46119. this._cam_axisX.x = 1.0;
  46120. this._cam_axisX.y = 0.0;
  46121. this._cam_axisX.z = 0.0;
  46122. this._cam_axisY.x = 0.0;
  46123. this._cam_axisY.y = 1.0;
  46124. this._cam_axisY.z = 0.0;
  46125. this._cam_axisZ.x = 0.0;
  46126. this._cam_axisZ.y = 0.0;
  46127. this._cam_axisZ.z = 1.0;
  46128. // cases when the World Matrix is to be computed first
  46129. if (this.billboard || this._depthSort) {
  46130. this.mesh.computeWorldMatrix(true);
  46131. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46132. }
  46133. // if the particles will always face the camera
  46134. if (this.billboard) {
  46135. // compute the camera position and un-rotate it by the current mesh rotation
  46136. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46137. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46138. this._cam_axisZ.normalize();
  46139. // same for camera up vector extracted from the cam view matrix
  46140. var view = this._camera.getViewMatrix(true);
  46141. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46142. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46143. this._cam_axisY.normalize();
  46144. this._cam_axisX.normalize();
  46145. }
  46146. // if depthSort, compute the camera global position in the mesh local system
  46147. if (this._depthSort) {
  46148. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46149. }
  46150. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46151. var idx = 0; // current position index in the global array positions32
  46152. var index = 0; // position start index in the global array positions32 of the current particle
  46153. var colidx = 0; // current color index in the global array colors32
  46154. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46155. var uvidx = 0; // current uv index in the global array uvs32
  46156. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46157. var pt = 0; // current index in the particle model shape
  46158. if (this.mesh.isFacetDataEnabled) {
  46159. this._computeBoundingBox = true;
  46160. }
  46161. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46162. if (this._computeBoundingBox) {
  46163. if (start == 0 && end == this.nbParticles - 1) {
  46164. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46165. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46166. }
  46167. else {
  46168. if (this.mesh._boundingInfo) {
  46169. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46170. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46171. }
  46172. }
  46173. }
  46174. // particle loop
  46175. index = this.particles[start]._pos;
  46176. var vpos = (index / 3) | 0;
  46177. colorIndex = vpos * 4;
  46178. uvIndex = vpos * 2;
  46179. for (var p = start; p <= end; p++) {
  46180. this._particle = this.particles[p];
  46181. this._shape = this._particle._model._shape;
  46182. this._shapeUV = this._particle._model._shapeUV;
  46183. // call to custom user function to update the particle properties
  46184. this.updateParticle(this._particle);
  46185. // camera-particle distance for depth sorting
  46186. if (this._depthSort && this._depthSortParticles) {
  46187. var dsp = this.depthSortedParticles[p];
  46188. dsp.ind = this._particle._ind;
  46189. dsp.indicesLength = this._particle._model._indicesLength;
  46190. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46191. }
  46192. // skip the computations for inactive or already invisible particles
  46193. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46194. // increment indexes for the next particle
  46195. pt = this._shape.length;
  46196. index += pt * 3;
  46197. colorIndex += pt * 4;
  46198. uvIndex += pt * 2;
  46199. continue;
  46200. }
  46201. if (this._particle.isVisible) {
  46202. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46203. // particle rotation matrix
  46204. if (this.billboard) {
  46205. this._particle.rotation.x = 0.0;
  46206. this._particle.rotation.y = 0.0;
  46207. }
  46208. if (this._computeParticleRotation || this.billboard) {
  46209. if (this._particle.rotationQuaternion) {
  46210. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46211. }
  46212. else {
  46213. this._yaw = this._particle.rotation.y;
  46214. this._pitch = this._particle.rotation.x;
  46215. this._roll = this._particle.rotation.z;
  46216. this._quaternionRotationYPR();
  46217. }
  46218. this._quaternionToRotationMatrix();
  46219. }
  46220. // particle vertex loop
  46221. for (pt = 0; pt < this._shape.length; pt++) {
  46222. idx = index + pt * 3;
  46223. colidx = colorIndex + pt * 4;
  46224. uvidx = uvIndex + pt * 2;
  46225. this._vertex.x = this._shape[pt].x;
  46226. this._vertex.y = this._shape[pt].y;
  46227. this._vertex.z = this._shape[pt].z;
  46228. if (this._computeParticleVertex) {
  46229. this.updateParticleVertex(this._particle, this._vertex, pt);
  46230. }
  46231. // positions
  46232. this._vertex.x *= this._particle.scaling.x;
  46233. this._vertex.y *= this._particle.scaling.y;
  46234. this._vertex.z *= this._particle.scaling.z;
  46235. this._vertex.x += this._particle.pivot.x;
  46236. this._vertex.y += this._particle.pivot.y;
  46237. this._vertex.z += this._particle.pivot.z;
  46238. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46239. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46240. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46241. 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;
  46242. 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;
  46243. 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;
  46244. if (this._computeBoundingBox) {
  46245. if (this._positions32[idx] < this._minimum.x) {
  46246. this._minimum.x = this._positions32[idx];
  46247. }
  46248. if (this._positions32[idx] > this._maximum.x) {
  46249. this._maximum.x = this._positions32[idx];
  46250. }
  46251. if (this._positions32[idx + 1] < this._minimum.y) {
  46252. this._minimum.y = this._positions32[idx + 1];
  46253. }
  46254. if (this._positions32[idx + 1] > this._maximum.y) {
  46255. this._maximum.y = this._positions32[idx + 1];
  46256. }
  46257. if (this._positions32[idx + 2] < this._minimum.z) {
  46258. this._minimum.z = this._positions32[idx + 2];
  46259. }
  46260. if (this._positions32[idx + 2] > this._maximum.z) {
  46261. this._maximum.z = this._positions32[idx + 2];
  46262. }
  46263. }
  46264. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46265. if (!this._computeParticleVertex) {
  46266. this._normal.x = this._fixedNormal32[idx];
  46267. this._normal.y = this._fixedNormal32[idx + 1];
  46268. this._normal.z = this._fixedNormal32[idx + 2];
  46269. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46270. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46271. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46272. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46273. 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;
  46274. 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;
  46275. }
  46276. if (this._computeParticleColor && this._particle.color) {
  46277. this._colors32[colidx] = this._particle.color.r;
  46278. this._colors32[colidx + 1] = this._particle.color.g;
  46279. this._colors32[colidx + 2] = this._particle.color.b;
  46280. this._colors32[colidx + 3] = this._particle.color.a;
  46281. }
  46282. if (this._computeParticleTexture) {
  46283. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46284. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46285. }
  46286. }
  46287. }
  46288. else {
  46289. this._particle._stillInvisible = true; // mark the particle as invisible
  46290. for (pt = 0; pt < this._shape.length; pt++) {
  46291. idx = index + pt * 3;
  46292. colidx = colorIndex + pt * 4;
  46293. uvidx = uvIndex + pt * 2;
  46294. this._positions32[idx] = 0.0;
  46295. this._positions32[idx + 1] = 0.0;
  46296. this._positions32[idx + 2] = 0.0;
  46297. this._normals32[idx] = 0.0;
  46298. this._normals32[idx + 1] = 0.0;
  46299. this._normals32[idx + 2] = 0.0;
  46300. if (this._computeParticleColor && this._particle.color) {
  46301. this._colors32[colidx] = this._particle.color.r;
  46302. this._colors32[colidx + 1] = this._particle.color.g;
  46303. this._colors32[colidx + 2] = this._particle.color.b;
  46304. this._colors32[colidx + 3] = this._particle.color.a;
  46305. }
  46306. if (this._computeParticleTexture) {
  46307. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46308. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46309. }
  46310. }
  46311. }
  46312. // if the particle intersections must be computed : update the bbInfo
  46313. if (this._particlesIntersect) {
  46314. var bInfo = this._particle._boundingInfo;
  46315. var bBox = bInfo.boundingBox;
  46316. var bSphere = bInfo.boundingSphere;
  46317. if (!this._bSphereOnly) {
  46318. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46319. for (var b = 0; b < bBox.vectors.length; b++) {
  46320. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46321. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46322. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46323. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46324. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46325. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46326. 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;
  46327. 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;
  46328. 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;
  46329. }
  46330. bBox._update(this.mesh._worldMatrix);
  46331. }
  46332. // place and scale the particle bouding sphere in the SPS local system, then update it
  46333. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46334. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46335. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46336. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46337. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46338. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46339. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46340. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46341. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46342. 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));
  46343. bSphere._update(this.mesh._worldMatrix);
  46344. }
  46345. // increment indexes for the next particle
  46346. index = idx + 3;
  46347. colorIndex = colidx + 4;
  46348. uvIndex = uvidx + 2;
  46349. }
  46350. // if the VBO must be updated
  46351. if (update) {
  46352. if (this._computeParticleColor) {
  46353. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46354. }
  46355. if (this._computeParticleTexture) {
  46356. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46357. }
  46358. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46359. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46360. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46361. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46362. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46363. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46364. for (var i = 0; i < this._normals32.length; i++) {
  46365. this._fixedNormal32[i] = this._normals32[i];
  46366. }
  46367. }
  46368. if (!this.mesh.areNormalsFrozen) {
  46369. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46370. }
  46371. }
  46372. if (this._depthSort && this._depthSortParticles) {
  46373. this.depthSortedParticles.sort(this._depthSortFunction);
  46374. var dspl = this.depthSortedParticles.length;
  46375. var sorted = 0;
  46376. var lind = 0;
  46377. var sind = 0;
  46378. var sid = 0;
  46379. for (sorted = 0; sorted < dspl; sorted++) {
  46380. lind = this.depthSortedParticles[sorted].indicesLength;
  46381. sind = this.depthSortedParticles[sorted].ind;
  46382. for (var i = 0; i < lind; i++) {
  46383. this._indices32[sid] = this._indices[sind + i];
  46384. sid++;
  46385. }
  46386. }
  46387. this.mesh.updateIndices(this._indices32);
  46388. }
  46389. }
  46390. if (this._computeBoundingBox) {
  46391. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46392. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46393. }
  46394. this.afterUpdateParticles(start, end, update);
  46395. return this;
  46396. };
  46397. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46398. this._halfroll = this._roll * 0.5;
  46399. this._halfpitch = this._pitch * 0.5;
  46400. this._halfyaw = this._yaw * 0.5;
  46401. this._sinRoll = Math.sin(this._halfroll);
  46402. this._cosRoll = Math.cos(this._halfroll);
  46403. this._sinPitch = Math.sin(this._halfpitch);
  46404. this._cosPitch = Math.cos(this._halfpitch);
  46405. this._sinYaw = Math.sin(this._halfyaw);
  46406. this._cosYaw = Math.cos(this._halfyaw);
  46407. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46408. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46409. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46410. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46411. };
  46412. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46413. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46414. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46415. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46416. this._rotMatrix.m[3] = 0;
  46417. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46418. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46419. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46420. this._rotMatrix.m[7] = 0;
  46421. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46422. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46423. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46424. this._rotMatrix.m[11] = 0;
  46425. this._rotMatrix.m[12] = 0;
  46426. this._rotMatrix.m[13] = 0;
  46427. this._rotMatrix.m[14] = 0;
  46428. this._rotMatrix.m[15] = 1.0;
  46429. };
  46430. /**
  46431. * Disposes the SPS.
  46432. * Returns nothing.
  46433. */
  46434. SolidParticleSystem.prototype.dispose = function () {
  46435. this.mesh.dispose();
  46436. this.vars = null;
  46437. // drop references to internal big arrays for the GC
  46438. this._positions = null;
  46439. this._indices = null;
  46440. this._normals = null;
  46441. this._uvs = null;
  46442. this._colors = null;
  46443. this._indices32 = null;
  46444. this._positions32 = null;
  46445. this._normals32 = null;
  46446. this._fixedNormal32 = null;
  46447. this._uvs32 = null;
  46448. this._colors32 = null;
  46449. this.pickedParticles = null;
  46450. };
  46451. /**
  46452. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46453. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46454. * Returns the SPS.
  46455. */
  46456. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46457. if (!this._isVisibilityBoxLocked) {
  46458. this.mesh.refreshBoundingInfo();
  46459. }
  46460. return this;
  46461. };
  46462. /**
  46463. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46464. * @param size the size (float) of the visibility box
  46465. * note : this doesn't lock the SPS mesh bounding box.
  46466. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46467. */
  46468. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46469. var vis = size / 2;
  46470. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46471. };
  46472. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46473. // getter and setter
  46474. get: function () {
  46475. return this._alwaysVisible;
  46476. },
  46477. /**
  46478. * Sets the SPS as always visible or not
  46479. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46480. */
  46481. set: function (val) {
  46482. this._alwaysVisible = val;
  46483. this.mesh.alwaysSelectAsActiveMesh = val;
  46484. },
  46485. enumerable: true,
  46486. configurable: true
  46487. });
  46488. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46489. get: function () {
  46490. return this._isVisibilityBoxLocked;
  46491. },
  46492. /**
  46493. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46494. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46495. */
  46496. set: function (val) {
  46497. this._isVisibilityBoxLocked = val;
  46498. var boundingInfo = this.mesh.getBoundingInfo();
  46499. boundingInfo.isLocked = val;
  46500. },
  46501. enumerable: true,
  46502. configurable: true
  46503. });
  46504. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46505. // getters
  46506. get: function () {
  46507. return this._computeParticleRotation;
  46508. },
  46509. // Optimizer setters
  46510. /**
  46511. * Tells to `setParticles()` to compute the particle rotations or not.
  46512. * Default value : true. The SPS is faster when it's set to false.
  46513. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46514. */
  46515. set: function (val) {
  46516. this._computeParticleRotation = val;
  46517. },
  46518. enumerable: true,
  46519. configurable: true
  46520. });
  46521. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46522. get: function () {
  46523. return this._computeParticleColor;
  46524. },
  46525. /**
  46526. * Tells to `setParticles()` to compute the particle colors or not.
  46527. * Default value : true. The SPS is faster when it's set to false.
  46528. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46529. */
  46530. set: function (val) {
  46531. this._computeParticleColor = val;
  46532. },
  46533. enumerable: true,
  46534. configurable: true
  46535. });
  46536. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46537. get: function () {
  46538. return this._computeParticleTexture;
  46539. },
  46540. /**
  46541. * Tells to `setParticles()` to compute the particle textures or not.
  46542. * Default value : true. The SPS is faster when it's set to false.
  46543. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46544. */
  46545. set: function (val) {
  46546. this._computeParticleTexture = val;
  46547. },
  46548. enumerable: true,
  46549. configurable: true
  46550. });
  46551. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46552. get: function () {
  46553. return this._computeParticleVertex;
  46554. },
  46555. /**
  46556. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46557. * Default value : false. The SPS is faster when it's set to false.
  46558. * Note : the particle custom vertex positions aren't stored values.
  46559. */
  46560. set: function (val) {
  46561. this._computeParticleVertex = val;
  46562. },
  46563. enumerable: true,
  46564. configurable: true
  46565. });
  46566. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46567. get: function () {
  46568. return this._computeBoundingBox;
  46569. },
  46570. /**
  46571. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46572. */
  46573. set: function (val) {
  46574. this._computeBoundingBox = val;
  46575. },
  46576. enumerable: true,
  46577. configurable: true
  46578. });
  46579. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46580. get: function () {
  46581. return this._depthSortParticles;
  46582. },
  46583. /**
  46584. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46585. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46586. * Default : `true`
  46587. */
  46588. set: function (val) {
  46589. this._depthSortParticles = val;
  46590. },
  46591. enumerable: true,
  46592. configurable: true
  46593. });
  46594. // =======================================================================
  46595. // Particle behavior logic
  46596. // these following methods may be overwritten by the user to fit his needs
  46597. /**
  46598. * This function does nothing. It may be overwritten to set all the particle first values.
  46599. * The SPS doesn't call this function, you may have to call it by your own.
  46600. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46601. */
  46602. SolidParticleSystem.prototype.initParticles = function () {
  46603. };
  46604. /**
  46605. * This function does nothing. It may be overwritten to recycle a particle.
  46606. * The SPS doesn't call this function, you may have to call it by your own.
  46607. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46608. */
  46609. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46610. return particle;
  46611. };
  46612. /**
  46613. * Updates a particle : this function should be overwritten by the user.
  46614. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46615. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46616. * ex : just set a particle position or velocity and recycle conditions
  46617. */
  46618. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46619. return particle;
  46620. };
  46621. /**
  46622. * Updates a vertex of a particle : it can be overwritten by the user.
  46623. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46624. * @param particle the current particle
  46625. * @param vertex the current index of the current particle
  46626. * @param pt the index of the current vertex in the particle shape
  46627. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46628. * ex : just set a vertex particle position
  46629. */
  46630. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46631. return vertex;
  46632. };
  46633. /**
  46634. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46635. * This does nothing and may be overwritten by the user.
  46636. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46637. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46638. * @param update the boolean update value actually passed to setParticles()
  46639. */
  46640. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46641. };
  46642. /**
  46643. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46644. * This will be passed three parameters.
  46645. * This does nothing and may be overwritten by the user.
  46646. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46647. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46648. * @param update the boolean update value actually passed to setParticles()
  46649. */
  46650. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46651. };
  46652. return SolidParticleSystem;
  46653. }());
  46654. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46655. })(BABYLON || (BABYLON = {}));
  46656. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46657. var BABYLON;
  46658. (function (BABYLON) {
  46659. var GroundMesh = /** @class */ (function (_super) {
  46660. __extends(GroundMesh, _super);
  46661. function GroundMesh(name, scene) {
  46662. var _this = _super.call(this, name, scene) || this;
  46663. _this.generateOctree = false;
  46664. return _this;
  46665. }
  46666. GroundMesh.prototype.getClassName = function () {
  46667. return "GroundMesh";
  46668. };
  46669. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46670. get: function () {
  46671. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46677. get: function () {
  46678. return this._subdivisionsX;
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46684. get: function () {
  46685. return this._subdivisionsY;
  46686. },
  46687. enumerable: true,
  46688. configurable: true
  46689. });
  46690. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46691. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46692. this._subdivisionsX = chunksCount;
  46693. this._subdivisionsY = chunksCount;
  46694. this.subdivide(chunksCount);
  46695. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46696. };
  46697. /**
  46698. * Returns a height (y) value in the Worl system :
  46699. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46700. * Returns the ground y position if (x, z) are outside the ground surface.
  46701. */
  46702. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46703. var world = this.getWorldMatrix();
  46704. var invMat = BABYLON.Tmp.Matrix[5];
  46705. world.invertToRef(invMat);
  46706. var tmpVect = BABYLON.Tmp.Vector3[8];
  46707. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46708. x = tmpVect.x;
  46709. z = tmpVect.z;
  46710. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46711. return this.position.y;
  46712. }
  46713. if (!this._heightQuads || this._heightQuads.length == 0) {
  46714. this._initHeightQuads();
  46715. this._computeHeightQuads();
  46716. }
  46717. var facet = this._getFacetAt(x, z);
  46718. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46719. // return y in the World system
  46720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46721. return tmpVect.y;
  46722. };
  46723. /**
  46724. * Returns a normalized vector (Vector3) orthogonal to the ground
  46725. * at the ground coordinates (x, z) expressed in the World system.
  46726. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46727. */
  46728. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46729. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46730. this.getNormalAtCoordinatesToRef(x, z, normal);
  46731. return normal;
  46732. };
  46733. /**
  46734. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46735. * at the ground coordinates (x, z) expressed in the World system.
  46736. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46737. * Returns the GroundMesh.
  46738. */
  46739. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46740. var world = this.getWorldMatrix();
  46741. var tmpMat = BABYLON.Tmp.Matrix[5];
  46742. world.invertToRef(tmpMat);
  46743. var tmpVect = BABYLON.Tmp.Vector3[8];
  46744. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46745. x = tmpVect.x;
  46746. z = tmpVect.z;
  46747. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46748. return this;
  46749. }
  46750. if (!this._heightQuads || this._heightQuads.length == 0) {
  46751. this._initHeightQuads();
  46752. this._computeHeightQuads();
  46753. }
  46754. var facet = this._getFacetAt(x, z);
  46755. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46756. return this;
  46757. };
  46758. /**
  46759. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46760. * if the ground has been updated.
  46761. * This can be used in the render loop.
  46762. * Returns the GroundMesh.
  46763. */
  46764. GroundMesh.prototype.updateCoordinateHeights = function () {
  46765. if (!this._heightQuads || this._heightQuads.length == 0) {
  46766. this._initHeightQuads();
  46767. }
  46768. this._computeHeightQuads();
  46769. return this;
  46770. };
  46771. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46772. GroundMesh.prototype._getFacetAt = function (x, z) {
  46773. // retrieve col and row from x, z coordinates in the ground local system
  46774. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46775. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46776. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46777. var facet;
  46778. if (z < quad.slope.x * x + quad.slope.y) {
  46779. facet = quad.facet1;
  46780. }
  46781. else {
  46782. facet = quad.facet2;
  46783. }
  46784. return facet;
  46785. };
  46786. // Creates and populates the heightMap array with "facet" elements :
  46787. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46788. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46789. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46790. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46791. // Returns the GroundMesh.
  46792. GroundMesh.prototype._initHeightQuads = function () {
  46793. var subdivisionsX = this._subdivisionsX;
  46794. var subdivisionsY = this._subdivisionsY;
  46795. this._heightQuads = new Array();
  46796. for (var row = 0; row < subdivisionsY; row++) {
  46797. for (var col = 0; col < subdivisionsX; col++) {
  46798. 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) };
  46799. this._heightQuads[row * subdivisionsX + col] = quad;
  46800. }
  46801. }
  46802. return this;
  46803. };
  46804. // Compute each quad element values and update the the heightMap array :
  46805. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46806. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46807. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46808. // Returns the GroundMesh.
  46809. GroundMesh.prototype._computeHeightQuads = function () {
  46810. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46811. if (!positions) {
  46812. return this;
  46813. }
  46814. var v1 = BABYLON.Tmp.Vector3[3];
  46815. var v2 = BABYLON.Tmp.Vector3[2];
  46816. var v3 = BABYLON.Tmp.Vector3[1];
  46817. var v4 = BABYLON.Tmp.Vector3[0];
  46818. var v1v2 = BABYLON.Tmp.Vector3[4];
  46819. var v1v3 = BABYLON.Tmp.Vector3[5];
  46820. var v1v4 = BABYLON.Tmp.Vector3[6];
  46821. var norm1 = BABYLON.Tmp.Vector3[7];
  46822. var norm2 = BABYLON.Tmp.Vector3[8];
  46823. var i = 0;
  46824. var j = 0;
  46825. var k = 0;
  46826. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46827. var h = 0;
  46828. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46829. var d2 = 0;
  46830. var subdivisionsX = this._subdivisionsX;
  46831. var subdivisionsY = this._subdivisionsY;
  46832. for (var row = 0; row < subdivisionsY; row++) {
  46833. for (var col = 0; col < subdivisionsX; col++) {
  46834. i = col * 3;
  46835. j = row * (subdivisionsX + 1) * 3;
  46836. k = (row + 1) * (subdivisionsX + 1) * 3;
  46837. v1.x = positions[j + i];
  46838. v1.y = positions[j + i + 1];
  46839. v1.z = positions[j + i + 2];
  46840. v2.x = positions[j + i + 3];
  46841. v2.y = positions[j + i + 4];
  46842. v2.z = positions[j + i + 5];
  46843. v3.x = positions[k + i];
  46844. v3.y = positions[k + i + 1];
  46845. v3.z = positions[k + i + 2];
  46846. v4.x = positions[k + i + 3];
  46847. v4.y = positions[k + i + 4];
  46848. v4.z = positions[k + i + 5];
  46849. // 2D slope V1V4
  46850. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46851. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46852. // facet equations :
  46853. // we compute each facet normal vector
  46854. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46855. // we compute the value d by applying the equation to v1 which belongs to the plane
  46856. // then we store the facet equation in a Vector4
  46857. v2.subtractToRef(v1, v1v2);
  46858. v3.subtractToRef(v1, v1v3);
  46859. v4.subtractToRef(v1, v1v4);
  46860. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46861. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46862. norm1.normalize();
  46863. norm2.normalize();
  46864. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46865. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46866. var quad = this._heightQuads[row * subdivisionsX + col];
  46867. quad.slope.copyFromFloats(cd, h);
  46868. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46869. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46870. }
  46871. }
  46872. return this;
  46873. };
  46874. GroundMesh.prototype.serialize = function (serializationObject) {
  46875. _super.prototype.serialize.call(this, serializationObject);
  46876. serializationObject.subdivisionsX = this._subdivisionsX;
  46877. serializationObject.subdivisionsY = this._subdivisionsY;
  46878. serializationObject.minX = this._minX;
  46879. serializationObject.maxX = this._maxX;
  46880. serializationObject.minZ = this._minZ;
  46881. serializationObject.maxZ = this._maxZ;
  46882. serializationObject.width = this._width;
  46883. serializationObject.height = this._height;
  46884. };
  46885. GroundMesh.Parse = function (parsedMesh, scene) {
  46886. var result = new GroundMesh(parsedMesh.name, scene);
  46887. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46888. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46889. result._minX = parsedMesh.minX;
  46890. result._maxX = parsedMesh.maxX;
  46891. result._minZ = parsedMesh.minZ;
  46892. result._maxZ = parsedMesh.maxZ;
  46893. result._width = parsedMesh.width;
  46894. result._height = parsedMesh.height;
  46895. return result;
  46896. };
  46897. return GroundMesh;
  46898. }(BABYLON.Mesh));
  46899. BABYLON.GroundMesh = GroundMesh;
  46900. })(BABYLON || (BABYLON = {}));
  46901. //# sourceMappingURL=babylon.groundMesh.js.map
  46902. var BABYLON;
  46903. (function (BABYLON) {
  46904. /**
  46905. * Creates an instance based on a source mesh.
  46906. */
  46907. var InstancedMesh = /** @class */ (function (_super) {
  46908. __extends(InstancedMesh, _super);
  46909. function InstancedMesh(name, source) {
  46910. var _this = _super.call(this, name, source.getScene()) || this;
  46911. source.instances.push(_this);
  46912. _this._sourceMesh = source;
  46913. _this.position.copyFrom(source.position);
  46914. _this.rotation.copyFrom(source.rotation);
  46915. _this.scaling.copyFrom(source.scaling);
  46916. if (source.rotationQuaternion) {
  46917. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46918. }
  46919. _this.infiniteDistance = source.infiniteDistance;
  46920. _this.setPivotMatrix(source.getPivotMatrix());
  46921. _this.refreshBoundingInfo();
  46922. _this._syncSubMeshes();
  46923. return _this;
  46924. }
  46925. /**
  46926. * Returns the string "InstancedMesh".
  46927. */
  46928. InstancedMesh.prototype.getClassName = function () {
  46929. return "InstancedMesh";
  46930. };
  46931. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46932. // Methods
  46933. get: function () {
  46934. return this._sourceMesh.receiveShadows;
  46935. },
  46936. enumerable: true,
  46937. configurable: true
  46938. });
  46939. Object.defineProperty(InstancedMesh.prototype, "material", {
  46940. get: function () {
  46941. return this._sourceMesh.material;
  46942. },
  46943. enumerable: true,
  46944. configurable: true
  46945. });
  46946. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46947. get: function () {
  46948. return this._sourceMesh.visibility;
  46949. },
  46950. enumerable: true,
  46951. configurable: true
  46952. });
  46953. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46954. get: function () {
  46955. return this._sourceMesh.skeleton;
  46956. },
  46957. enumerable: true,
  46958. configurable: true
  46959. });
  46960. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46961. get: function () {
  46962. return this._sourceMesh.renderingGroupId;
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. /**
  46968. * Returns the total number of vertices (integer).
  46969. */
  46970. InstancedMesh.prototype.getTotalVertices = function () {
  46971. return this._sourceMesh.getTotalVertices();
  46972. };
  46973. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46974. get: function () {
  46975. return this._sourceMesh;
  46976. },
  46977. enumerable: true,
  46978. configurable: true
  46979. });
  46980. /**
  46981. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46982. */
  46983. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46984. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46985. };
  46986. /**
  46987. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46988. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46989. * The `data` are either a numeric array either a Float32Array.
  46990. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46991. * 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).
  46992. * Note that a new underlying VertexBuffer object is created each call.
  46993. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46994. *
  46995. * Possible `kind` values :
  46996. * - BABYLON.VertexBuffer.PositionKind
  46997. * - BABYLON.VertexBuffer.UVKind
  46998. * - BABYLON.VertexBuffer.UV2Kind
  46999. * - BABYLON.VertexBuffer.UV3Kind
  47000. * - BABYLON.VertexBuffer.UV4Kind
  47001. * - BABYLON.VertexBuffer.UV5Kind
  47002. * - BABYLON.VertexBuffer.UV6Kind
  47003. * - BABYLON.VertexBuffer.ColorKind
  47004. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47005. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47006. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47007. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47008. *
  47009. * Returns the Mesh.
  47010. */
  47011. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  47012. if (this.sourceMesh) {
  47013. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  47014. }
  47015. return this.sourceMesh;
  47016. };
  47017. /**
  47018. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  47019. * If the mesh has no geometry, it is simply returned as it is.
  47020. * The `data` are either a numeric array either a Float32Array.
  47021. * No new underlying VertexBuffer object is created.
  47022. * 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.
  47023. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  47024. *
  47025. * Possible `kind` values :
  47026. * - BABYLON.VertexBuffer.PositionKind
  47027. * - BABYLON.VertexBuffer.UVKind
  47028. * - BABYLON.VertexBuffer.UV2Kind
  47029. * - BABYLON.VertexBuffer.UV3Kind
  47030. * - BABYLON.VertexBuffer.UV4Kind
  47031. * - BABYLON.VertexBuffer.UV5Kind
  47032. * - BABYLON.VertexBuffer.UV6Kind
  47033. * - BABYLON.VertexBuffer.ColorKind
  47034. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47035. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47036. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47037. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47038. *
  47039. * Returns the Mesh.
  47040. */
  47041. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  47042. if (this.sourceMesh) {
  47043. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  47044. }
  47045. return this.sourceMesh;
  47046. };
  47047. /**
  47048. * Sets the mesh indices.
  47049. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  47050. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  47051. * This method creates a new index buffer each call.
  47052. * Returns the Mesh.
  47053. */
  47054. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  47055. if (totalVertices === void 0) { totalVertices = null; }
  47056. if (this.sourceMesh) {
  47057. this.sourceMesh.setIndices(indices, totalVertices);
  47058. }
  47059. return this.sourceMesh;
  47060. };
  47061. /**
  47062. * Boolean : True if the mesh owns the requested kind of data.
  47063. */
  47064. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  47065. return this._sourceMesh.isVerticesDataPresent(kind);
  47066. };
  47067. /**
  47068. * Returns an array of indices (IndicesArray).
  47069. */
  47070. InstancedMesh.prototype.getIndices = function () {
  47071. return this._sourceMesh.getIndices();
  47072. };
  47073. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  47074. get: function () {
  47075. return this._sourceMesh._positions;
  47076. },
  47077. enumerable: true,
  47078. configurable: true
  47079. });
  47080. /**
  47081. * Sets a new updated BoundingInfo to the mesh.
  47082. * Returns the mesh.
  47083. */
  47084. InstancedMesh.prototype.refreshBoundingInfo = function () {
  47085. var meshBB = this._sourceMesh.getBoundingInfo();
  47086. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  47087. this._updateBoundingInfo();
  47088. return this;
  47089. };
  47090. InstancedMesh.prototype._preActivate = function () {
  47091. if (this._currentLOD) {
  47092. this._currentLOD._preActivate();
  47093. }
  47094. return this;
  47095. };
  47096. InstancedMesh.prototype._activate = function (renderId) {
  47097. if (this._currentLOD) {
  47098. this._currentLOD._registerInstanceForRenderId(this, renderId);
  47099. }
  47100. return this;
  47101. };
  47102. /**
  47103. * Returns the current associated LOD AbstractMesh.
  47104. */
  47105. InstancedMesh.prototype.getLOD = function (camera) {
  47106. if (!camera) {
  47107. return this;
  47108. }
  47109. var boundingInfo = this.getBoundingInfo();
  47110. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47111. if (this._currentLOD === this.sourceMesh) {
  47112. return this;
  47113. }
  47114. return this._currentLOD;
  47115. };
  47116. InstancedMesh.prototype._syncSubMeshes = function () {
  47117. this.releaseSubMeshes();
  47118. if (this._sourceMesh.subMeshes) {
  47119. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47120. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47121. }
  47122. }
  47123. return this;
  47124. };
  47125. InstancedMesh.prototype._generatePointsArray = function () {
  47126. return this._sourceMesh._generatePointsArray();
  47127. };
  47128. /**
  47129. * Creates a new InstancedMesh from the current mesh.
  47130. * - name (string) : the cloned mesh name
  47131. * - newParent (optional Node) : the optional Node to parent the clone to.
  47132. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47133. *
  47134. * Returns the clone.
  47135. */
  47136. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47137. var result = this._sourceMesh.createInstance(name);
  47138. // Deep copy
  47139. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47140. // Bounding info
  47141. this.refreshBoundingInfo();
  47142. // Parent
  47143. if (newParent) {
  47144. result.parent = newParent;
  47145. }
  47146. if (!doNotCloneChildren) {
  47147. // Children
  47148. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47149. var mesh = this.getScene().meshes[index];
  47150. if (mesh.parent === this) {
  47151. mesh.clone(mesh.name, result);
  47152. }
  47153. }
  47154. }
  47155. result.computeWorldMatrix(true);
  47156. return result;
  47157. };
  47158. /**
  47159. * Disposes the InstancedMesh.
  47160. * Returns nothing.
  47161. */
  47162. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47163. // Remove from mesh
  47164. var index = this._sourceMesh.instances.indexOf(this);
  47165. this._sourceMesh.instances.splice(index, 1);
  47166. _super.prototype.dispose.call(this, doNotRecurse);
  47167. };
  47168. return InstancedMesh;
  47169. }(BABYLON.AbstractMesh));
  47170. BABYLON.InstancedMesh = InstancedMesh;
  47171. })(BABYLON || (BABYLON = {}));
  47172. //# sourceMappingURL=babylon.instancedMesh.js.map
  47173. var BABYLON;
  47174. (function (BABYLON) {
  47175. var LinesMesh = /** @class */ (function (_super) {
  47176. __extends(LinesMesh, _super);
  47177. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47178. if (scene === void 0) { scene = null; }
  47179. if (parent === void 0) { parent = null; }
  47180. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47181. _this.useVertexColor = useVertexColor;
  47182. _this.useVertexAlpha = useVertexAlpha;
  47183. _this.color = new BABYLON.Color3(1, 1, 1);
  47184. _this.alpha = 1;
  47185. if (source) {
  47186. _this.color = source.color.clone();
  47187. _this.alpha = source.alpha;
  47188. _this.useVertexColor = source.useVertexColor;
  47189. _this.useVertexAlpha = source.useVertexAlpha;
  47190. }
  47191. _this._intersectionThreshold = 0.1;
  47192. var defines = [];
  47193. var options = {
  47194. attributes: [BABYLON.VertexBuffer.PositionKind],
  47195. uniforms: ["world", "viewProjection"],
  47196. needAlphaBlending: true,
  47197. defines: defines
  47198. };
  47199. if (useVertexAlpha === false) {
  47200. options.needAlphaBlending = false;
  47201. }
  47202. if (!useVertexColor) {
  47203. options.uniforms.push("color");
  47204. }
  47205. else {
  47206. options.defines.push("#define VERTEXCOLOR");
  47207. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47208. }
  47209. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47210. return _this;
  47211. }
  47212. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47213. /**
  47214. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47215. * This margin is expressed in world space coordinates, so its value may vary.
  47216. * Default value is 0.1
  47217. * @returns the intersection Threshold value.
  47218. */
  47219. get: function () {
  47220. return this._intersectionThreshold;
  47221. },
  47222. /**
  47223. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47224. * This margin is expressed in world space coordinates, so its value may vary.
  47225. * @param value the new threshold to apply
  47226. */
  47227. set: function (value) {
  47228. if (this._intersectionThreshold === value) {
  47229. return;
  47230. }
  47231. this._intersectionThreshold = value;
  47232. if (this.geometry) {
  47233. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47234. }
  47235. },
  47236. enumerable: true,
  47237. configurable: true
  47238. });
  47239. /**
  47240. * Returns the string "LineMesh"
  47241. */
  47242. LinesMesh.prototype.getClassName = function () {
  47243. return "LinesMesh";
  47244. };
  47245. Object.defineProperty(LinesMesh.prototype, "material", {
  47246. get: function () {
  47247. return this._colorShader;
  47248. },
  47249. set: function (value) {
  47250. // Do nothing
  47251. },
  47252. enumerable: true,
  47253. configurable: true
  47254. });
  47255. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47256. get: function () {
  47257. return false;
  47258. },
  47259. enumerable: true,
  47260. configurable: true
  47261. });
  47262. LinesMesh.prototype.createInstance = function (name) {
  47263. throw new Error("LinesMeshes do not support createInstance.");
  47264. };
  47265. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47266. if (!this._geometry) {
  47267. return this;
  47268. }
  47269. // VBOs
  47270. this._geometry._bind(this._colorShader.getEffect());
  47271. // Color
  47272. if (!this.useVertexColor) {
  47273. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47274. }
  47275. return this;
  47276. };
  47277. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47278. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47279. return this;
  47280. }
  47281. var engine = this.getScene().getEngine();
  47282. // Draw order
  47283. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  47284. return this;
  47285. };
  47286. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47287. this._colorShader.dispose();
  47288. _super.prototype.dispose.call(this, doNotRecurse);
  47289. };
  47290. /**
  47291. * Returns a new LineMesh object cloned from the current one.
  47292. */
  47293. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47294. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47295. };
  47296. return LinesMesh;
  47297. }(BABYLON.Mesh));
  47298. BABYLON.LinesMesh = LinesMesh;
  47299. })(BABYLON || (BABYLON = {}));
  47300. //# sourceMappingURL=babylon.linesMesh.js.map
  47301. var BABYLON;
  47302. (function (BABYLON) {
  47303. var ShaderMaterial = /** @class */ (function (_super) {
  47304. __extends(ShaderMaterial, _super);
  47305. function ShaderMaterial(name, scene, shaderPath, options) {
  47306. var _this = _super.call(this, name, scene) || this;
  47307. _this._textures = {};
  47308. _this._textureArrays = {};
  47309. _this._floats = {};
  47310. _this._floatsArrays = {};
  47311. _this._colors3 = {};
  47312. _this._colors3Arrays = {};
  47313. _this._colors4 = {};
  47314. _this._vectors2 = {};
  47315. _this._vectors3 = {};
  47316. _this._vectors4 = {};
  47317. _this._matrices = {};
  47318. _this._matrices3x3 = {};
  47319. _this._matrices2x2 = {};
  47320. _this._vectors2Arrays = {};
  47321. _this._vectors3Arrays = {};
  47322. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47323. _this._shaderPath = shaderPath;
  47324. options.needAlphaBlending = options.needAlphaBlending || false;
  47325. options.needAlphaTesting = options.needAlphaTesting || false;
  47326. options.attributes = options.attributes || ["position", "normal", "uv"];
  47327. options.uniforms = options.uniforms || ["worldViewProjection"];
  47328. options.uniformBuffers = options.uniformBuffers || [];
  47329. options.samplers = options.samplers || [];
  47330. options.defines = options.defines || [];
  47331. _this._options = options;
  47332. return _this;
  47333. }
  47334. ShaderMaterial.prototype.getClassName = function () {
  47335. return "ShaderMaterial";
  47336. };
  47337. ShaderMaterial.prototype.needAlphaBlending = function () {
  47338. return this._options.needAlphaBlending;
  47339. };
  47340. ShaderMaterial.prototype.needAlphaTesting = function () {
  47341. return this._options.needAlphaTesting;
  47342. };
  47343. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47344. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47345. this._options.uniforms.push(uniformName);
  47346. }
  47347. };
  47348. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47349. if (this._options.samplers.indexOf(name) === -1) {
  47350. this._options.samplers.push(name);
  47351. }
  47352. this._textures[name] = texture;
  47353. return this;
  47354. };
  47355. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47356. if (this._options.samplers.indexOf(name) === -1) {
  47357. this._options.samplers.push(name);
  47358. }
  47359. this._checkUniform(name);
  47360. this._textureArrays[name] = textures;
  47361. return this;
  47362. };
  47363. ShaderMaterial.prototype.setFloat = function (name, value) {
  47364. this._checkUniform(name);
  47365. this._floats[name] = value;
  47366. return this;
  47367. };
  47368. ShaderMaterial.prototype.setFloats = function (name, value) {
  47369. this._checkUniform(name);
  47370. this._floatsArrays[name] = value;
  47371. return this;
  47372. };
  47373. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47374. this._checkUniform(name);
  47375. this._colors3[name] = value;
  47376. return this;
  47377. };
  47378. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47379. this._checkUniform(name);
  47380. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47381. color.toArray(arr, arr.length);
  47382. return arr;
  47383. }, []);
  47384. return this;
  47385. };
  47386. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47387. this._checkUniform(name);
  47388. this._colors4[name] = value;
  47389. return this;
  47390. };
  47391. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47392. this._checkUniform(name);
  47393. this._vectors2[name] = value;
  47394. return this;
  47395. };
  47396. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47397. this._checkUniform(name);
  47398. this._vectors3[name] = value;
  47399. return this;
  47400. };
  47401. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47402. this._checkUniform(name);
  47403. this._vectors4[name] = value;
  47404. return this;
  47405. };
  47406. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47407. this._checkUniform(name);
  47408. this._matrices[name] = value;
  47409. return this;
  47410. };
  47411. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47412. this._checkUniform(name);
  47413. this._matrices3x3[name] = value;
  47414. return this;
  47415. };
  47416. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47417. this._checkUniform(name);
  47418. this._matrices2x2[name] = value;
  47419. return this;
  47420. };
  47421. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47422. this._checkUniform(name);
  47423. this._vectors2Arrays[name] = value;
  47424. return this;
  47425. };
  47426. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47427. this._checkUniform(name);
  47428. this._vectors3Arrays[name] = value;
  47429. return this;
  47430. };
  47431. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47432. if (!mesh) {
  47433. return true;
  47434. }
  47435. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47436. return false;
  47437. }
  47438. return false;
  47439. };
  47440. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47441. var scene = this.getScene();
  47442. var engine = scene.getEngine();
  47443. if (!this.checkReadyOnEveryCall) {
  47444. if (this._renderId === scene.getRenderId()) {
  47445. if (this._checkCache(scene, mesh, useInstances)) {
  47446. return true;
  47447. }
  47448. }
  47449. }
  47450. // Instances
  47451. var defines = [];
  47452. var attribs = [];
  47453. var fallbacks = new BABYLON.EffectFallbacks();
  47454. if (useInstances) {
  47455. defines.push("#define INSTANCES");
  47456. }
  47457. for (var index = 0; index < this._options.defines.length; index++) {
  47458. defines.push(this._options.defines[index]);
  47459. }
  47460. for (var index = 0; index < this._options.attributes.length; index++) {
  47461. attribs.push(this._options.attributes[index]);
  47462. }
  47463. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47464. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47465. defines.push("#define VERTEXCOLOR");
  47466. }
  47467. // Bones
  47468. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47471. if (mesh.numBoneInfluencers > 4) {
  47472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47474. }
  47475. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47476. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47477. fallbacks.addCPUSkinningFallback(0, mesh);
  47478. if (this._options.uniforms.indexOf("mBones") === -1) {
  47479. this._options.uniforms.push("mBones");
  47480. }
  47481. }
  47482. else {
  47483. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47484. }
  47485. // Textures
  47486. for (var name in this._textures) {
  47487. if (!this._textures[name].isReady()) {
  47488. return false;
  47489. }
  47490. }
  47491. // Alpha test
  47492. if (engine.getAlphaTesting()) {
  47493. defines.push("#define ALPHATEST");
  47494. }
  47495. var previousEffect = this._effect;
  47496. var join = defines.join("\n");
  47497. this._effect = engine.createEffect(this._shaderPath, {
  47498. attributes: attribs,
  47499. uniformsNames: this._options.uniforms,
  47500. uniformBuffersNames: this._options.uniformBuffers,
  47501. samplers: this._options.samplers,
  47502. defines: join,
  47503. fallbacks: fallbacks,
  47504. onCompiled: this.onCompiled,
  47505. onError: this.onError
  47506. }, engine);
  47507. if (!this._effect.isReady()) {
  47508. return false;
  47509. }
  47510. if (previousEffect !== this._effect) {
  47511. scene.resetCachedMaterial();
  47512. }
  47513. this._renderId = scene.getRenderId();
  47514. return true;
  47515. };
  47516. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47517. var scene = this.getScene();
  47518. if (!this._effect) {
  47519. return;
  47520. }
  47521. if (this._options.uniforms.indexOf("world") !== -1) {
  47522. this._effect.setMatrix("world", world);
  47523. }
  47524. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47525. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47526. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47527. }
  47528. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47529. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47530. }
  47531. };
  47532. ShaderMaterial.prototype.bind = function (world, mesh) {
  47533. // Std values
  47534. this.bindOnlyWorldMatrix(world);
  47535. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47536. if (this._options.uniforms.indexOf("view") !== -1) {
  47537. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47538. }
  47539. if (this._options.uniforms.indexOf("projection") !== -1) {
  47540. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47541. }
  47542. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47543. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47544. }
  47545. // Bones
  47546. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47547. var name;
  47548. // Texture
  47549. for (name in this._textures) {
  47550. this._effect.setTexture(name, this._textures[name]);
  47551. }
  47552. // Texture arrays
  47553. for (name in this._textureArrays) {
  47554. this._effect.setTextureArray(name, this._textureArrays[name]);
  47555. }
  47556. // Float
  47557. for (name in this._floats) {
  47558. this._effect.setFloat(name, this._floats[name]);
  47559. }
  47560. // Float s
  47561. for (name in this._floatsArrays) {
  47562. this._effect.setArray(name, this._floatsArrays[name]);
  47563. }
  47564. // Color3
  47565. for (name in this._colors3) {
  47566. this._effect.setColor3(name, this._colors3[name]);
  47567. }
  47568. for (name in this._colors3Arrays) {
  47569. this._effect.setArray3(name, this._colors3Arrays[name]);
  47570. }
  47571. // Color4
  47572. for (name in this._colors4) {
  47573. var color = this._colors4[name];
  47574. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47575. }
  47576. // Vector2
  47577. for (name in this._vectors2) {
  47578. this._effect.setVector2(name, this._vectors2[name]);
  47579. }
  47580. // Vector3
  47581. for (name in this._vectors3) {
  47582. this._effect.setVector3(name, this._vectors3[name]);
  47583. }
  47584. // Vector4
  47585. for (name in this._vectors4) {
  47586. this._effect.setVector4(name, this._vectors4[name]);
  47587. }
  47588. // Matrix
  47589. for (name in this._matrices) {
  47590. this._effect.setMatrix(name, this._matrices[name]);
  47591. }
  47592. // Matrix 3x3
  47593. for (name in this._matrices3x3) {
  47594. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47595. }
  47596. // Matrix 2x2
  47597. for (name in this._matrices2x2) {
  47598. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47599. }
  47600. // Vector2Array
  47601. for (name in this._vectors2Arrays) {
  47602. this._effect.setArray2(name, this._vectors2Arrays[name]);
  47603. }
  47604. // Vector3Array
  47605. for (name in this._vectors3Arrays) {
  47606. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47607. }
  47608. }
  47609. this._afterBind(mesh);
  47610. };
  47611. ShaderMaterial.prototype.getActiveTextures = function () {
  47612. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47613. for (var name in this._textures) {
  47614. activeTextures.push(this._textures[name]);
  47615. }
  47616. for (var name in this._textureArrays) {
  47617. var array = this._textureArrays[name];
  47618. for (var index = 0; index < array.length; index++) {
  47619. activeTextures.push(array[index]);
  47620. }
  47621. }
  47622. return activeTextures;
  47623. };
  47624. ShaderMaterial.prototype.hasTexture = function (texture) {
  47625. if (_super.prototype.hasTexture.call(this, texture)) {
  47626. return true;
  47627. }
  47628. for (var name in this._textures) {
  47629. if (this._textures[name] === texture) {
  47630. return true;
  47631. }
  47632. }
  47633. for (var name in this._textureArrays) {
  47634. var array = this._textureArrays[name];
  47635. for (var index = 0; index < array.length; index++) {
  47636. if (array[index] === texture) {
  47637. return true;
  47638. }
  47639. }
  47640. }
  47641. return false;
  47642. };
  47643. ShaderMaterial.prototype.clone = function (name) {
  47644. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47645. return newShaderMaterial;
  47646. };
  47647. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47648. if (forceDisposeTextures) {
  47649. var name;
  47650. for (name in this._textures) {
  47651. this._textures[name].dispose();
  47652. }
  47653. for (name in this._textureArrays) {
  47654. var array = this._textureArrays[name];
  47655. for (var index = 0; index < array.length; index++) {
  47656. array[index].dispose();
  47657. }
  47658. }
  47659. }
  47660. this._textures = {};
  47661. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47662. };
  47663. ShaderMaterial.prototype.serialize = function () {
  47664. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47665. serializationObject.customType = "BABYLON.ShaderMaterial";
  47666. serializationObject.options = this._options;
  47667. serializationObject.shaderPath = this._shaderPath;
  47668. var name;
  47669. // Texture
  47670. serializationObject.textures = {};
  47671. for (name in this._textures) {
  47672. serializationObject.textures[name] = this._textures[name].serialize();
  47673. }
  47674. // Texture arrays
  47675. serializationObject.textureArrays = {};
  47676. for (name in this._textureArrays) {
  47677. serializationObject.textureArrays[name] = [];
  47678. var array = this._textureArrays[name];
  47679. for (var index = 0; index < array.length; index++) {
  47680. serializationObject.textureArrays[name].push(array[index].serialize());
  47681. }
  47682. }
  47683. // Float
  47684. serializationObject.floats = {};
  47685. for (name in this._floats) {
  47686. serializationObject.floats[name] = this._floats[name];
  47687. }
  47688. // Float s
  47689. serializationObject.FloatArrays = {};
  47690. for (name in this._floatsArrays) {
  47691. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47692. }
  47693. // Color3
  47694. serializationObject.colors3 = {};
  47695. for (name in this._colors3) {
  47696. serializationObject.colors3[name] = this._colors3[name].asArray();
  47697. }
  47698. // Color3 array
  47699. serializationObject.colors3Arrays = {};
  47700. for (name in this._colors3Arrays) {
  47701. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47702. }
  47703. // Color4
  47704. serializationObject.colors4 = {};
  47705. for (name in this._colors4) {
  47706. serializationObject.colors4[name] = this._colors4[name].asArray();
  47707. }
  47708. // Vector2
  47709. serializationObject.vectors2 = {};
  47710. for (name in this._vectors2) {
  47711. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47712. }
  47713. // Vector3
  47714. serializationObject.vectors3 = {};
  47715. for (name in this._vectors3) {
  47716. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47717. }
  47718. // Vector4
  47719. serializationObject.vectors4 = {};
  47720. for (name in this._vectors4) {
  47721. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47722. }
  47723. // Matrix
  47724. serializationObject.matrices = {};
  47725. for (name in this._matrices) {
  47726. serializationObject.matrices[name] = this._matrices[name].asArray();
  47727. }
  47728. // Matrix 3x3
  47729. serializationObject.matrices3x3 = {};
  47730. for (name in this._matrices3x3) {
  47731. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47732. }
  47733. // Matrix 2x2
  47734. serializationObject.matrices2x2 = {};
  47735. for (name in this._matrices2x2) {
  47736. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47737. }
  47738. // Vector2Array
  47739. serializationObject.vectors2Arrays = {};
  47740. for (name in this._vectors2Arrays) {
  47741. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  47742. }
  47743. // Vector3Array
  47744. serializationObject.vectors3Arrays = {};
  47745. for (name in this._vectors3Arrays) {
  47746. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47747. }
  47748. return serializationObject;
  47749. };
  47750. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47751. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47752. var name;
  47753. // Texture
  47754. for (name in source.textures) {
  47755. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47756. }
  47757. // Texture arrays
  47758. for (name in source.textureArrays) {
  47759. var array = source.textureArrays[name];
  47760. var textureArray = new Array();
  47761. for (var index = 0; index < array.length; index++) {
  47762. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47763. }
  47764. material.setTextureArray(name, textureArray);
  47765. }
  47766. // Float
  47767. for (name in source.floats) {
  47768. material.setFloat(name, source.floats[name]);
  47769. }
  47770. // Float s
  47771. for (name in source.floatsArrays) {
  47772. material.setFloats(name, source.floatsArrays[name]);
  47773. }
  47774. // Color3
  47775. for (name in source.colors3) {
  47776. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47777. }
  47778. // Color3 arrays
  47779. for (name in source.colors3Arrays) {
  47780. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47781. if (i % 3 === 0) {
  47782. arr.push([num]);
  47783. }
  47784. else {
  47785. arr[arr.length - 1].push(num);
  47786. }
  47787. return arr;
  47788. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47789. material.setColor3Array(name, colors);
  47790. }
  47791. // Color4
  47792. for (name in source.colors4) {
  47793. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47794. }
  47795. // Vector2
  47796. for (name in source.vectors2) {
  47797. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47798. }
  47799. // Vector3
  47800. for (name in source.vectors3) {
  47801. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47802. }
  47803. // Vector4
  47804. for (name in source.vectors4) {
  47805. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47806. }
  47807. // Matrix
  47808. for (name in source.matrices) {
  47809. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47810. }
  47811. // Matrix 3x3
  47812. for (name in source.matrices3x3) {
  47813. material.setMatrix3x3(name, source.matrices3x3[name]);
  47814. }
  47815. // Matrix 2x2
  47816. for (name in source.matrices2x2) {
  47817. material.setMatrix2x2(name, source.matrices2x2[name]);
  47818. }
  47819. // Vector2Array
  47820. for (name in source.vectors2Arrays) {
  47821. material.setArray2(name, source.vectors2Arrays[name]);
  47822. }
  47823. // Vector3Array
  47824. for (name in source.vectors3Arrays) {
  47825. material.setArray3(name, source.vectors3Arrays[name]);
  47826. }
  47827. return material;
  47828. };
  47829. return ShaderMaterial;
  47830. }(BABYLON.Material));
  47831. BABYLON.ShaderMaterial = ShaderMaterial;
  47832. })(BABYLON || (BABYLON = {}));
  47833. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47834. var BABYLON;
  47835. (function (BABYLON) {
  47836. var MeshBuilder = /** @class */ (function () {
  47837. function MeshBuilder() {
  47838. }
  47839. MeshBuilder.updateSideOrientation = function (orientation) {
  47840. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47841. return BABYLON.Mesh.DOUBLESIDE;
  47842. }
  47843. if (orientation === undefined || orientation === null) {
  47844. return BABYLON.Mesh.FRONTSIDE;
  47845. }
  47846. return orientation;
  47847. };
  47848. /**
  47849. * Creates a box mesh.
  47850. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47851. * The parameter `size` sets the size (float) of each box side (default 1).
  47852. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47853. * 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).
  47854. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47856. * 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).
  47857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47859. */
  47860. MeshBuilder.CreateBox = function (name, options, scene) {
  47861. if (scene === void 0) { scene = null; }
  47862. var box = new BABYLON.Mesh(name, scene);
  47863. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47864. box._originalBuilderSideOrientation = options.sideOrientation;
  47865. var vertexData = BABYLON.VertexData.CreateBox(options);
  47866. vertexData.applyToMesh(box, options.updatable);
  47867. return box;
  47868. };
  47869. /**
  47870. * Creates a sphere mesh.
  47871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47872. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47873. * 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`).
  47874. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47875. * 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
  47876. * 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).
  47877. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47878. * 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).
  47879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47881. */
  47882. MeshBuilder.CreateSphere = function (name, options, scene) {
  47883. var sphere = new BABYLON.Mesh(name, scene);
  47884. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47885. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47886. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47887. vertexData.applyToMesh(sphere, options.updatable);
  47888. return sphere;
  47889. };
  47890. /**
  47891. * Creates a plane polygonal mesh. By default, this is a disc.
  47892. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47893. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47894. * 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.
  47895. * 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
  47896. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47897. * 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).
  47898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47900. */
  47901. MeshBuilder.CreateDisc = function (name, options, scene) {
  47902. if (scene === void 0) { scene = null; }
  47903. var disc = new BABYLON.Mesh(name, scene);
  47904. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47905. disc._originalBuilderSideOrientation = options.sideOrientation;
  47906. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47907. vertexData.applyToMesh(disc, options.updatable);
  47908. return disc;
  47909. };
  47910. /**
  47911. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47913. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47914. * 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`).
  47915. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47916. * 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.
  47917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47918. * 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).
  47919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47921. */
  47922. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47923. var sphere = new BABYLON.Mesh(name, scene);
  47924. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47925. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47926. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47927. vertexData.applyToMesh(sphere, options.updatable);
  47928. return sphere;
  47929. };
  47930. ;
  47931. /**
  47932. * Creates a ribbon mesh.
  47933. * 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.
  47934. *
  47935. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47936. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47937. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47938. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47939. * 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.
  47940. * 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.
  47941. * 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
  47942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47943. * 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).
  47944. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47945. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47946. * 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.
  47947. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47948. * 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
  47949. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47950. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47952. */
  47953. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47954. if (scene === void 0) { scene = null; }
  47955. var pathArray = options.pathArray;
  47956. var closeArray = options.closeArray;
  47957. var closePath = options.closePath;
  47958. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47959. var instance = options.instance;
  47960. var updatable = options.updatable;
  47961. if (instance) {
  47962. // positionFunction : ribbon case
  47963. // only pathArray and sideOrientation parameters are taken into account for positions update
  47964. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47965. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47966. var positionFunction = function (positions) {
  47967. var minlg = pathArray[0].length;
  47968. var i = 0;
  47969. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47970. for (var si = 1; si <= ns; si++) {
  47971. for (var p = 0; p < pathArray.length; p++) {
  47972. var path = pathArray[p];
  47973. var l = path.length;
  47974. minlg = (minlg < l) ? minlg : l;
  47975. var j = 0;
  47976. while (j < minlg) {
  47977. positions[i] = path[j].x;
  47978. positions[i + 1] = path[j].y;
  47979. positions[i + 2] = path[j].z;
  47980. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47981. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47982. }
  47983. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47984. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47985. }
  47986. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47987. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47988. }
  47989. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47990. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47991. }
  47992. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47993. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47994. }
  47995. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47996. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47997. }
  47998. j++;
  47999. i += 3;
  48000. }
  48001. if (instance._closePath) {
  48002. positions[i] = path[0].x;
  48003. positions[i + 1] = path[0].y;
  48004. positions[i + 2] = path[0].z;
  48005. i += 3;
  48006. }
  48007. }
  48008. }
  48009. };
  48010. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48011. positionFunction(positions);
  48012. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  48013. instance._boundingInfo.update(instance._worldMatrix);
  48014. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48015. if (options.colors) {
  48016. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48017. for (var c = 0; c < options.colors.length; c++) {
  48018. colors[c * 4] = options.colors[c].r;
  48019. colors[c * 4 + 1] = options.colors[c].g;
  48020. colors[c * 4 + 2] = options.colors[c].b;
  48021. colors[c * 4 + 3] = options.colors[c].a;
  48022. }
  48023. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  48024. }
  48025. if (options.uvs) {
  48026. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48027. for (var i = 0; i < options.uvs.length; i++) {
  48028. uvs[i * 2] = options.uvs[i].x;
  48029. uvs[i * 2 + 1] = options.uvs[i].y;
  48030. }
  48031. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  48032. }
  48033. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  48034. var indices = instance.getIndices();
  48035. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48036. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  48037. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  48038. if (instance._closePath) {
  48039. var indexFirst = 0;
  48040. var indexLast = 0;
  48041. for (var p = 0; p < pathArray.length; p++) {
  48042. indexFirst = instance._idx[p] * 3;
  48043. if (p + 1 < pathArray.length) {
  48044. indexLast = (instance._idx[p + 1] - 1) * 3;
  48045. }
  48046. else {
  48047. indexLast = normals.length - 3;
  48048. }
  48049. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  48050. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  48051. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  48052. normals[indexLast] = normals[indexFirst];
  48053. normals[indexLast + 1] = normals[indexFirst + 1];
  48054. normals[indexLast + 2] = normals[indexFirst + 2];
  48055. }
  48056. }
  48057. if (!(instance.areNormalsFrozen)) {
  48058. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  48059. }
  48060. }
  48061. return instance;
  48062. }
  48063. else {
  48064. var ribbon = new BABYLON.Mesh(name, scene);
  48065. ribbon._originalBuilderSideOrientation = sideOrientation;
  48066. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  48067. if (closePath) {
  48068. ribbon._idx = vertexData._idx;
  48069. }
  48070. ribbon._closePath = closePath;
  48071. ribbon._closeArray = closeArray;
  48072. vertexData.applyToMesh(ribbon, updatable);
  48073. return ribbon;
  48074. }
  48075. };
  48076. /**
  48077. * Creates a cylinder or a cone mesh.
  48078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  48079. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  48080. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  48081. * 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.
  48082. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  48083. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  48084. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  48085. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  48086. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  48087. * 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).
  48088. * 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
  48089. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  48090. * 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
  48091. * 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.
  48092. * If `enclose` is false, a ring surface is one element.
  48093. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  48094. * 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
  48095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48096. * 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).
  48097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48099. */
  48100. MeshBuilder.CreateCylinder = function (name, options, scene) {
  48101. var cylinder = new BABYLON.Mesh(name, scene);
  48102. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48103. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  48104. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  48105. vertexData.applyToMesh(cylinder, options.updatable);
  48106. return cylinder;
  48107. };
  48108. /**
  48109. * Creates a torus mesh.
  48110. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48111. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48112. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48113. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48115. * 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).
  48116. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48118. */
  48119. MeshBuilder.CreateTorus = function (name, options, scene) {
  48120. var torus = new BABYLON.Mesh(name, scene);
  48121. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48122. torus._originalBuilderSideOrientation = options.sideOrientation;
  48123. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48124. vertexData.applyToMesh(torus, options.updatable);
  48125. return torus;
  48126. };
  48127. /**
  48128. * Creates a torus knot mesh.
  48129. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48130. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48131. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48132. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48133. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48135. * 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).
  48136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48138. */
  48139. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48140. var torusKnot = new BABYLON.Mesh(name, scene);
  48141. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48142. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48143. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48144. vertexData.applyToMesh(torusKnot, options.updatable);
  48145. return torusKnot;
  48146. };
  48147. /**
  48148. * Creates a line system mesh.
  48149. * A line system is a pool of many lines gathered in a single mesh.
  48150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48151. * 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.
  48152. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48153. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48154. * 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
  48155. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48156. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48157. * 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
  48158. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48160. */
  48161. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48162. var instance = options.instance;
  48163. var lines = options.lines;
  48164. var colors = options.colors;
  48165. if (instance) {
  48166. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48167. var vertexColor;
  48168. var lineColors;
  48169. if (colors) {
  48170. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48171. }
  48172. var i = 0;
  48173. var c = 0;
  48174. for (var l = 0; l < lines.length; l++) {
  48175. var points = lines[l];
  48176. for (var p = 0; p < points.length; p++) {
  48177. positions[i] = points[p].x;
  48178. positions[i + 1] = points[p].y;
  48179. positions[i + 2] = points[p].z;
  48180. if (colors && vertexColor) {
  48181. lineColors = colors[l];
  48182. vertexColor[c] = lineColors[p].r;
  48183. vertexColor[c + 1] = lineColors[p].g;
  48184. vertexColor[c + 2] = lineColors[p].b;
  48185. vertexColor[c + 3] = lineColors[p].a;
  48186. c += 4;
  48187. }
  48188. i += 3;
  48189. }
  48190. }
  48191. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48192. if (colors && vertexColor) {
  48193. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48194. }
  48195. return instance;
  48196. }
  48197. // line system creation
  48198. var useVertexColor = (colors) ? true : false;
  48199. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48200. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48201. vertexData.applyToMesh(lineSystem, options.updatable);
  48202. return lineSystem;
  48203. };
  48204. /**
  48205. * Creates a line mesh.
  48206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48207. * 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.
  48208. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48209. * The parameter `points` is an array successive Vector3.
  48210. * 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
  48211. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48212. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48213. * When updating an instance, remember that only point positions can change, not the number of points.
  48214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48215. */
  48216. MeshBuilder.CreateLines = function (name, options, scene) {
  48217. if (scene === void 0) { scene = null; }
  48218. var colors = (options.colors) ? [options.colors] : null;
  48219. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48220. return lines;
  48221. };
  48222. /**
  48223. * Creates a dashed line mesh.
  48224. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48225. * 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.
  48226. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48227. * The parameter `points` is an array successive Vector3.
  48228. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48229. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48230. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48231. * 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
  48232. * When updating an instance, remember that only point positions can change, not the number of points.
  48233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48234. */
  48235. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48236. if (scene === void 0) { scene = null; }
  48237. var points = options.points;
  48238. var instance = options.instance;
  48239. var gapSize = options.gapSize || 1;
  48240. var dashSize = options.dashSize || 3;
  48241. if (instance) {
  48242. var positionFunction = function (positions) {
  48243. var curvect = BABYLON.Vector3.Zero();
  48244. var nbSeg = positions.length / 6;
  48245. var lg = 0;
  48246. var nb = 0;
  48247. var shft = 0;
  48248. var dashshft = 0;
  48249. var curshft = 0;
  48250. var p = 0;
  48251. var i = 0;
  48252. var j = 0;
  48253. for (i = 0; i < points.length - 1; i++) {
  48254. points[i + 1].subtractToRef(points[i], curvect);
  48255. lg += curvect.length();
  48256. }
  48257. shft = lg / nbSeg;
  48258. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48259. for (i = 0; i < points.length - 1; i++) {
  48260. points[i + 1].subtractToRef(points[i], curvect);
  48261. nb = Math.floor(curvect.length() / shft);
  48262. curvect.normalize();
  48263. j = 0;
  48264. while (j < nb && p < positions.length) {
  48265. curshft = shft * j;
  48266. positions[p] = points[i].x + curshft * curvect.x;
  48267. positions[p + 1] = points[i].y + curshft * curvect.y;
  48268. positions[p + 2] = points[i].z + curshft * curvect.z;
  48269. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48270. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48271. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48272. p += 6;
  48273. j++;
  48274. }
  48275. }
  48276. while (p < positions.length) {
  48277. positions[p] = points[i].x;
  48278. positions[p + 1] = points[i].y;
  48279. positions[p + 2] = points[i].z;
  48280. p += 3;
  48281. }
  48282. };
  48283. instance.updateMeshPositions(positionFunction, false);
  48284. return instance;
  48285. }
  48286. // dashed lines creation
  48287. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48288. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48289. vertexData.applyToMesh(dashedLines, options.updatable);
  48290. dashedLines.dashSize = dashSize;
  48291. dashedLines.gapSize = gapSize;
  48292. return dashedLines;
  48293. };
  48294. /**
  48295. * Creates an extruded shape mesh.
  48296. * 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.
  48297. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48298. *
  48299. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48300. * 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
  48301. * extruded along the Z axis.
  48302. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48303. * 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.
  48304. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48305. * 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
  48306. * 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
  48307. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48308. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48309. * 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).
  48310. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48311. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48313. */
  48314. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48315. if (scene === void 0) { scene = null; }
  48316. var path = options.path;
  48317. var shape = options.shape;
  48318. var scale = options.scale || 1;
  48319. var rotation = options.rotation || 0;
  48320. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48321. var updatable = options.updatable;
  48322. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48323. var instance = options.instance || null;
  48324. var invertUV = options.invertUV || false;
  48325. 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);
  48326. };
  48327. /**
  48328. * Creates an custom extruded shape mesh.
  48329. * 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.
  48330. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48331. *
  48332. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48333. * 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
  48334. * extruded along the Z axis.
  48335. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48336. * 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
  48337. * and the distance of this point from the begining of the path :
  48338. * ```javascript
  48339. * var rotationFunction = function(i, distance) {
  48340. * // do things
  48341. * return rotationValue; }
  48342. * ```
  48343. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48344. * 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
  48345. * and the distance of this point from the begining of the path :
  48346. * ```javascript
  48347. * var scaleFunction = function(i, distance) {
  48348. * // do things
  48349. * return scaleValue;}
  48350. * ```
  48351. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48352. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48353. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48354. * 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
  48355. * 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
  48356. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48358. * 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).
  48359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48360. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48362. */
  48363. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48364. var path = options.path;
  48365. var shape = options.shape;
  48366. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48367. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48368. var ribbonCloseArray = options.ribbonCloseArray || false;
  48369. var ribbonClosePath = options.ribbonClosePath || false;
  48370. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48371. var updatable = options.updatable;
  48372. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48373. var instance = options.instance;
  48374. var invertUV = options.invertUV || false;
  48375. 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);
  48376. };
  48377. /**
  48378. * Creates lathe mesh.
  48379. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48380. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48381. *
  48382. * 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
  48383. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48384. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48385. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48386. * 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.
  48387. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48388. * 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
  48389. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48390. * 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).
  48391. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48392. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48394. */
  48395. MeshBuilder.CreateLathe = function (name, options, scene) {
  48396. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48397. var closed = (options.closed === undefined) ? true : options.closed;
  48398. var shape = options.shape;
  48399. var radius = options.radius || 1;
  48400. var tessellation = options.tessellation || 64;
  48401. var updatable = options.updatable;
  48402. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48403. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48404. var pi2 = Math.PI * 2;
  48405. var paths = new Array();
  48406. var invertUV = options.invertUV || false;
  48407. var i = 0;
  48408. var p = 0;
  48409. var step = pi2 / tessellation * arc;
  48410. var rotated;
  48411. var path = new Array();
  48412. ;
  48413. for (i = 0; i <= tessellation; i++) {
  48414. var path = [];
  48415. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48416. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48417. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48418. }
  48419. for (p = 0; p < shape.length; p++) {
  48420. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48421. path.push(rotated);
  48422. }
  48423. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48424. 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));
  48425. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48426. }
  48427. paths.push(path);
  48428. }
  48429. // lathe ribbon
  48430. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48431. return lathe;
  48432. };
  48433. /**
  48434. * Creates a plane mesh.
  48435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48436. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48437. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48438. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48440. * 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).
  48441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48443. */
  48444. MeshBuilder.CreatePlane = function (name, options, scene) {
  48445. var plane = new BABYLON.Mesh(name, scene);
  48446. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48447. plane._originalBuilderSideOrientation = options.sideOrientation;
  48448. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48449. vertexData.applyToMesh(plane, options.updatable);
  48450. if (options.sourcePlane) {
  48451. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48452. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48453. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48454. plane.rotate(vectorProduct, product);
  48455. }
  48456. return plane;
  48457. };
  48458. /**
  48459. * Creates a ground mesh.
  48460. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48461. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48462. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48464. */
  48465. MeshBuilder.CreateGround = function (name, options, scene) {
  48466. var ground = new BABYLON.GroundMesh(name, scene);
  48467. ground._setReady(false);
  48468. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48469. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48470. ground._width = options.width || 1;
  48471. ground._height = options.height || 1;
  48472. ground._maxX = ground._width / 2;
  48473. ground._maxZ = ground._height / 2;
  48474. ground._minX = -ground._maxX;
  48475. ground._minZ = -ground._maxZ;
  48476. var vertexData = BABYLON.VertexData.CreateGround(options);
  48477. vertexData.applyToMesh(ground, options.updatable);
  48478. ground._setReady(true);
  48479. return ground;
  48480. };
  48481. /**
  48482. * Creates a tiled ground mesh.
  48483. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48484. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48485. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48486. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48487. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48488. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48489. * numbers of subdivisions on the ground width and height of each tile.
  48490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48491. */
  48492. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48493. var tiledGround = new BABYLON.Mesh(name, scene);
  48494. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48495. vertexData.applyToMesh(tiledGround, options.updatable);
  48496. return tiledGround;
  48497. };
  48498. /**
  48499. * Creates a ground mesh from a height map.
  48500. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48501. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48502. * The parameter `url` sets the URL of the height map image resource.
  48503. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48504. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48505. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48506. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48507. * 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.
  48508. * 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).
  48509. * This function is passed the newly built mesh :
  48510. * ```javascript
  48511. * function(mesh) { // do things
  48512. * return; }
  48513. * ```
  48514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48515. */
  48516. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48517. var width = options.width || 10.0;
  48518. var height = options.height || 10.0;
  48519. var subdivisions = options.subdivisions || 1 | 0;
  48520. var minHeight = options.minHeight || 0.0;
  48521. var maxHeight = options.maxHeight || 1.0;
  48522. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48523. var updatable = options.updatable;
  48524. var onReady = options.onReady;
  48525. var ground = new BABYLON.GroundMesh(name, scene);
  48526. ground._subdivisionsX = subdivisions;
  48527. ground._subdivisionsY = subdivisions;
  48528. ground._width = width;
  48529. ground._height = height;
  48530. ground._maxX = ground._width / 2.0;
  48531. ground._maxZ = ground._height / 2.0;
  48532. ground._minX = -ground._maxX;
  48533. ground._minZ = -ground._maxZ;
  48534. ground._setReady(false);
  48535. var onload = function (img) {
  48536. // Getting height map data
  48537. var canvas = document.createElement("canvas");
  48538. var context = canvas.getContext("2d");
  48539. if (!context) {
  48540. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48541. }
  48542. var bufferWidth = img.width;
  48543. var bufferHeight = img.height;
  48544. canvas.width = bufferWidth;
  48545. canvas.height = bufferHeight;
  48546. context.drawImage(img, 0, 0);
  48547. // Create VertexData from map data
  48548. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48549. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48550. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48551. width: width, height: height,
  48552. subdivisions: subdivisions,
  48553. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48554. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48555. });
  48556. vertexData.applyToMesh(ground, updatable);
  48557. ground._setReady(true);
  48558. //execute ready callback, if set
  48559. if (onReady) {
  48560. onReady(ground);
  48561. }
  48562. };
  48563. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48564. return ground;
  48565. };
  48566. /**
  48567. * Creates a polygon mesh.
  48568. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48569. * 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.
  48570. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48571. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48572. * 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).
  48573. * Remember you can only change the shape positions, not their number when updating a polygon.
  48574. */
  48575. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48576. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48577. var shape = options.shape;
  48578. var holes = options.holes || [];
  48579. var depth = options.depth || 0;
  48580. var contours = [];
  48581. var hole = [];
  48582. for (var i = 0; i < shape.length; i++) {
  48583. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48584. }
  48585. var epsilon = 0.00000001;
  48586. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48587. contours.pop();
  48588. }
  48589. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48590. for (var hNb = 0; hNb < holes.length; hNb++) {
  48591. hole = [];
  48592. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48593. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48594. }
  48595. polygonTriangulation.addHole(hole);
  48596. }
  48597. var polygon = polygonTriangulation.build(options.updatable, depth);
  48598. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48599. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48600. vertexData.applyToMesh(polygon, options.updatable);
  48601. return polygon;
  48602. };
  48603. ;
  48604. /**
  48605. * Creates an extruded polygon mesh, with depth in the Y direction.
  48606. * 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).
  48607. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48608. */
  48609. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48610. return MeshBuilder.CreatePolygon(name, options, scene);
  48611. };
  48612. ;
  48613. /**
  48614. * Creates a tube mesh.
  48615. * 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.
  48616. *
  48617. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48618. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48619. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48620. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48621. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48622. * 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.
  48623. * It must return a radius value (positive float) :
  48624. * ```javascript
  48625. * var radiusFunction = function(i, distance) {
  48626. * // do things
  48627. * return radius; }
  48628. * ```
  48629. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48630. * 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
  48631. * 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
  48632. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48633. * 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).
  48634. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48635. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48637. */
  48638. MeshBuilder.CreateTube = function (name, options, scene) {
  48639. var path = options.path;
  48640. var instance = options.instance;
  48641. var radius = 1.0;
  48642. if (instance) {
  48643. radius = instance.radius;
  48644. }
  48645. if (options.radius !== undefined) {
  48646. radius = options.radius;
  48647. }
  48648. ;
  48649. var tessellation = options.tessellation || 64 | 0;
  48650. var radiusFunction = options.radiusFunction || null;
  48651. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48652. var invertUV = options.invertUV || false;
  48653. var updatable = options.updatable;
  48654. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48655. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48656. // tube geometry
  48657. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48658. var tangents = path3D.getTangents();
  48659. var normals = path3D.getNormals();
  48660. var distances = path3D.getDistances();
  48661. var pi2 = Math.PI * 2;
  48662. var step = pi2 / tessellation * arc;
  48663. var returnRadius = function () { return radius; };
  48664. var radiusFunctionFinal = radiusFunction || returnRadius;
  48665. var circlePath;
  48666. var rad;
  48667. var normal;
  48668. var rotated;
  48669. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48670. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48671. for (var i = 0; i < path.length; i++) {
  48672. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48673. circlePath = Array(); // current circle array
  48674. normal = normals[i]; // current normal
  48675. for (var t = 0; t < tessellation; t++) {
  48676. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48677. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48678. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48679. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48680. circlePath[t] = rotated;
  48681. }
  48682. circlePaths[index] = circlePath;
  48683. index++;
  48684. }
  48685. // cap
  48686. var capPath = function (nbPoints, pathIndex) {
  48687. var pointCap = Array();
  48688. for (var i = 0; i < nbPoints; i++) {
  48689. pointCap.push(path[pathIndex]);
  48690. }
  48691. return pointCap;
  48692. };
  48693. switch (cap) {
  48694. case BABYLON.Mesh.NO_CAP:
  48695. break;
  48696. case BABYLON.Mesh.CAP_START:
  48697. circlePaths[0] = capPath(tessellation, 0);
  48698. circlePaths[1] = circlePaths[2].slice(0);
  48699. break;
  48700. case BABYLON.Mesh.CAP_END:
  48701. circlePaths[index] = circlePaths[index - 1].slice(0);
  48702. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48703. break;
  48704. case BABYLON.Mesh.CAP_ALL:
  48705. circlePaths[0] = capPath(tessellation, 0);
  48706. circlePaths[1] = circlePaths[2].slice(0);
  48707. circlePaths[index] = circlePaths[index - 1].slice(0);
  48708. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48709. break;
  48710. default:
  48711. break;
  48712. }
  48713. return circlePaths;
  48714. };
  48715. var path3D;
  48716. var pathArray;
  48717. if (instance) {
  48718. var arc = options.arc || instance.arc;
  48719. path3D = (instance.path3D).update(path);
  48720. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48721. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48722. instance.path3D = path3D;
  48723. instance.pathArray = pathArray;
  48724. instance.arc = arc;
  48725. instance.radius = radius;
  48726. return instance;
  48727. }
  48728. // tube creation
  48729. path3D = new BABYLON.Path3D(path);
  48730. var newPathArray = new Array();
  48731. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48732. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48733. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48734. tube.pathArray = pathArray;
  48735. tube.path3D = path3D;
  48736. tube.tessellation = tessellation;
  48737. tube.cap = cap;
  48738. tube.arc = options.arc;
  48739. tube.radius = radius;
  48740. return tube;
  48741. };
  48742. /**
  48743. * Creates a polyhedron mesh.
  48744. *
  48745. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48746. * 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
  48747. * to choose the wanted type.
  48748. * The parameter `size` (positive float, default 1) sets the polygon size.
  48749. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48750. * 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`.
  48751. * 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
  48752. * 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)`).
  48753. * 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
  48754. * 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.
  48755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48756. * 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).
  48757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48759. */
  48760. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48761. var polyhedron = new BABYLON.Mesh(name, scene);
  48762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48763. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48764. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48765. vertexData.applyToMesh(polyhedron, options.updatable);
  48766. return polyhedron;
  48767. };
  48768. /**
  48769. * Creates a decal mesh.
  48770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48771. * 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.
  48772. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48773. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48774. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48775. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48776. */
  48777. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48778. var indices = sourceMesh.getIndices();
  48779. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48780. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48781. var position = options.position || BABYLON.Vector3.Zero();
  48782. var normal = options.normal || BABYLON.Vector3.Up();
  48783. var size = options.size || BABYLON.Vector3.One();
  48784. var angle = options.angle || 0;
  48785. // Getting correct rotation
  48786. if (!normal) {
  48787. var target = new BABYLON.Vector3(0, 0, 1);
  48788. var camera = sourceMesh.getScene().activeCamera;
  48789. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48790. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48791. }
  48792. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48793. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48794. var pitch = Math.atan2(normal.y, len);
  48795. // Matrix
  48796. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48797. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48798. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48799. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48800. var vertexData = new BABYLON.VertexData();
  48801. vertexData.indices = [];
  48802. vertexData.positions = [];
  48803. vertexData.normals = [];
  48804. vertexData.uvs = [];
  48805. var currentVertexDataIndex = 0;
  48806. var extractDecalVector3 = function (indexId) {
  48807. var result = new BABYLON.PositionNormalVertex();
  48808. if (!indices || !positions || !normals) {
  48809. return result;
  48810. }
  48811. var vertexId = indices[indexId];
  48812. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48813. // Send vector to decal local world
  48814. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48815. // Get normal
  48816. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48817. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48818. return result;
  48819. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48820. var clip = function (vertices, axis) {
  48821. if (vertices.length === 0) {
  48822. return vertices;
  48823. }
  48824. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48825. var clipVertices = function (v0, v1) {
  48826. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48827. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48828. };
  48829. var result = new Array();
  48830. for (var index = 0; index < vertices.length; index += 3) {
  48831. var v1Out;
  48832. var v2Out;
  48833. var v3Out;
  48834. var total = 0;
  48835. var nV1 = null;
  48836. var nV2 = null;
  48837. var nV3 = null;
  48838. var nV4 = null;
  48839. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48840. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48841. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48842. v1Out = d1 > 0;
  48843. v2Out = d2 > 0;
  48844. v3Out = d3 > 0;
  48845. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48846. switch (total) {
  48847. case 0:
  48848. result.push(vertices[index]);
  48849. result.push(vertices[index + 1]);
  48850. result.push(vertices[index + 2]);
  48851. break;
  48852. case 1:
  48853. if (v1Out) {
  48854. nV1 = vertices[index + 1];
  48855. nV2 = vertices[index + 2];
  48856. nV3 = clipVertices(vertices[index], nV1);
  48857. nV4 = clipVertices(vertices[index], nV2);
  48858. }
  48859. if (v2Out) {
  48860. nV1 = vertices[index];
  48861. nV2 = vertices[index + 2];
  48862. nV3 = clipVertices(vertices[index + 1], nV1);
  48863. nV4 = clipVertices(vertices[index + 1], nV2);
  48864. result.push(nV3);
  48865. result.push(nV2.clone());
  48866. result.push(nV1.clone());
  48867. result.push(nV2.clone());
  48868. result.push(nV3.clone());
  48869. result.push(nV4);
  48870. break;
  48871. }
  48872. if (v3Out) {
  48873. nV1 = vertices[index];
  48874. nV2 = vertices[index + 1];
  48875. nV3 = clipVertices(vertices[index + 2], nV1);
  48876. nV4 = clipVertices(vertices[index + 2], nV2);
  48877. }
  48878. if (nV1 && nV2 && nV3 && nV4) {
  48879. result.push(nV1.clone());
  48880. result.push(nV2.clone());
  48881. result.push(nV3);
  48882. result.push(nV4);
  48883. result.push(nV3.clone());
  48884. result.push(nV2.clone());
  48885. }
  48886. break;
  48887. case 2:
  48888. if (!v1Out) {
  48889. nV1 = vertices[index].clone();
  48890. nV2 = clipVertices(nV1, vertices[index + 1]);
  48891. nV3 = clipVertices(nV1, vertices[index + 2]);
  48892. result.push(nV1);
  48893. result.push(nV2);
  48894. result.push(nV3);
  48895. }
  48896. if (!v2Out) {
  48897. nV1 = vertices[index + 1].clone();
  48898. nV2 = clipVertices(nV1, vertices[index + 2]);
  48899. nV3 = clipVertices(nV1, vertices[index]);
  48900. result.push(nV1);
  48901. result.push(nV2);
  48902. result.push(nV3);
  48903. }
  48904. if (!v3Out) {
  48905. nV1 = vertices[index + 2].clone();
  48906. nV2 = clipVertices(nV1, vertices[index]);
  48907. nV3 = clipVertices(nV1, vertices[index + 1]);
  48908. result.push(nV1);
  48909. result.push(nV2);
  48910. result.push(nV3);
  48911. }
  48912. break;
  48913. case 3:
  48914. break;
  48915. }
  48916. }
  48917. return result;
  48918. };
  48919. for (var index = 0; index < indices.length; index += 3) {
  48920. var faceVertices = new Array();
  48921. faceVertices.push(extractDecalVector3(index));
  48922. faceVertices.push(extractDecalVector3(index + 1));
  48923. faceVertices.push(extractDecalVector3(index + 2));
  48924. // Clip
  48925. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48926. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48927. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48928. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48929. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48930. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48931. if (faceVertices.length === 0) {
  48932. continue;
  48933. }
  48934. // Add UVs and get back to world
  48935. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48936. var vertex = faceVertices[vIndex];
  48937. //TODO check for Int32Array | Uint32Array | Uint16Array
  48938. vertexData.indices.push(currentVertexDataIndex);
  48939. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48940. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48941. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48942. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48943. currentVertexDataIndex++;
  48944. }
  48945. }
  48946. // Return mesh
  48947. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48948. vertexData.applyToMesh(decal);
  48949. decal.position = position.clone();
  48950. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48951. return decal;
  48952. };
  48953. // Privates
  48954. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48955. // extrusion geometry
  48956. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48957. var tangents = path3D.getTangents();
  48958. var normals = path3D.getNormals();
  48959. var binormals = path3D.getBinormals();
  48960. var distances = path3D.getDistances();
  48961. var angle = 0;
  48962. var returnScale = function () { return scale !== null ? scale : 1; };
  48963. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48964. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48965. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48966. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48967. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48968. for (var i = 0; i < curve.length; i++) {
  48969. var shapePath = new Array();
  48970. var angleStep = rotate(i, distances[i]);
  48971. var scaleRatio = scl(i, distances[i]);
  48972. for (var p = 0; p < shape.length; p++) {
  48973. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48974. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48975. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48976. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48977. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48978. shapePath[p] = rotated;
  48979. }
  48980. shapePaths[index] = shapePath;
  48981. angle += angleStep;
  48982. index++;
  48983. }
  48984. // cap
  48985. var capPath = function (shapePath) {
  48986. var pointCap = Array();
  48987. var barycenter = BABYLON.Vector3.Zero();
  48988. var i;
  48989. for (i = 0; i < shapePath.length; i++) {
  48990. barycenter.addInPlace(shapePath[i]);
  48991. }
  48992. barycenter.scaleInPlace(1.0 / shapePath.length);
  48993. for (i = 0; i < shapePath.length; i++) {
  48994. pointCap.push(barycenter);
  48995. }
  48996. return pointCap;
  48997. };
  48998. switch (cap) {
  48999. case BABYLON.Mesh.NO_CAP:
  49000. break;
  49001. case BABYLON.Mesh.CAP_START:
  49002. shapePaths[0] = capPath(shapePaths[2]);
  49003. shapePaths[1] = shapePaths[2];
  49004. break;
  49005. case BABYLON.Mesh.CAP_END:
  49006. shapePaths[index] = shapePaths[index - 1];
  49007. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49008. break;
  49009. case BABYLON.Mesh.CAP_ALL:
  49010. shapePaths[0] = capPath(shapePaths[2]);
  49011. shapePaths[1] = shapePaths[2];
  49012. shapePaths[index] = shapePaths[index - 1];
  49013. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49014. break;
  49015. default:
  49016. break;
  49017. }
  49018. return shapePaths;
  49019. };
  49020. var path3D;
  49021. var pathArray;
  49022. if (instance) {
  49023. path3D = (instance.path3D).update(curve);
  49024. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  49025. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  49026. return instance;
  49027. }
  49028. // extruded shape creation
  49029. path3D = new BABYLON.Path3D(curve);
  49030. var newShapePaths = new Array();
  49031. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49032. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  49033. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  49034. extrudedGeneric.pathArray = pathArray;
  49035. extrudedGeneric.path3D = path3D;
  49036. extrudedGeneric.cap = cap;
  49037. return extrudedGeneric;
  49038. };
  49039. return MeshBuilder;
  49040. }());
  49041. BABYLON.MeshBuilder = MeshBuilder;
  49042. })(BABYLON || (BABYLON = {}));
  49043. //# sourceMappingURL=babylon.meshBuilder.js.map
  49044. var BABYLON;
  49045. (function (BABYLON) {
  49046. var AudioEngine = /** @class */ (function () {
  49047. function AudioEngine() {
  49048. this._audioContext = null;
  49049. this._audioContextInitialized = false;
  49050. this.canUseWebAudio = false;
  49051. this.WarnedWebAudioUnsupported = false;
  49052. this.unlocked = false;
  49053. this.isMP3supported = false;
  49054. this.isOGGsupported = false;
  49055. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  49056. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  49057. this.canUseWebAudio = true;
  49058. }
  49059. var audioElem = document.createElement('audio');
  49060. try {
  49061. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  49062. this.isMP3supported = true;
  49063. }
  49064. }
  49065. catch (e) {
  49066. // protect error during capability check.
  49067. }
  49068. try {
  49069. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  49070. this.isOGGsupported = true;
  49071. }
  49072. }
  49073. catch (e) {
  49074. // protect error during capability check.
  49075. }
  49076. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  49077. this._unlockiOSaudio();
  49078. }
  49079. else {
  49080. this.unlocked = true;
  49081. }
  49082. }
  49083. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  49084. get: function () {
  49085. if (!this._audioContextInitialized) {
  49086. this._initializeAudioContext();
  49087. }
  49088. return this._audioContext;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. AudioEngine.prototype._unlockiOSaudio = function () {
  49094. var _this = this;
  49095. var unlockaudio = function () {
  49096. if (!_this.audioContext) {
  49097. return;
  49098. }
  49099. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  49100. var source = _this.audioContext.createBufferSource();
  49101. source.buffer = buffer;
  49102. source.connect(_this.audioContext.destination);
  49103. source.start(0);
  49104. setTimeout(function () {
  49105. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  49106. _this.unlocked = true;
  49107. window.removeEventListener('touchend', unlockaudio, false);
  49108. if (_this.onAudioUnlocked) {
  49109. _this.onAudioUnlocked();
  49110. }
  49111. }
  49112. }, 0);
  49113. };
  49114. window.addEventListener('touchend', unlockaudio, false);
  49115. };
  49116. AudioEngine.prototype._initializeAudioContext = function () {
  49117. try {
  49118. if (this.canUseWebAudio) {
  49119. this._audioContext = new AudioContext();
  49120. // create a global volume gain node
  49121. this.masterGain = this._audioContext.createGain();
  49122. this.masterGain.gain.value = 1;
  49123. this.masterGain.connect(this._audioContext.destination);
  49124. this._audioContextInitialized = true;
  49125. }
  49126. }
  49127. catch (e) {
  49128. this.canUseWebAudio = false;
  49129. BABYLON.Tools.Error("Web Audio: " + e.message);
  49130. }
  49131. };
  49132. AudioEngine.prototype.dispose = function () {
  49133. if (this.canUseWebAudio && this._audioContextInitialized) {
  49134. if (this._connectedAnalyser && this._audioContext) {
  49135. this._connectedAnalyser.stopDebugCanvas();
  49136. this._connectedAnalyser.dispose();
  49137. this.masterGain.disconnect();
  49138. this.masterGain.connect(this._audioContext.destination);
  49139. this._connectedAnalyser = null;
  49140. }
  49141. this.masterGain.gain.value = 1;
  49142. }
  49143. this.WarnedWebAudioUnsupported = false;
  49144. };
  49145. AudioEngine.prototype.getGlobalVolume = function () {
  49146. if (this.canUseWebAudio && this._audioContextInitialized) {
  49147. return this.masterGain.gain.value;
  49148. }
  49149. else {
  49150. return -1;
  49151. }
  49152. };
  49153. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49154. if (this.canUseWebAudio && this._audioContextInitialized) {
  49155. this.masterGain.gain.value = newVolume;
  49156. }
  49157. };
  49158. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49159. if (this._connectedAnalyser) {
  49160. this._connectedAnalyser.stopDebugCanvas();
  49161. }
  49162. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49163. this._connectedAnalyser = analyser;
  49164. this.masterGain.disconnect();
  49165. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49166. }
  49167. };
  49168. return AudioEngine;
  49169. }());
  49170. BABYLON.AudioEngine = AudioEngine;
  49171. })(BABYLON || (BABYLON = {}));
  49172. //# sourceMappingURL=babylon.audioEngine.js.map
  49173. var BABYLON;
  49174. (function (BABYLON) {
  49175. var Sound = /** @class */ (function () {
  49176. /**
  49177. * Create a sound and attach it to a scene
  49178. * @param name Name of your sound
  49179. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49180. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49181. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49182. */
  49183. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49184. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49185. var _this = this;
  49186. this.autoplay = false;
  49187. this.loop = false;
  49188. this.useCustomAttenuation = false;
  49189. this.spatialSound = false;
  49190. this.refDistance = 1;
  49191. this.rolloffFactor = 1;
  49192. this.maxDistance = 100;
  49193. this.distanceModel = "linear";
  49194. this._panningModel = "equalpower";
  49195. this._playbackRate = 1;
  49196. this._streaming = false;
  49197. this._startTime = 0;
  49198. this._startOffset = 0;
  49199. this._position = BABYLON.Vector3.Zero();
  49200. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49201. this._volume = 1;
  49202. this._isReadyToPlay = false;
  49203. this.isPlaying = false;
  49204. this.isPaused = false;
  49205. this._isDirectional = false;
  49206. // Used if you'd like to create a directional sound.
  49207. // If not set, the sound will be omnidirectional
  49208. this._coneInnerAngle = 360;
  49209. this._coneOuterAngle = 360;
  49210. this._coneOuterGain = 0;
  49211. this._isOutputConnected = false;
  49212. this._urlType = "Unknown";
  49213. this.name = name;
  49214. this._scene = scene;
  49215. this._readyToPlayCallback = readyToPlayCallback;
  49216. // Default custom attenuation function is a linear attenuation
  49217. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49218. if (currentDistance < maxDistance) {
  49219. return currentVolume * (1 - currentDistance / maxDistance);
  49220. }
  49221. else {
  49222. return 0;
  49223. }
  49224. };
  49225. if (options) {
  49226. this.autoplay = options.autoplay || false;
  49227. this.loop = options.loop || false;
  49228. // if volume === 0, we need another way to check this option
  49229. if (options.volume !== undefined) {
  49230. this._volume = options.volume;
  49231. }
  49232. this.spatialSound = options.spatialSound || false;
  49233. this.maxDistance = options.maxDistance || 100;
  49234. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49235. this.rolloffFactor = options.rolloffFactor || 1;
  49236. this.refDistance = options.refDistance || 1;
  49237. this.distanceModel = options.distanceModel || "linear";
  49238. this._playbackRate = options.playbackRate || 1;
  49239. this._streaming = options.streaming || false;
  49240. }
  49241. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49242. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49243. this._soundGain.gain.value = this._volume;
  49244. this._inputAudioNode = this._soundGain;
  49245. this._ouputAudioNode = this._soundGain;
  49246. if (this.spatialSound) {
  49247. this._createSpatialParameters();
  49248. }
  49249. this._scene.mainSoundTrack.AddSound(this);
  49250. var validParameter = true;
  49251. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49252. if (urlOrArrayBuffer) {
  49253. if (typeof (urlOrArrayBuffer) === "string")
  49254. this._urlType = "String";
  49255. if (Array.isArray(urlOrArrayBuffer))
  49256. this._urlType = "Array";
  49257. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49258. this._urlType = "ArrayBuffer";
  49259. var urls = [];
  49260. var codecSupportedFound = false;
  49261. switch (this._urlType) {
  49262. case "ArrayBuffer":
  49263. if (urlOrArrayBuffer.byteLength > 0) {
  49264. codecSupportedFound = true;
  49265. this._soundLoaded(urlOrArrayBuffer);
  49266. }
  49267. break;
  49268. case "String":
  49269. urls.push(urlOrArrayBuffer);
  49270. case "Array":
  49271. if (urls.length === 0)
  49272. urls = urlOrArrayBuffer;
  49273. // If we found a supported format, we load it immediately and stop the loop
  49274. for (var i = 0; i < urls.length; i++) {
  49275. var url = urls[i];
  49276. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49277. codecSupportedFound = true;
  49278. }
  49279. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49280. codecSupportedFound = true;
  49281. }
  49282. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49283. codecSupportedFound = true;
  49284. }
  49285. if (url.indexOf("blob:") !== -1) {
  49286. codecSupportedFound = true;
  49287. }
  49288. if (codecSupportedFound) {
  49289. // Loading sound using XHR2
  49290. if (!this._streaming) {
  49291. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49292. }
  49293. else {
  49294. this._htmlAudioElement = new Audio(url);
  49295. this._htmlAudioElement.controls = false;
  49296. this._htmlAudioElement.loop = this.loop;
  49297. this._htmlAudioElement.crossOrigin = "anonymous";
  49298. this._htmlAudioElement.preload = "auto";
  49299. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49300. _this._isReadyToPlay = true;
  49301. if (_this.autoplay) {
  49302. _this.play();
  49303. }
  49304. if (_this._readyToPlayCallback) {
  49305. _this._readyToPlayCallback();
  49306. }
  49307. });
  49308. document.body.appendChild(this._htmlAudioElement);
  49309. }
  49310. break;
  49311. }
  49312. }
  49313. break;
  49314. default:
  49315. validParameter = false;
  49316. break;
  49317. }
  49318. if (!validParameter) {
  49319. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49320. }
  49321. else {
  49322. if (!codecSupportedFound) {
  49323. this._isReadyToPlay = true;
  49324. // Simulating a ready to play event to avoid breaking code path
  49325. if (this._readyToPlayCallback) {
  49326. window.setTimeout(function () {
  49327. if (_this._readyToPlayCallback) {
  49328. _this._readyToPlayCallback();
  49329. }
  49330. }, 1000);
  49331. }
  49332. }
  49333. }
  49334. }
  49335. }
  49336. else {
  49337. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49338. this._scene.mainSoundTrack.AddSound(this);
  49339. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49340. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49341. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49342. }
  49343. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49344. if (this._readyToPlayCallback) {
  49345. window.setTimeout(function () {
  49346. if (_this._readyToPlayCallback) {
  49347. _this._readyToPlayCallback();
  49348. }
  49349. }, 1000);
  49350. }
  49351. }
  49352. }
  49353. Sound.prototype.dispose = function () {
  49354. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49355. if (this.isPlaying) {
  49356. this.stop();
  49357. }
  49358. this._isReadyToPlay = false;
  49359. if (this.soundTrackId === -1) {
  49360. this._scene.mainSoundTrack.RemoveSound(this);
  49361. }
  49362. else {
  49363. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49364. }
  49365. if (this._soundGain) {
  49366. this._soundGain.disconnect();
  49367. this._soundGain = null;
  49368. }
  49369. if (this._soundPanner) {
  49370. this._soundPanner.disconnect();
  49371. this._soundPanner = null;
  49372. }
  49373. if (this._soundSource) {
  49374. this._soundSource.disconnect();
  49375. this._soundSource = null;
  49376. }
  49377. this._audioBuffer = null;
  49378. if (this._htmlAudioElement) {
  49379. this._htmlAudioElement.pause();
  49380. this._htmlAudioElement.src = "";
  49381. document.body.removeChild(this._htmlAudioElement);
  49382. }
  49383. if (this._connectedMesh && this._registerFunc) {
  49384. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49385. this._connectedMesh = null;
  49386. }
  49387. }
  49388. };
  49389. Sound.prototype.isReady = function () {
  49390. return this._isReadyToPlay;
  49391. };
  49392. Sound.prototype._soundLoaded = function (audioData) {
  49393. var _this = this;
  49394. if (!BABYLON.Engine.audioEngine.audioContext) {
  49395. return;
  49396. }
  49397. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49398. _this._audioBuffer = buffer;
  49399. _this._isReadyToPlay = true;
  49400. if (_this.autoplay) {
  49401. _this.play();
  49402. }
  49403. if (_this._readyToPlayCallback) {
  49404. _this._readyToPlayCallback();
  49405. }
  49406. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49407. };
  49408. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49409. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49410. this._audioBuffer = audioBuffer;
  49411. this._isReadyToPlay = true;
  49412. }
  49413. };
  49414. Sound.prototype.updateOptions = function (options) {
  49415. if (options) {
  49416. this.loop = options.loop || this.loop;
  49417. this.maxDistance = options.maxDistance || this.maxDistance;
  49418. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49419. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49420. this.refDistance = options.refDistance || this.refDistance;
  49421. this.distanceModel = options.distanceModel || this.distanceModel;
  49422. this._playbackRate = options.playbackRate || this._playbackRate;
  49423. this._updateSpatialParameters();
  49424. if (this.isPlaying) {
  49425. if (this._streaming) {
  49426. this._htmlAudioElement.playbackRate = this._playbackRate;
  49427. }
  49428. else {
  49429. if (this._soundSource) {
  49430. this._soundSource.playbackRate.value = this._playbackRate;
  49431. }
  49432. }
  49433. }
  49434. }
  49435. };
  49436. Sound.prototype._createSpatialParameters = function () {
  49437. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49438. if (this._scene.headphone) {
  49439. this._panningModel = "HRTF";
  49440. }
  49441. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49442. this._updateSpatialParameters();
  49443. this._soundPanner.connect(this._ouputAudioNode);
  49444. this._inputAudioNode = this._soundPanner;
  49445. }
  49446. };
  49447. Sound.prototype._updateSpatialParameters = function () {
  49448. if (this.spatialSound && this._soundPanner) {
  49449. if (this.useCustomAttenuation) {
  49450. // Tricks to disable in a way embedded Web Audio attenuation
  49451. this._soundPanner.distanceModel = "linear";
  49452. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49453. this._soundPanner.refDistance = 1;
  49454. this._soundPanner.rolloffFactor = 1;
  49455. this._soundPanner.panningModel = this._panningModel;
  49456. }
  49457. else {
  49458. this._soundPanner.distanceModel = this.distanceModel;
  49459. this._soundPanner.maxDistance = this.maxDistance;
  49460. this._soundPanner.refDistance = this.refDistance;
  49461. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49462. this._soundPanner.panningModel = this._panningModel;
  49463. }
  49464. }
  49465. };
  49466. Sound.prototype.switchPanningModelToHRTF = function () {
  49467. this._panningModel = "HRTF";
  49468. this._switchPanningModel();
  49469. };
  49470. Sound.prototype.switchPanningModelToEqualPower = function () {
  49471. this._panningModel = "equalpower";
  49472. this._switchPanningModel();
  49473. };
  49474. Sound.prototype._switchPanningModel = function () {
  49475. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49476. this._soundPanner.panningModel = this._panningModel;
  49477. }
  49478. };
  49479. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49480. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49481. if (this._isOutputConnected) {
  49482. this._ouputAudioNode.disconnect();
  49483. }
  49484. this._ouputAudioNode.connect(soundTrackAudioNode);
  49485. this._isOutputConnected = true;
  49486. }
  49487. };
  49488. /**
  49489. * Transform this sound into a directional source
  49490. * @param coneInnerAngle Size of the inner cone in degree
  49491. * @param coneOuterAngle Size of the outer cone in degree
  49492. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49493. */
  49494. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49495. if (coneOuterAngle < coneInnerAngle) {
  49496. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49497. return;
  49498. }
  49499. this._coneInnerAngle = coneInnerAngle;
  49500. this._coneOuterAngle = coneOuterAngle;
  49501. this._coneOuterGain = coneOuterGain;
  49502. this._isDirectional = true;
  49503. if (this.isPlaying && this.loop) {
  49504. this.stop();
  49505. this.play();
  49506. }
  49507. };
  49508. Sound.prototype.setPosition = function (newPosition) {
  49509. this._position = newPosition;
  49510. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49511. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49512. }
  49513. };
  49514. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49515. this._localDirection = newLocalDirection;
  49516. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49517. this._updateDirection();
  49518. }
  49519. };
  49520. Sound.prototype._updateDirection = function () {
  49521. if (!this._connectedMesh || !this._soundPanner) {
  49522. return;
  49523. }
  49524. var mat = this._connectedMesh.getWorldMatrix();
  49525. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49526. direction.normalize();
  49527. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49528. };
  49529. Sound.prototype.updateDistanceFromListener = function () {
  49530. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49531. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49532. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49533. }
  49534. };
  49535. Sound.prototype.setAttenuationFunction = function (callback) {
  49536. this._customAttenuationFunction = callback;
  49537. };
  49538. /**
  49539. * Play the sound
  49540. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49541. * @param offset (optional) Start the sound setting it at a specific time
  49542. */
  49543. Sound.prototype.play = function (time, offset) {
  49544. var _this = this;
  49545. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49546. try {
  49547. if (this._startOffset < 0) {
  49548. time = -this._startOffset;
  49549. this._startOffset = 0;
  49550. }
  49551. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49552. if (!this._soundSource || !this._streamingSource) {
  49553. if (this.spatialSound && this._soundPanner) {
  49554. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49555. if (this._isDirectional) {
  49556. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49557. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49558. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49559. if (this._connectedMesh) {
  49560. this._updateDirection();
  49561. }
  49562. else {
  49563. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49564. }
  49565. }
  49566. }
  49567. }
  49568. if (this._streaming) {
  49569. if (!this._streamingSource) {
  49570. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49571. this._htmlAudioElement.onended = function () { _this._onended(); };
  49572. this._htmlAudioElement.playbackRate = this._playbackRate;
  49573. }
  49574. this._streamingSource.disconnect();
  49575. this._streamingSource.connect(this._inputAudioNode);
  49576. this._htmlAudioElement.play();
  49577. }
  49578. else {
  49579. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49580. this._soundSource.buffer = this._audioBuffer;
  49581. this._soundSource.connect(this._inputAudioNode);
  49582. this._soundSource.loop = this.loop;
  49583. this._soundSource.playbackRate.value = this._playbackRate;
  49584. this._soundSource.onended = function () { _this._onended(); };
  49585. if (this._soundSource.buffer) {
  49586. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49587. }
  49588. }
  49589. this._startTime = startTime;
  49590. this.isPlaying = true;
  49591. this.isPaused = false;
  49592. }
  49593. catch (ex) {
  49594. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49595. }
  49596. }
  49597. };
  49598. Sound.prototype._onended = function () {
  49599. this.isPlaying = false;
  49600. if (this.onended) {
  49601. this.onended();
  49602. }
  49603. };
  49604. /**
  49605. * Stop the sound
  49606. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49607. */
  49608. Sound.prototype.stop = function (time) {
  49609. if (this.isPlaying) {
  49610. if (this._streaming) {
  49611. this._htmlAudioElement.pause();
  49612. // Test needed for Firefox or it will generate an Invalid State Error
  49613. if (this._htmlAudioElement.currentTime > 0) {
  49614. this._htmlAudioElement.currentTime = 0;
  49615. }
  49616. }
  49617. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49618. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49619. this._soundSource.stop(stopTime);
  49620. this._soundSource.onended = function () { };
  49621. if (!this.isPaused) {
  49622. this._startOffset = 0;
  49623. }
  49624. }
  49625. this.isPlaying = false;
  49626. }
  49627. };
  49628. Sound.prototype.pause = function () {
  49629. if (this.isPlaying) {
  49630. this.isPaused = true;
  49631. if (this._streaming) {
  49632. this._htmlAudioElement.pause();
  49633. }
  49634. else if (BABYLON.Engine.audioEngine.audioContext) {
  49635. this.stop(0);
  49636. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49637. }
  49638. }
  49639. };
  49640. Sound.prototype.setVolume = function (newVolume, time) {
  49641. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49642. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49643. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49644. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49645. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49646. }
  49647. else {
  49648. this._soundGain.gain.value = newVolume;
  49649. }
  49650. }
  49651. this._volume = newVolume;
  49652. };
  49653. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49654. this._playbackRate = newPlaybackRate;
  49655. if (this.isPlaying) {
  49656. if (this._streaming) {
  49657. this._htmlAudioElement.playbackRate = this._playbackRate;
  49658. }
  49659. else if (this._soundSource) {
  49660. this._soundSource.playbackRate.value = this._playbackRate;
  49661. }
  49662. }
  49663. };
  49664. Sound.prototype.getVolume = function () {
  49665. return this._volume;
  49666. };
  49667. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49668. var _this = this;
  49669. if (this._connectedMesh && this._registerFunc) {
  49670. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49671. this._registerFunc = null;
  49672. }
  49673. this._connectedMesh = meshToConnectTo;
  49674. if (!this.spatialSound) {
  49675. this.spatialSound = true;
  49676. this._createSpatialParameters();
  49677. if (this.isPlaying && this.loop) {
  49678. this.stop();
  49679. this.play();
  49680. }
  49681. }
  49682. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49683. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49684. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49685. };
  49686. Sound.prototype.detachFromMesh = function () {
  49687. if (this._connectedMesh && this._registerFunc) {
  49688. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49689. this._registerFunc = null;
  49690. this._connectedMesh = null;
  49691. }
  49692. };
  49693. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  49694. if (!node.getBoundingInfo) {
  49695. return;
  49696. }
  49697. var mesh = node;
  49698. var boundingInfo = mesh.getBoundingInfo();
  49699. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49700. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49701. this._updateDirection();
  49702. }
  49703. };
  49704. Sound.prototype.clone = function () {
  49705. var _this = this;
  49706. if (!this._streaming) {
  49707. var setBufferAndRun = function () {
  49708. if (_this._isReadyToPlay) {
  49709. clonedSound._audioBuffer = _this.getAudioBuffer();
  49710. clonedSound._isReadyToPlay = true;
  49711. if (clonedSound.autoplay) {
  49712. clonedSound.play();
  49713. }
  49714. }
  49715. else {
  49716. window.setTimeout(setBufferAndRun, 300);
  49717. }
  49718. };
  49719. var currentOptions = {
  49720. autoplay: this.autoplay, loop: this.loop,
  49721. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49722. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49723. refDistance: this.refDistance, distanceModel: this.distanceModel
  49724. };
  49725. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49726. if (this.useCustomAttenuation) {
  49727. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49728. }
  49729. clonedSound.setPosition(this._position);
  49730. clonedSound.setPlaybackRate(this._playbackRate);
  49731. setBufferAndRun();
  49732. return clonedSound;
  49733. }
  49734. else {
  49735. return null;
  49736. }
  49737. };
  49738. Sound.prototype.getAudioBuffer = function () {
  49739. return this._audioBuffer;
  49740. };
  49741. Sound.prototype.serialize = function () {
  49742. var serializationObject = {
  49743. name: this.name,
  49744. url: this.name,
  49745. autoplay: this.autoplay,
  49746. loop: this.loop,
  49747. volume: this._volume,
  49748. spatialSound: this.spatialSound,
  49749. maxDistance: this.maxDistance,
  49750. rolloffFactor: this.rolloffFactor,
  49751. refDistance: this.refDistance,
  49752. distanceModel: this.distanceModel,
  49753. playbackRate: this._playbackRate,
  49754. panningModel: this._panningModel,
  49755. soundTrackId: this.soundTrackId
  49756. };
  49757. if (this.spatialSound) {
  49758. if (this._connectedMesh)
  49759. serializationObject.connectedMeshId = this._connectedMesh.id;
  49760. serializationObject.position = this._position.asArray();
  49761. serializationObject.refDistance = this.refDistance;
  49762. serializationObject.distanceModel = this.distanceModel;
  49763. serializationObject.isDirectional = this._isDirectional;
  49764. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49765. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49766. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49767. serializationObject.coneOuterGain = this._coneOuterGain;
  49768. }
  49769. return serializationObject;
  49770. };
  49771. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49772. var soundName = parsedSound.name;
  49773. var soundUrl;
  49774. if (parsedSound.url) {
  49775. soundUrl = rootUrl + parsedSound.url;
  49776. }
  49777. else {
  49778. soundUrl = rootUrl + soundName;
  49779. }
  49780. var options = {
  49781. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49782. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49783. rolloffFactor: parsedSound.rolloffFactor,
  49784. refDistance: parsedSound.refDistance,
  49785. distanceModel: parsedSound.distanceModel,
  49786. playbackRate: parsedSound.playbackRate
  49787. };
  49788. var newSound;
  49789. if (!sourceSound) {
  49790. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49791. scene._addPendingData(newSound);
  49792. }
  49793. else {
  49794. var setBufferAndRun = function () {
  49795. if (sourceSound._isReadyToPlay) {
  49796. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49797. newSound._isReadyToPlay = true;
  49798. if (newSound.autoplay) {
  49799. newSound.play();
  49800. }
  49801. }
  49802. else {
  49803. window.setTimeout(setBufferAndRun, 300);
  49804. }
  49805. };
  49806. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49807. setBufferAndRun();
  49808. }
  49809. if (parsedSound.position) {
  49810. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49811. newSound.setPosition(soundPosition);
  49812. }
  49813. if (parsedSound.isDirectional) {
  49814. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49815. if (parsedSound.localDirectionToMesh) {
  49816. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49817. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49818. }
  49819. }
  49820. if (parsedSound.connectedMeshId) {
  49821. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49822. if (connectedMesh) {
  49823. newSound.attachToMesh(connectedMesh);
  49824. }
  49825. }
  49826. return newSound;
  49827. };
  49828. return Sound;
  49829. }());
  49830. BABYLON.Sound = Sound;
  49831. })(BABYLON || (BABYLON = {}));
  49832. //# sourceMappingURL=babylon.sound.js.map
  49833. var BABYLON;
  49834. (function (BABYLON) {
  49835. var SoundTrack = /** @class */ (function () {
  49836. function SoundTrack(scene, options) {
  49837. this.id = -1;
  49838. this._isMainTrack = false;
  49839. this._isInitialized = false;
  49840. this._scene = scene;
  49841. this.soundCollection = new Array();
  49842. this._options = options;
  49843. if (!this._isMainTrack) {
  49844. this._scene.soundTracks.push(this);
  49845. this.id = this._scene.soundTracks.length - 1;
  49846. }
  49847. }
  49848. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49849. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49850. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49851. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49852. if (this._options) {
  49853. if (this._options.volume) {
  49854. this._outputAudioNode.gain.value = this._options.volume;
  49855. }
  49856. if (this._options.mainTrack) {
  49857. this._isMainTrack = this._options.mainTrack;
  49858. }
  49859. }
  49860. this._isInitialized = true;
  49861. }
  49862. };
  49863. SoundTrack.prototype.dispose = function () {
  49864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49865. if (this._connectedAnalyser) {
  49866. this._connectedAnalyser.stopDebugCanvas();
  49867. }
  49868. while (this.soundCollection.length) {
  49869. this.soundCollection[0].dispose();
  49870. }
  49871. if (this._outputAudioNode) {
  49872. this._outputAudioNode.disconnect();
  49873. }
  49874. this._outputAudioNode = null;
  49875. }
  49876. };
  49877. SoundTrack.prototype.AddSound = function (sound) {
  49878. if (!this._isInitialized) {
  49879. this._initializeSoundTrackAudioGraph();
  49880. }
  49881. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49882. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49883. }
  49884. if (sound.soundTrackId) {
  49885. if (sound.soundTrackId === -1) {
  49886. this._scene.mainSoundTrack.RemoveSound(sound);
  49887. }
  49888. else {
  49889. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49890. }
  49891. }
  49892. this.soundCollection.push(sound);
  49893. sound.soundTrackId = this.id;
  49894. };
  49895. SoundTrack.prototype.RemoveSound = function (sound) {
  49896. var index = this.soundCollection.indexOf(sound);
  49897. if (index !== -1) {
  49898. this.soundCollection.splice(index, 1);
  49899. }
  49900. };
  49901. SoundTrack.prototype.setVolume = function (newVolume) {
  49902. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49903. this._outputAudioNode.gain.value = newVolume;
  49904. }
  49905. };
  49906. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49907. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49908. for (var i = 0; i < this.soundCollection.length; i++) {
  49909. this.soundCollection[i].switchPanningModelToHRTF();
  49910. }
  49911. }
  49912. };
  49913. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49914. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49915. for (var i = 0; i < this.soundCollection.length; i++) {
  49916. this.soundCollection[i].switchPanningModelToEqualPower();
  49917. }
  49918. }
  49919. };
  49920. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49921. if (this._connectedAnalyser) {
  49922. this._connectedAnalyser.stopDebugCanvas();
  49923. }
  49924. this._connectedAnalyser = analyser;
  49925. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49926. this._outputAudioNode.disconnect();
  49927. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49928. }
  49929. };
  49930. return SoundTrack;
  49931. }());
  49932. BABYLON.SoundTrack = SoundTrack;
  49933. })(BABYLON || (BABYLON = {}));
  49934. //# sourceMappingURL=babylon.soundtrack.js.map
  49935. var BABYLON;
  49936. (function (BABYLON) {
  49937. var Analyser = /** @class */ (function () {
  49938. function Analyser(scene) {
  49939. this.SMOOTHING = 0.75;
  49940. this.FFT_SIZE = 512;
  49941. this.BARGRAPHAMPLITUDE = 256;
  49942. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49943. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49944. this._scene = scene;
  49945. this._audioEngine = BABYLON.Engine.audioEngine;
  49946. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49947. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49948. this._webAudioAnalyser.minDecibels = -140;
  49949. this._webAudioAnalyser.maxDecibels = 0;
  49950. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49951. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49952. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49953. }
  49954. }
  49955. Analyser.prototype.getFrequencyBinCount = function () {
  49956. if (this._audioEngine.canUseWebAudio) {
  49957. return this._webAudioAnalyser.frequencyBinCount;
  49958. }
  49959. else {
  49960. return 0;
  49961. }
  49962. };
  49963. Analyser.prototype.getByteFrequencyData = function () {
  49964. if (this._audioEngine.canUseWebAudio) {
  49965. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49966. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49967. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49968. }
  49969. return this._byteFreqs;
  49970. };
  49971. Analyser.prototype.getByteTimeDomainData = function () {
  49972. if (this._audioEngine.canUseWebAudio) {
  49973. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49974. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49975. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49976. }
  49977. return this._byteTime;
  49978. };
  49979. Analyser.prototype.getFloatFrequencyData = function () {
  49980. if (this._audioEngine.canUseWebAudio) {
  49981. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49982. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49983. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49984. }
  49985. return this._floatFreqs;
  49986. };
  49987. Analyser.prototype.drawDebugCanvas = function () {
  49988. var _this = this;
  49989. if (this._audioEngine.canUseWebAudio) {
  49990. if (!this._debugCanvas) {
  49991. this._debugCanvas = document.createElement("canvas");
  49992. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49993. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49994. this._debugCanvas.style.position = "absolute";
  49995. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49996. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49997. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49998. document.body.appendChild(this._debugCanvas);
  49999. this._registerFunc = function () {
  50000. _this.drawDebugCanvas();
  50001. };
  50002. this._scene.registerBeforeRender(this._registerFunc);
  50003. }
  50004. if (this._registerFunc && this._debugCanvasContext) {
  50005. var workingArray = this.getByteFrequencyData();
  50006. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50007. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50008. // Draw the frequency domain chart.
  50009. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50010. var value = workingArray[i];
  50011. var percent = value / this.BARGRAPHAMPLITUDE;
  50012. var height = this.DEBUGCANVASSIZE.height * percent;
  50013. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50014. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50015. var hue = i / this.getFrequencyBinCount() * 360;
  50016. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50017. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50018. }
  50019. }
  50020. }
  50021. };
  50022. Analyser.prototype.stopDebugCanvas = function () {
  50023. if (this._debugCanvas) {
  50024. if (this._registerFunc) {
  50025. this._scene.unregisterBeforeRender(this._registerFunc);
  50026. this._registerFunc = null;
  50027. }
  50028. document.body.removeChild(this._debugCanvas);
  50029. this._debugCanvas = null;
  50030. this._debugCanvasContext = null;
  50031. }
  50032. };
  50033. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50034. if (this._audioEngine.canUseWebAudio) {
  50035. inputAudioNode.connect(this._webAudioAnalyser);
  50036. this._webAudioAnalyser.connect(outputAudioNode);
  50037. }
  50038. };
  50039. Analyser.prototype.dispose = function () {
  50040. if (this._audioEngine.canUseWebAudio) {
  50041. this._webAudioAnalyser.disconnect();
  50042. }
  50043. };
  50044. return Analyser;
  50045. }());
  50046. BABYLON.Analyser = Analyser;
  50047. })(BABYLON || (BABYLON = {}));
  50048. //# sourceMappingURL=babylon.analyser.js.map
  50049. var BABYLON;
  50050. (function (BABYLON) {
  50051. var CubeTexture = /** @class */ (function (_super) {
  50052. __extends(CubeTexture, _super);
  50053. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  50054. if (extensions === void 0) { extensions = null; }
  50055. if (noMipmap === void 0) { noMipmap = false; }
  50056. if (files === void 0) { files = null; }
  50057. if (onLoad === void 0) { onLoad = null; }
  50058. if (onError === void 0) { onError = null; }
  50059. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50060. if (prefiltered === void 0) { prefiltered = false; }
  50061. if (forcedExtension === void 0) { forcedExtension = null; }
  50062. var _this = _super.call(this, scene) || this;
  50063. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50064. _this.name = rootUrl;
  50065. _this.url = rootUrl;
  50066. _this._noMipmap = noMipmap;
  50067. _this.hasAlpha = false;
  50068. _this._format = format;
  50069. _this._prefiltered = prefiltered;
  50070. _this.isCube = true;
  50071. _this._textureMatrix = BABYLON.Matrix.Identity();
  50072. if (prefiltered) {
  50073. _this.gammaSpace = false;
  50074. }
  50075. if (!rootUrl && !files) {
  50076. return _this;
  50077. }
  50078. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  50079. var lastDot = rootUrl.lastIndexOf(".");
  50080. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  50081. var isDDS = (extension === ".dds");
  50082. if (!files) {
  50083. if (!isDDS && !extensions) {
  50084. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  50085. }
  50086. files = [];
  50087. if (extensions) {
  50088. for (var index = 0; index < extensions.length; index++) {
  50089. files.push(rootUrl + extensions[index]);
  50090. }
  50091. }
  50092. }
  50093. if (!_this._texture) {
  50094. if (!scene.useDelayedTextureLoading) {
  50095. if (prefiltered) {
  50096. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  50097. }
  50098. else {
  50099. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  50100. }
  50101. }
  50102. else {
  50103. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50104. }
  50105. }
  50106. else if (onLoad) {
  50107. if (_this._texture.isReady) {
  50108. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  50109. }
  50110. else {
  50111. _this._texture.onLoadedObservable.add(onLoad);
  50112. }
  50113. }
  50114. return _this;
  50115. }
  50116. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50117. return new CubeTexture("", scene, null, noMipmap, files);
  50118. };
  50119. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50120. if (forcedExtension === void 0) { forcedExtension = null; }
  50121. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50122. };
  50123. // Methods
  50124. CubeTexture.prototype.delayLoad = function () {
  50125. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50126. return;
  50127. }
  50128. var scene = this.getScene();
  50129. if (!scene) {
  50130. return;
  50131. }
  50132. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50133. this._texture = this._getFromCache(this.url, this._noMipmap);
  50134. if (!this._texture) {
  50135. if (this._prefiltered) {
  50136. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50137. }
  50138. else {
  50139. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50140. }
  50141. }
  50142. };
  50143. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50144. return this._textureMatrix;
  50145. };
  50146. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50147. this._textureMatrix = value;
  50148. };
  50149. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50150. var texture = BABYLON.SerializationHelper.Parse(function () {
  50151. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50152. }, parsedTexture, scene);
  50153. // Animations
  50154. if (parsedTexture.animations) {
  50155. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50156. var parsedAnimation = parsedTexture.animations[animationIndex];
  50157. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50158. }
  50159. }
  50160. return texture;
  50161. };
  50162. CubeTexture.prototype.clone = function () {
  50163. var _this = this;
  50164. return BABYLON.SerializationHelper.Clone(function () {
  50165. var scene = _this.getScene();
  50166. if (!scene) {
  50167. return _this;
  50168. }
  50169. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50170. }, this);
  50171. };
  50172. return CubeTexture;
  50173. }(BABYLON.BaseTexture));
  50174. BABYLON.CubeTexture = CubeTexture;
  50175. })(BABYLON || (BABYLON = {}));
  50176. //# sourceMappingURL=babylon.cubeTexture.js.map
  50177. var BABYLON;
  50178. (function (BABYLON) {
  50179. var RenderTargetTexture = /** @class */ (function (_super) {
  50180. __extends(RenderTargetTexture, _super);
  50181. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50182. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50183. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50184. if (isCube === void 0) { isCube = false; }
  50185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50186. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50187. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50188. if (isMulti === void 0) { isMulti = false; }
  50189. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50190. _this.isCube = isCube;
  50191. /**
  50192. * Use this list to define the list of mesh you want to render.
  50193. */
  50194. _this.renderList = new Array();
  50195. _this.renderParticles = true;
  50196. _this.renderSprites = false;
  50197. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50198. _this.ignoreCameraViewport = false;
  50199. // Events
  50200. /**
  50201. * An event triggered when the texture is unbind.
  50202. * @type {BABYLON.Observable}
  50203. */
  50204. _this.onBeforeBindObservable = new BABYLON.Observable();
  50205. /**
  50206. * An event triggered when the texture is unbind.
  50207. * @type {BABYLON.Observable}
  50208. */
  50209. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50210. /**
  50211. * An event triggered before rendering the texture
  50212. * @type {BABYLON.Observable}
  50213. */
  50214. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50215. /**
  50216. * An event triggered after rendering the texture
  50217. * @type {BABYLON.Observable}
  50218. */
  50219. _this.onAfterRenderObservable = new BABYLON.Observable();
  50220. /**
  50221. * An event triggered after the texture clear
  50222. * @type {BABYLON.Observable}
  50223. */
  50224. _this.onClearObservable = new BABYLON.Observable();
  50225. _this._currentRefreshId = -1;
  50226. _this._refreshRate = 1;
  50227. _this._samples = 1;
  50228. scene = _this.getScene();
  50229. if (!scene) {
  50230. return _this;
  50231. }
  50232. _this._engine = scene.getEngine();
  50233. _this.name = name;
  50234. _this.isRenderTarget = true;
  50235. _this._initialSizeParameter = size;
  50236. _this._processSizeParameter(size);
  50237. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50238. });
  50239. _this._generateMipMaps = generateMipMaps ? true : false;
  50240. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50241. // Rendering groups
  50242. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50243. if (isMulti) {
  50244. return _this;
  50245. }
  50246. _this._renderTargetOptions = {
  50247. generateMipMaps: generateMipMaps,
  50248. type: type,
  50249. samplingMode: samplingMode,
  50250. generateDepthBuffer: generateDepthBuffer,
  50251. generateStencilBuffer: generateStencilBuffer
  50252. };
  50253. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50254. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50255. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50256. }
  50257. if (isCube) {
  50258. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50259. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50260. _this._textureMatrix = BABYLON.Matrix.Identity();
  50261. }
  50262. else {
  50263. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50264. }
  50265. return _this;
  50266. }
  50267. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50268. get: function () {
  50269. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50270. },
  50271. enumerable: true,
  50272. configurable: true
  50273. });
  50274. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50275. get: function () {
  50276. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50277. },
  50278. enumerable: true,
  50279. configurable: true
  50280. });
  50281. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50282. get: function () {
  50283. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50284. },
  50285. enumerable: true,
  50286. configurable: true
  50287. });
  50288. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50289. set: function (callback) {
  50290. if (this._onAfterUnbindObserver) {
  50291. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50292. }
  50293. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50294. },
  50295. enumerable: true,
  50296. configurable: true
  50297. });
  50298. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50299. set: function (callback) {
  50300. if (this._onBeforeRenderObserver) {
  50301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50302. }
  50303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50304. },
  50305. enumerable: true,
  50306. configurable: true
  50307. });
  50308. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50309. set: function (callback) {
  50310. if (this._onAfterRenderObserver) {
  50311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50312. }
  50313. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50314. },
  50315. enumerable: true,
  50316. configurable: true
  50317. });
  50318. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50319. set: function (callback) {
  50320. if (this._onClearObserver) {
  50321. this.onClearObservable.remove(this._onClearObserver);
  50322. }
  50323. this._onClearObserver = this.onClearObservable.add(callback);
  50324. },
  50325. enumerable: true,
  50326. configurable: true
  50327. });
  50328. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50329. get: function () {
  50330. return this._renderTargetOptions;
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. RenderTargetTexture.prototype._onRatioRescale = function () {
  50336. if (this._sizeRatio) {
  50337. this.resize(this._initialSizeParameter);
  50338. }
  50339. };
  50340. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50341. if (size.ratio) {
  50342. this._sizeRatio = size.ratio;
  50343. this._size = {
  50344. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50345. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50346. };
  50347. }
  50348. else {
  50349. this._size = size;
  50350. }
  50351. };
  50352. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50353. get: function () {
  50354. return this._samples;
  50355. },
  50356. set: function (value) {
  50357. if (this._samples === value) {
  50358. return;
  50359. }
  50360. var scene = this.getScene();
  50361. if (!scene) {
  50362. return;
  50363. }
  50364. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50365. },
  50366. enumerable: true,
  50367. configurable: true
  50368. });
  50369. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50370. this._currentRefreshId = -1;
  50371. };
  50372. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50373. get: function () {
  50374. return this._refreshRate;
  50375. },
  50376. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50377. set: function (value) {
  50378. this._refreshRate = value;
  50379. this.resetRefreshCounter();
  50380. },
  50381. enumerable: true,
  50382. configurable: true
  50383. });
  50384. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50385. if (!this._postProcessManager) {
  50386. var scene = this.getScene();
  50387. if (!scene) {
  50388. return;
  50389. }
  50390. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50391. this._postProcesses = new Array();
  50392. }
  50393. this._postProcesses.push(postProcess);
  50394. this._postProcesses[0].autoClear = false;
  50395. };
  50396. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50397. if (!this._postProcesses) {
  50398. return;
  50399. }
  50400. if (dispose) {
  50401. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50402. var postProcess = _a[_i];
  50403. postProcess.dispose();
  50404. }
  50405. }
  50406. this._postProcesses = [];
  50407. };
  50408. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50409. if (!this._postProcesses) {
  50410. return;
  50411. }
  50412. var index = this._postProcesses.indexOf(postProcess);
  50413. if (index === -1) {
  50414. return;
  50415. }
  50416. this._postProcesses.splice(index, 1);
  50417. if (this._postProcesses.length > 0) {
  50418. this._postProcesses[0].autoClear = false;
  50419. }
  50420. };
  50421. RenderTargetTexture.prototype._shouldRender = function () {
  50422. if (this._currentRefreshId === -1) {
  50423. this._currentRefreshId = 1;
  50424. return true;
  50425. }
  50426. if (this.refreshRate === this._currentRefreshId) {
  50427. this._currentRefreshId = 1;
  50428. return true;
  50429. }
  50430. this._currentRefreshId++;
  50431. return false;
  50432. };
  50433. RenderTargetTexture.prototype.getRenderSize = function () {
  50434. if (this._size.width) {
  50435. return this._size.width;
  50436. }
  50437. return this._size;
  50438. };
  50439. RenderTargetTexture.prototype.getRenderWidth = function () {
  50440. if (this._size.width) {
  50441. return this._size.width;
  50442. }
  50443. return this._size;
  50444. };
  50445. RenderTargetTexture.prototype.getRenderHeight = function () {
  50446. if (this._size.width) {
  50447. return this._size.height;
  50448. }
  50449. return this._size;
  50450. };
  50451. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50452. get: function () {
  50453. return true;
  50454. },
  50455. enumerable: true,
  50456. configurable: true
  50457. });
  50458. RenderTargetTexture.prototype.scale = function (ratio) {
  50459. var newSize = this.getRenderSize() * ratio;
  50460. this.resize(newSize);
  50461. };
  50462. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50463. if (this.isCube) {
  50464. return this._textureMatrix;
  50465. }
  50466. return _super.prototype.getReflectionTextureMatrix.call(this);
  50467. };
  50468. RenderTargetTexture.prototype.resize = function (size) {
  50469. this.releaseInternalTexture();
  50470. var scene = this.getScene();
  50471. if (!scene) {
  50472. return;
  50473. }
  50474. this._processSizeParameter(size);
  50475. if (this.isCube) {
  50476. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50477. }
  50478. else {
  50479. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50480. }
  50481. };
  50482. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50483. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50484. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50485. var scene = this.getScene();
  50486. if (!scene) {
  50487. return;
  50488. }
  50489. var engine = scene.getEngine();
  50490. if (this.useCameraPostProcesses !== undefined) {
  50491. useCameraPostProcess = this.useCameraPostProcesses;
  50492. }
  50493. if (this._waitingRenderList) {
  50494. this.renderList = [];
  50495. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50496. var id = this._waitingRenderList[index];
  50497. var mesh_1 = scene.getMeshByID(id);
  50498. if (mesh_1) {
  50499. this.renderList.push(mesh_1);
  50500. }
  50501. }
  50502. delete this._waitingRenderList;
  50503. }
  50504. // Is predicate defined?
  50505. if (this.renderListPredicate) {
  50506. if (this.renderList) {
  50507. this.renderList.splice(0); // Clear previous renderList
  50508. }
  50509. else {
  50510. this.renderList = [];
  50511. }
  50512. var scene = this.getScene();
  50513. if (!scene) {
  50514. return;
  50515. }
  50516. var sceneMeshes = scene.meshes;
  50517. for (var index = 0; index < sceneMeshes.length; index++) {
  50518. var mesh = sceneMeshes[index];
  50519. if (this.renderListPredicate(mesh)) {
  50520. this.renderList.push(mesh);
  50521. }
  50522. }
  50523. }
  50524. this.onBeforeBindObservable.notifyObservers(this);
  50525. // Set custom projection.
  50526. // Needs to be before binding to prevent changing the aspect ratio.
  50527. var camera;
  50528. if (this.activeCamera) {
  50529. camera = this.activeCamera;
  50530. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50531. if (this.activeCamera !== scene.activeCamera) {
  50532. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50533. }
  50534. }
  50535. else {
  50536. camera = scene.activeCamera;
  50537. if (camera) {
  50538. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50539. }
  50540. }
  50541. // Prepare renderingManager
  50542. this._renderingManager.reset();
  50543. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50544. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50545. var sceneRenderId = scene.getRenderId();
  50546. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50547. var mesh = currentRenderList[meshIndex];
  50548. if (mesh) {
  50549. if (!mesh.isReady()) {
  50550. // Reset _currentRefreshId
  50551. this.resetRefreshCounter();
  50552. continue;
  50553. }
  50554. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50555. var isMasked = void 0;
  50556. if (!this.renderList && camera) {
  50557. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50558. }
  50559. else {
  50560. isMasked = false;
  50561. }
  50562. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50563. mesh._activate(sceneRenderId);
  50564. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50565. var subMesh = mesh.subMeshes[subIndex];
  50566. scene._activeIndices.addCount(subMesh.indexCount, false);
  50567. this._renderingManager.dispatch(subMesh);
  50568. }
  50569. }
  50570. }
  50571. }
  50572. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50573. var particleSystem = scene.particleSystems[particleIndex];
  50574. var emitter = particleSystem.emitter;
  50575. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50576. continue;
  50577. }
  50578. if (currentRenderList.indexOf(emitter) >= 0) {
  50579. this._renderingManager.dispatchParticles(particleSystem);
  50580. }
  50581. }
  50582. if (this.isCube) {
  50583. for (var face = 0; face < 6; face++) {
  50584. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50585. scene.incrementRenderId();
  50586. scene.resetCachedMaterial();
  50587. }
  50588. }
  50589. else {
  50590. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50591. }
  50592. this.onAfterUnbindObservable.notifyObservers(this);
  50593. if (scene.activeCamera) {
  50594. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50595. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50596. }
  50597. engine.setViewport(scene.activeCamera.viewport);
  50598. }
  50599. scene.resetCachedMaterial();
  50600. };
  50601. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50602. var minimum = 128;
  50603. var x = renderDimension * scale;
  50604. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50605. // Ensure we don't exceed the render dimension (while staying POT)
  50606. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50607. };
  50608. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50609. var _this = this;
  50610. var scene = this.getScene();
  50611. if (!scene) {
  50612. return;
  50613. }
  50614. var engine = scene.getEngine();
  50615. if (!this._texture) {
  50616. return;
  50617. }
  50618. // Bind
  50619. if (this._postProcessManager) {
  50620. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50621. }
  50622. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50623. if (this._texture) {
  50624. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50625. }
  50626. }
  50627. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50628. // Clear
  50629. if (this.onClearObservable.hasObservers()) {
  50630. this.onClearObservable.notifyObservers(engine);
  50631. }
  50632. else {
  50633. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50634. }
  50635. if (!this._doNotChangeAspectRatio) {
  50636. scene.updateTransformMatrix(true);
  50637. }
  50638. // Render
  50639. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50640. if (this._postProcessManager) {
  50641. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50642. }
  50643. else if (useCameraPostProcess) {
  50644. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50645. }
  50646. if (!this._doNotChangeAspectRatio) {
  50647. scene.updateTransformMatrix(true);
  50648. }
  50649. // Dump ?
  50650. if (dumpForDebug) {
  50651. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50652. }
  50653. // Unbind
  50654. if (!this.isCube || faceIndex === 5) {
  50655. if (this.isCube) {
  50656. if (faceIndex === 5) {
  50657. engine.generateMipMapsForCubemap(this._texture);
  50658. }
  50659. }
  50660. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50661. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50662. });
  50663. }
  50664. else {
  50665. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50666. }
  50667. };
  50668. /**
  50669. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50670. * This allowed control for front to back rendering or reversly depending of the special needs.
  50671. *
  50672. * @param renderingGroupId The rendering group id corresponding to its index
  50673. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50674. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50675. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50676. */
  50677. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50678. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50679. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50680. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50681. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50682. };
  50683. /**
  50684. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50685. *
  50686. * @param renderingGroupId The rendering group id corresponding to its index
  50687. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50688. */
  50689. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50690. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50691. };
  50692. RenderTargetTexture.prototype.clone = function () {
  50693. var textureSize = this.getSize();
  50694. 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);
  50695. // Base texture
  50696. newTexture.hasAlpha = this.hasAlpha;
  50697. newTexture.level = this.level;
  50698. // RenderTarget Texture
  50699. newTexture.coordinatesMode = this.coordinatesMode;
  50700. if (this.renderList) {
  50701. newTexture.renderList = this.renderList.slice(0);
  50702. }
  50703. return newTexture;
  50704. };
  50705. RenderTargetTexture.prototype.serialize = function () {
  50706. if (!this.name) {
  50707. return null;
  50708. }
  50709. var serializationObject = _super.prototype.serialize.call(this);
  50710. serializationObject.renderTargetSize = this.getRenderSize();
  50711. serializationObject.renderList = [];
  50712. if (this.renderList) {
  50713. for (var index = 0; index < this.renderList.length; index++) {
  50714. serializationObject.renderList.push(this.renderList[index].id);
  50715. }
  50716. }
  50717. return serializationObject;
  50718. };
  50719. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50720. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50721. var objBuffer = this.getInternalTexture();
  50722. var scene = this.getScene();
  50723. if (objBuffer && scene) {
  50724. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50725. }
  50726. };
  50727. RenderTargetTexture.prototype.dispose = function () {
  50728. if (this._postProcessManager) {
  50729. this._postProcessManager.dispose();
  50730. this._postProcessManager = null;
  50731. }
  50732. this.clearPostProcesses(true);
  50733. if (this._resizeObserver) {
  50734. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50735. this._resizeObserver = null;
  50736. }
  50737. this.renderList = null;
  50738. // Remove from custom render targets
  50739. var scene = this.getScene();
  50740. if (!scene) {
  50741. return;
  50742. }
  50743. var index = scene.customRenderTargets.indexOf(this);
  50744. if (index >= 0) {
  50745. scene.customRenderTargets.splice(index, 1);
  50746. }
  50747. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50748. var camera = _a[_i];
  50749. index = camera.customRenderTargets.indexOf(this);
  50750. if (index >= 0) {
  50751. camera.customRenderTargets.splice(index, 1);
  50752. }
  50753. }
  50754. _super.prototype.dispose.call(this);
  50755. };
  50756. RenderTargetTexture.prototype._rebuild = function () {
  50757. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50758. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50759. }
  50760. if (this._postProcessManager) {
  50761. this._postProcessManager._rebuild();
  50762. }
  50763. };
  50764. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50765. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50766. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50767. return RenderTargetTexture;
  50768. }(BABYLON.Texture));
  50769. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50770. })(BABYLON || (BABYLON = {}));
  50771. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50772. var BABYLON;
  50773. (function (BABYLON) {
  50774. ;
  50775. var MultiRenderTarget = /** @class */ (function (_super) {
  50776. __extends(MultiRenderTarget, _super);
  50777. function MultiRenderTarget(name, size, count, scene, options) {
  50778. var _this = this;
  50779. options = options || {};
  50780. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50781. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50782. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50783. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50784. _this._engine = scene.getEngine();
  50785. if (!_this.isSupported) {
  50786. _this.dispose();
  50787. return;
  50788. }
  50789. var types = [];
  50790. var samplingModes = [];
  50791. for (var i = 0; i < count; i++) {
  50792. if (options.types && options.types[i]) {
  50793. types.push(options.types[i]);
  50794. }
  50795. else {
  50796. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50797. }
  50798. if (options.samplingModes && options.samplingModes[i]) {
  50799. samplingModes.push(options.samplingModes[i]);
  50800. }
  50801. else {
  50802. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50803. }
  50804. }
  50805. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50806. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50807. _this._size = size;
  50808. _this._multiRenderTargetOptions = {
  50809. samplingModes: samplingModes,
  50810. generateMipMaps: generateMipMaps,
  50811. generateDepthBuffer: generateDepthBuffer,
  50812. generateStencilBuffer: generateStencilBuffer,
  50813. generateDepthTexture: generateDepthTexture,
  50814. types: types,
  50815. textureCount: count
  50816. };
  50817. _this._createInternalTextures();
  50818. _this._createTextures();
  50819. return _this;
  50820. }
  50821. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50822. get: function () {
  50823. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50829. get: function () {
  50830. return this._textures;
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50836. get: function () {
  50837. return this._textures[this._textures.length - 1];
  50838. },
  50839. enumerable: true,
  50840. configurable: true
  50841. });
  50842. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50843. set: function (wrap) {
  50844. if (this._textures) {
  50845. for (var i = 0; i < this._textures.length; i++) {
  50846. this._textures[i].wrapU = wrap;
  50847. }
  50848. }
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50854. set: function (wrap) {
  50855. if (this._textures) {
  50856. for (var i = 0; i < this._textures.length; i++) {
  50857. this._textures[i].wrapV = wrap;
  50858. }
  50859. }
  50860. },
  50861. enumerable: true,
  50862. configurable: true
  50863. });
  50864. MultiRenderTarget.prototype._rebuild = function () {
  50865. this.releaseInternalTextures();
  50866. this._createInternalTextures();
  50867. for (var i = 0; i < this._internalTextures.length; i++) {
  50868. var texture = this._textures[i];
  50869. texture._texture = this._internalTextures[i];
  50870. }
  50871. // Keeps references to frame buffer and stencil/depth buffer
  50872. this._texture = this._internalTextures[0];
  50873. };
  50874. MultiRenderTarget.prototype._createInternalTextures = function () {
  50875. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50876. };
  50877. MultiRenderTarget.prototype._createTextures = function () {
  50878. this._textures = [];
  50879. for (var i = 0; i < this._internalTextures.length; i++) {
  50880. var texture = new BABYLON.Texture(null, this.getScene());
  50881. texture._texture = this._internalTextures[i];
  50882. this._textures.push(texture);
  50883. }
  50884. // Keeps references to frame buffer and stencil/depth buffer
  50885. this._texture = this._internalTextures[0];
  50886. };
  50887. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50888. get: function () {
  50889. return this._samples;
  50890. },
  50891. set: function (value) {
  50892. if (this._samples === value) {
  50893. return;
  50894. }
  50895. for (var i = 0; i < this._internalTextures.length; i++) {
  50896. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50897. }
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. MultiRenderTarget.prototype.resize = function (size) {
  50903. this.releaseInternalTextures();
  50904. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50905. this._createInternalTextures();
  50906. };
  50907. MultiRenderTarget.prototype.dispose = function () {
  50908. this.releaseInternalTextures();
  50909. _super.prototype.dispose.call(this);
  50910. };
  50911. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50912. if (!this._internalTextures) {
  50913. return;
  50914. }
  50915. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50916. if (this._internalTextures[i] !== undefined) {
  50917. this._internalTextures[i].dispose();
  50918. this._internalTextures.splice(i, 1);
  50919. }
  50920. }
  50921. };
  50922. return MultiRenderTarget;
  50923. }(BABYLON.RenderTargetTexture));
  50924. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50925. })(BABYLON || (BABYLON = {}));
  50926. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50927. var BABYLON;
  50928. (function (BABYLON) {
  50929. var MirrorTexture = /** @class */ (function (_super) {
  50930. __extends(MirrorTexture, _super);
  50931. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50932. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50934. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50935. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50936. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50937. _this._transformMatrix = BABYLON.Matrix.Zero();
  50938. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50939. _this._adaptiveBlurKernel = 0;
  50940. _this._blurKernelX = 0;
  50941. _this._blurKernelY = 0;
  50942. _this._blurRatio = 1.0;
  50943. _this.ignoreCameraViewport = true;
  50944. _this.onBeforeRenderObservable.add(function () {
  50945. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50946. _this._savedViewMatrix = scene.getViewMatrix();
  50947. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50948. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50949. scene.clipPlane = _this.mirrorPlane;
  50950. scene.getEngine().cullBackFaces = false;
  50951. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50952. });
  50953. _this.onAfterRenderObservable.add(function () {
  50954. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50955. scene.getEngine().cullBackFaces = true;
  50956. scene._mirroredCameraPosition = null;
  50957. delete scene.clipPlane;
  50958. });
  50959. return _this;
  50960. }
  50961. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50962. get: function () {
  50963. return this._blurRatio;
  50964. },
  50965. set: function (value) {
  50966. if (this._blurRatio === value) {
  50967. return;
  50968. }
  50969. this._blurRatio = value;
  50970. this._preparePostProcesses();
  50971. },
  50972. enumerable: true,
  50973. configurable: true
  50974. });
  50975. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50976. set: function (value) {
  50977. this._adaptiveBlurKernel = value;
  50978. this._autoComputeBlurKernel();
  50979. },
  50980. enumerable: true,
  50981. configurable: true
  50982. });
  50983. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50984. set: function (value) {
  50985. this.blurKernelX = value;
  50986. this.blurKernelY = value;
  50987. },
  50988. enumerable: true,
  50989. configurable: true
  50990. });
  50991. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50992. get: function () {
  50993. return this._blurKernelX;
  50994. },
  50995. set: function (value) {
  50996. if (this._blurKernelX === value) {
  50997. return;
  50998. }
  50999. this._blurKernelX = value;
  51000. this._preparePostProcesses();
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  51006. get: function () {
  51007. return this._blurKernelY;
  51008. },
  51009. set: function (value) {
  51010. if (this._blurKernelY === value) {
  51011. return;
  51012. }
  51013. this._blurKernelY = value;
  51014. this._preparePostProcesses();
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  51020. var engine = this.getScene().getEngine();
  51021. var dw = this.getRenderWidth() / engine.getRenderWidth();
  51022. var dh = this.getRenderHeight() / engine.getRenderHeight();
  51023. this.blurKernelX = this._adaptiveBlurKernel * dw;
  51024. this.blurKernelY = this._adaptiveBlurKernel * dh;
  51025. };
  51026. MirrorTexture.prototype._onRatioRescale = function () {
  51027. if (this._sizeRatio) {
  51028. this.resize(this._initialSizeParameter);
  51029. if (!this._adaptiveBlurKernel) {
  51030. this._preparePostProcesses();
  51031. }
  51032. }
  51033. if (this._adaptiveBlurKernel) {
  51034. this._autoComputeBlurKernel();
  51035. }
  51036. };
  51037. MirrorTexture.prototype._preparePostProcesses = function () {
  51038. this.clearPostProcesses(true);
  51039. if (this._blurKernelX && this._blurKernelY) {
  51040. var engine = this.getScene().getEngine();
  51041. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51042. 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);
  51043. this._blurX.autoClear = false;
  51044. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  51045. this._blurX.outputTexture = this._texture;
  51046. }
  51047. else {
  51048. this._blurX.alwaysForcePOT = true;
  51049. }
  51050. 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);
  51051. this._blurY.autoClear = false;
  51052. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  51053. this.addPostProcess(this._blurX);
  51054. this.addPostProcess(this._blurY);
  51055. }
  51056. else {
  51057. if (this._blurY) {
  51058. this.removePostProcess(this._blurY);
  51059. this._blurY.dispose();
  51060. this._blurY = null;
  51061. }
  51062. if (this._blurX) {
  51063. this.removePostProcess(this._blurX);
  51064. this._blurX.dispose();
  51065. this._blurX = null;
  51066. }
  51067. }
  51068. };
  51069. MirrorTexture.prototype.clone = function () {
  51070. var scene = this.getScene();
  51071. if (!scene) {
  51072. return this;
  51073. }
  51074. var textureSize = this.getSize();
  51075. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  51076. // Base texture
  51077. newTexture.hasAlpha = this.hasAlpha;
  51078. newTexture.level = this.level;
  51079. // Mirror Texture
  51080. newTexture.mirrorPlane = this.mirrorPlane.clone();
  51081. if (this.renderList) {
  51082. newTexture.renderList = this.renderList.slice(0);
  51083. }
  51084. return newTexture;
  51085. };
  51086. MirrorTexture.prototype.serialize = function () {
  51087. if (!this.name) {
  51088. return null;
  51089. }
  51090. var serializationObject = _super.prototype.serialize.call(this);
  51091. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  51092. return serializationObject;
  51093. };
  51094. return MirrorTexture;
  51095. }(BABYLON.RenderTargetTexture));
  51096. BABYLON.MirrorTexture = MirrorTexture;
  51097. })(BABYLON || (BABYLON = {}));
  51098. //# sourceMappingURL=babylon.mirrorTexture.js.map
  51099. var BABYLON;
  51100. (function (BABYLON) {
  51101. /**
  51102. * Creates a refraction texture used by refraction channel of the standard material.
  51103. * @param name the texture name
  51104. * @param size size of the underlying texture
  51105. * @param scene root scene
  51106. */
  51107. var RefractionTexture = /** @class */ (function (_super) {
  51108. __extends(RefractionTexture, _super);
  51109. function RefractionTexture(name, size, scene, generateMipMaps) {
  51110. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51111. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51112. _this.depth = 2.0;
  51113. _this.onBeforeRenderObservable.add(function () {
  51114. scene.clipPlane = _this.refractionPlane;
  51115. });
  51116. _this.onAfterRenderObservable.add(function () {
  51117. delete scene.clipPlane;
  51118. });
  51119. return _this;
  51120. }
  51121. RefractionTexture.prototype.clone = function () {
  51122. var scene = this.getScene();
  51123. if (!scene) {
  51124. return this;
  51125. }
  51126. var textureSize = this.getSize();
  51127. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51128. // Base texture
  51129. newTexture.hasAlpha = this.hasAlpha;
  51130. newTexture.level = this.level;
  51131. // Refraction Texture
  51132. newTexture.refractionPlane = this.refractionPlane.clone();
  51133. if (this.renderList) {
  51134. newTexture.renderList = this.renderList.slice(0);
  51135. }
  51136. newTexture.depth = this.depth;
  51137. return newTexture;
  51138. };
  51139. RefractionTexture.prototype.serialize = function () {
  51140. if (!this.name) {
  51141. return null;
  51142. }
  51143. var serializationObject = _super.prototype.serialize.call(this);
  51144. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51145. serializationObject.depth = this.depth;
  51146. return serializationObject;
  51147. };
  51148. return RefractionTexture;
  51149. }(BABYLON.RenderTargetTexture));
  51150. BABYLON.RefractionTexture = RefractionTexture;
  51151. })(BABYLON || (BABYLON = {}));
  51152. //# sourceMappingURL=babylon.refractionTexture.js.map
  51153. var BABYLON;
  51154. (function (BABYLON) {
  51155. var DynamicTexture = /** @class */ (function (_super) {
  51156. __extends(DynamicTexture, _super);
  51157. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51158. if (scene === void 0) { scene = null; }
  51159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51160. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51161. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51162. _this.name = name;
  51163. _this._engine = _this.getScene().getEngine();
  51164. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51165. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51166. _this._generateMipMaps = generateMipMaps;
  51167. if (options.getContext) {
  51168. _this._canvas = options;
  51169. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51170. }
  51171. else {
  51172. _this._canvas = document.createElement("canvas");
  51173. if (options.width) {
  51174. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51175. }
  51176. else {
  51177. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51178. }
  51179. }
  51180. var textureSize = _this.getSize();
  51181. _this._canvas.width = textureSize.width;
  51182. _this._canvas.height = textureSize.height;
  51183. _this._context = _this._canvas.getContext("2d");
  51184. return _this;
  51185. }
  51186. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51187. get: function () {
  51188. return true;
  51189. },
  51190. enumerable: true,
  51191. configurable: true
  51192. });
  51193. DynamicTexture.prototype._recreate = function (textureSize) {
  51194. this._canvas.width = textureSize.width;
  51195. this._canvas.height = textureSize.height;
  51196. this.releaseInternalTexture();
  51197. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51198. };
  51199. DynamicTexture.prototype.scale = function (ratio) {
  51200. var textureSize = this.getSize();
  51201. textureSize.width *= ratio;
  51202. textureSize.height *= ratio;
  51203. this._recreate(textureSize);
  51204. };
  51205. DynamicTexture.prototype.scaleTo = function (width, height) {
  51206. var textureSize = this.getSize();
  51207. textureSize.width = width;
  51208. textureSize.height = height;
  51209. this._recreate(textureSize);
  51210. };
  51211. DynamicTexture.prototype.getContext = function () {
  51212. return this._context;
  51213. };
  51214. DynamicTexture.prototype.clear = function () {
  51215. var size = this.getSize();
  51216. this._context.fillRect(0, 0, size.width, size.height);
  51217. };
  51218. DynamicTexture.prototype.update = function (invertY) {
  51219. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51220. };
  51221. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51222. if (update === void 0) { update = true; }
  51223. var size = this.getSize();
  51224. if (clearColor) {
  51225. this._context.fillStyle = clearColor;
  51226. this._context.fillRect(0, 0, size.width, size.height);
  51227. }
  51228. this._context.font = font;
  51229. if (x === null || x === undefined) {
  51230. var textSize = this._context.measureText(text);
  51231. x = (size.width - textSize.width) / 2;
  51232. }
  51233. if (y === null || y === undefined) {
  51234. var fontSize = parseInt((font.replace(/\D/g, '')));
  51235. ;
  51236. y = (size.height / 2) + (fontSize / 3.65);
  51237. }
  51238. this._context.fillStyle = color;
  51239. this._context.fillText(text, x, y);
  51240. if (update) {
  51241. this.update(invertY);
  51242. }
  51243. };
  51244. DynamicTexture.prototype.clone = function () {
  51245. var scene = this.getScene();
  51246. if (!scene) {
  51247. return this;
  51248. }
  51249. var textureSize = this.getSize();
  51250. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51251. // Base texture
  51252. newTexture.hasAlpha = this.hasAlpha;
  51253. newTexture.level = this.level;
  51254. // Dynamic Texture
  51255. newTexture.wrapU = this.wrapU;
  51256. newTexture.wrapV = this.wrapV;
  51257. return newTexture;
  51258. };
  51259. DynamicTexture.prototype._rebuild = function () {
  51260. this.update();
  51261. };
  51262. return DynamicTexture;
  51263. }(BABYLON.Texture));
  51264. BABYLON.DynamicTexture = DynamicTexture;
  51265. })(BABYLON || (BABYLON = {}));
  51266. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51267. var BABYLON;
  51268. (function (BABYLON) {
  51269. var VideoTexture = /** @class */ (function (_super) {
  51270. __extends(VideoTexture, _super);
  51271. /**
  51272. * Creates a video texture.
  51273. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51274. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51275. * @param {BABYLON.Scene} scene is obviously the current scene.
  51276. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51277. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51278. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51279. */
  51280. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51281. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51282. if (invertY === void 0) { invertY = false; }
  51283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51284. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51285. _this._autoLaunch = true;
  51286. var urls = null;
  51287. _this.name = name;
  51288. if (urlsOrVideo instanceof HTMLVideoElement) {
  51289. _this.video = urlsOrVideo;
  51290. }
  51291. else {
  51292. urls = urlsOrVideo;
  51293. _this.video = document.createElement("video");
  51294. _this.video.autoplay = false;
  51295. _this.video.loop = true;
  51296. }
  51297. _this._engine = _this.getScene().getEngine();
  51298. _this._generateMipMaps = generateMipMaps;
  51299. _this._samplingMode = samplingMode;
  51300. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51301. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51302. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51303. }
  51304. else {
  51305. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51306. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51307. _this._generateMipMaps = false;
  51308. }
  51309. if (urls) {
  51310. _this.video.addEventListener("canplay", function () {
  51311. _this._createTexture();
  51312. });
  51313. urls.forEach(function (url) {
  51314. var source = document.createElement("source");
  51315. source.src = url;
  51316. _this.video.appendChild(source);
  51317. });
  51318. }
  51319. else {
  51320. _this._createTexture();
  51321. }
  51322. _this._lastUpdate = BABYLON.Tools.Now;
  51323. return _this;
  51324. }
  51325. VideoTexture.prototype.__setTextureReady = function () {
  51326. if (this._texture) {
  51327. this._texture.isReady = true;
  51328. }
  51329. };
  51330. VideoTexture.prototype._createTexture = function () {
  51331. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51332. if (this._autoLaunch) {
  51333. this._autoLaunch = false;
  51334. this.video.play();
  51335. }
  51336. this._setTextureReady = this.__setTextureReady.bind(this);
  51337. this.video.addEventListener("playing", this._setTextureReady);
  51338. };
  51339. VideoTexture.prototype._rebuild = function () {
  51340. this.update();
  51341. };
  51342. VideoTexture.prototype.update = function () {
  51343. var now = BABYLON.Tools.Now;
  51344. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51345. return false;
  51346. }
  51347. this._lastUpdate = now;
  51348. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51349. return true;
  51350. };
  51351. VideoTexture.prototype.dispose = function () {
  51352. _super.prototype.dispose.call(this);
  51353. this.video.removeEventListener("playing", this._setTextureReady);
  51354. };
  51355. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51356. var video = document.createElement("video");
  51357. var constraintsDeviceId;
  51358. if (constraints && constraints.deviceId) {
  51359. constraintsDeviceId = {
  51360. exact: constraints.deviceId
  51361. };
  51362. }
  51363. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51364. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51365. if (navigator.getUserMedia) {
  51366. navigator.getUserMedia({
  51367. video: {
  51368. deviceId: constraintsDeviceId,
  51369. width: {
  51370. min: (constraints && constraints.minWidth) || 256,
  51371. max: (constraints && constraints.maxWidth) || 640
  51372. },
  51373. height: {
  51374. min: (constraints && constraints.minHeight) || 256,
  51375. max: (constraints && constraints.maxHeight) || 480
  51376. }
  51377. }
  51378. }, function (stream) {
  51379. if (video.mozSrcObject !== undefined) {
  51380. video.mozSrcObject = stream;
  51381. }
  51382. else {
  51383. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51384. }
  51385. video.play();
  51386. if (onReady) {
  51387. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51388. }
  51389. }, function (e) {
  51390. BABYLON.Tools.Error(e.name);
  51391. });
  51392. }
  51393. };
  51394. return VideoTexture;
  51395. }(BABYLON.Texture));
  51396. BABYLON.VideoTexture = VideoTexture;
  51397. })(BABYLON || (BABYLON = {}));
  51398. //# sourceMappingURL=babylon.videoTexture.js.map
  51399. var BABYLON;
  51400. (function (BABYLON) {
  51401. var RawTexture = /** @class */ (function (_super) {
  51402. __extends(RawTexture, _super);
  51403. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51404. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51405. if (invertY === void 0) { invertY = false; }
  51406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51407. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51408. _this.format = format;
  51409. _this._engine = scene.getEngine();
  51410. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51411. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51412. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51413. return _this;
  51414. }
  51415. RawTexture.prototype.update = function (data) {
  51416. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  51417. };
  51418. // Statics
  51419. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51420. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51421. if (invertY === void 0) { invertY = false; }
  51422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51423. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51424. };
  51425. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51426. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51427. if (invertY === void 0) { invertY = false; }
  51428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51429. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51430. };
  51431. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51432. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51433. if (invertY === void 0) { invertY = false; }
  51434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51435. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51436. };
  51437. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51438. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51439. if (invertY === void 0) { invertY = false; }
  51440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51441. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51442. };
  51443. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51444. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51445. if (invertY === void 0) { invertY = false; }
  51446. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51447. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51448. };
  51449. return RawTexture;
  51450. }(BABYLON.Texture));
  51451. BABYLON.RawTexture = RawTexture;
  51452. })(BABYLON || (BABYLON = {}));
  51453. //# sourceMappingURL=babylon.rawTexture.js.map
  51454. var BABYLON;
  51455. (function (BABYLON) {
  51456. var PostProcess = /** @class */ (function () {
  51457. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51458. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51459. if (defines === void 0) { defines = null; }
  51460. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51461. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51462. if (blockCompilation === void 0) { blockCompilation = false; }
  51463. this.name = name;
  51464. this.width = -1;
  51465. this.height = -1;
  51466. this.autoClear = true;
  51467. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51468. this.animations = new Array();
  51469. /*
  51470. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51471. Can only be used on a single postprocess or on the last one of a chain.
  51472. */
  51473. this.enablePixelPerfectMode = false;
  51474. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51475. this.alwaysForcePOT = false;
  51476. this.samples = 1;
  51477. this.adaptScaleToCurrentViewport = false;
  51478. this._reusable = false;
  51479. this._textures = new BABYLON.SmartArray(2);
  51480. this._currentRenderTextureInd = 0;
  51481. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51482. this._texelSize = BABYLON.Vector2.Zero();
  51483. // Events
  51484. /**
  51485. * An event triggered when the postprocess is activated.
  51486. * @type {BABYLON.Observable}
  51487. */
  51488. this.onActivateObservable = new BABYLON.Observable();
  51489. /**
  51490. * An event triggered when the postprocess changes its size.
  51491. * @type {BABYLON.Observable}
  51492. */
  51493. this.onSizeChangedObservable = new BABYLON.Observable();
  51494. /**
  51495. * An event triggered when the postprocess applies its effect.
  51496. * @type {BABYLON.Observable}
  51497. */
  51498. this.onApplyObservable = new BABYLON.Observable();
  51499. /**
  51500. * An event triggered before rendering the postprocess
  51501. * @type {BABYLON.Observable}
  51502. */
  51503. this.onBeforeRenderObservable = new BABYLON.Observable();
  51504. /**
  51505. * An event triggered after rendering the postprocess
  51506. * @type {BABYLON.Observable}
  51507. */
  51508. this.onAfterRenderObservable = new BABYLON.Observable();
  51509. if (camera != null) {
  51510. this._camera = camera;
  51511. this._scene = camera.getScene();
  51512. camera.attachPostProcess(this);
  51513. this._engine = this._scene.getEngine();
  51514. this._scene.postProcesses.push(this);
  51515. }
  51516. else if (engine) {
  51517. this._engine = engine;
  51518. this._engine.postProcesses.push(this);
  51519. }
  51520. this._options = options;
  51521. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51522. this._reusable = reusable || false;
  51523. this._textureType = textureType;
  51524. this._samplers = samplers || [];
  51525. this._samplers.push("textureSampler");
  51526. this._fragmentUrl = fragmentUrl;
  51527. this._vertexUrl = vertexUrl;
  51528. this._parameters = parameters || [];
  51529. this._parameters.push("scale");
  51530. this._indexParameters = indexParameters;
  51531. if (!blockCompilation) {
  51532. this.updateEffect(defines);
  51533. }
  51534. }
  51535. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51536. set: function (callback) {
  51537. if (this._onActivateObserver) {
  51538. this.onActivateObservable.remove(this._onActivateObserver);
  51539. }
  51540. if (callback) {
  51541. this._onActivateObserver = this.onActivateObservable.add(callback);
  51542. }
  51543. },
  51544. enumerable: true,
  51545. configurable: true
  51546. });
  51547. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51548. set: function (callback) {
  51549. if (this._onSizeChangedObserver) {
  51550. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51551. }
  51552. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. Object.defineProperty(PostProcess.prototype, "onApply", {
  51558. set: function (callback) {
  51559. if (this._onApplyObserver) {
  51560. this.onApplyObservable.remove(this._onApplyObserver);
  51561. }
  51562. this._onApplyObserver = this.onApplyObservable.add(callback);
  51563. },
  51564. enumerable: true,
  51565. configurable: true
  51566. });
  51567. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51568. set: function (callback) {
  51569. if (this._onBeforeRenderObserver) {
  51570. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51571. }
  51572. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51573. },
  51574. enumerable: true,
  51575. configurable: true
  51576. });
  51577. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51578. set: function (callback) {
  51579. if (this._onAfterRenderObserver) {
  51580. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51581. }
  51582. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51583. },
  51584. enumerable: true,
  51585. configurable: true
  51586. });
  51587. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51588. get: function () {
  51589. return this._textures.data[this._currentRenderTextureInd];
  51590. },
  51591. set: function (value) {
  51592. this._forcedOutputTexture = value;
  51593. },
  51594. enumerable: true,
  51595. configurable: true
  51596. });
  51597. PostProcess.prototype.getCamera = function () {
  51598. return this._camera;
  51599. };
  51600. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51601. get: function () {
  51602. if (this._shareOutputWithPostProcess) {
  51603. return this._shareOutputWithPostProcess.texelSize;
  51604. }
  51605. if (this._forcedOutputTexture) {
  51606. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51607. }
  51608. return this._texelSize;
  51609. },
  51610. enumerable: true,
  51611. configurable: true
  51612. });
  51613. PostProcess.prototype.getEngine = function () {
  51614. return this._engine;
  51615. };
  51616. PostProcess.prototype.getEffect = function () {
  51617. return this._effect;
  51618. };
  51619. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51620. this._disposeTextures();
  51621. this._shareOutputWithPostProcess = postProcess;
  51622. return this;
  51623. };
  51624. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51625. if (defines === void 0) { defines = null; }
  51626. if (uniforms === void 0) { uniforms = null; }
  51627. if (samplers === void 0) { samplers = null; }
  51628. 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);
  51629. };
  51630. PostProcess.prototype.isReusable = function () {
  51631. return this._reusable;
  51632. };
  51633. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51634. PostProcess.prototype.markTextureDirty = function () {
  51635. this.width = -1;
  51636. };
  51637. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51638. var _this = this;
  51639. if (sourceTexture === void 0) { sourceTexture = null; }
  51640. camera = camera || this._camera;
  51641. var scene = camera.getScene();
  51642. var engine = scene.getEngine();
  51643. var maxSize = engine.getCaps().maxTextureSize;
  51644. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51645. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51646. var desiredWidth = (this._options.width || requiredWidth);
  51647. var desiredHeight = this._options.height || requiredHeight;
  51648. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51649. if (this.adaptScaleToCurrentViewport) {
  51650. var currentViewport = engine.currentViewport;
  51651. if (currentViewport) {
  51652. desiredWidth *= currentViewport.width;
  51653. desiredHeight *= currentViewport.height;
  51654. }
  51655. }
  51656. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51657. if (!this._options.width) {
  51658. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51659. }
  51660. if (!this._options.height) {
  51661. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51662. }
  51663. }
  51664. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51665. if (this._textures.length > 0) {
  51666. for (var i = 0; i < this._textures.length; i++) {
  51667. this._engine._releaseTexture(this._textures.data[i]);
  51668. }
  51669. this._textures.reset();
  51670. }
  51671. this.width = desiredWidth;
  51672. this.height = desiredHeight;
  51673. var textureSize = { width: this.width, height: this.height };
  51674. var textureOptions = {
  51675. generateMipMaps: false,
  51676. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51677. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51678. samplingMode: this.renderTargetSamplingMode,
  51679. type: this._textureType
  51680. };
  51681. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51682. if (this._reusable) {
  51683. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51684. }
  51685. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51686. this.onSizeChangedObservable.notifyObservers(this);
  51687. }
  51688. this._textures.forEach(function (texture) {
  51689. if (texture.samples !== _this.samples) {
  51690. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51691. }
  51692. });
  51693. }
  51694. var target;
  51695. if (this._shareOutputWithPostProcess) {
  51696. target = this._shareOutputWithPostProcess.outputTexture;
  51697. }
  51698. else if (this._forcedOutputTexture) {
  51699. target = this._forcedOutputTexture;
  51700. this.width = this._forcedOutputTexture.width;
  51701. this.height = this._forcedOutputTexture.height;
  51702. }
  51703. else {
  51704. target = this.outputTexture;
  51705. }
  51706. if (this.enablePixelPerfectMode) {
  51707. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51708. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51709. }
  51710. else {
  51711. this._scaleRatio.copyFromFloats(1, 1);
  51712. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51713. }
  51714. this.onActivateObservable.notifyObservers(camera);
  51715. // Clear
  51716. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51717. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51718. }
  51719. if (this._reusable) {
  51720. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51721. }
  51722. };
  51723. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51724. get: function () {
  51725. return this._effect.isSupported;
  51726. },
  51727. enumerable: true,
  51728. configurable: true
  51729. });
  51730. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51731. get: function () {
  51732. if (this._shareOutputWithPostProcess) {
  51733. return this._shareOutputWithPostProcess.aspectRatio;
  51734. }
  51735. if (this._forcedOutputTexture) {
  51736. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51737. }
  51738. return this.width / this.height;
  51739. },
  51740. enumerable: true,
  51741. configurable: true
  51742. });
  51743. PostProcess.prototype.apply = function () {
  51744. // Check
  51745. if (!this._effect || !this._effect.isReady())
  51746. return null;
  51747. // States
  51748. this._engine.enableEffect(this._effect);
  51749. this._engine.setState(false);
  51750. this._engine.setDepthBuffer(false);
  51751. this._engine.setDepthWrite(false);
  51752. // Alpha
  51753. this._engine.setAlphaMode(this.alphaMode);
  51754. if (this.alphaConstants) {
  51755. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51756. }
  51757. // Texture
  51758. var source;
  51759. if (this._shareOutputWithPostProcess) {
  51760. source = this._shareOutputWithPostProcess.outputTexture;
  51761. }
  51762. else if (this._forcedOutputTexture) {
  51763. source = this._forcedOutputTexture;
  51764. }
  51765. else {
  51766. source = this.outputTexture;
  51767. }
  51768. this._effect._bindTexture("textureSampler", source);
  51769. // Parameters
  51770. this._effect.setVector2("scale", this._scaleRatio);
  51771. this.onApplyObservable.notifyObservers(this._effect);
  51772. return this._effect;
  51773. };
  51774. PostProcess.prototype._disposeTextures = function () {
  51775. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51776. return;
  51777. }
  51778. if (this._textures.length > 0) {
  51779. for (var i = 0; i < this._textures.length; i++) {
  51780. this._engine._releaseTexture(this._textures.data[i]);
  51781. }
  51782. }
  51783. this._textures.dispose();
  51784. };
  51785. PostProcess.prototype.dispose = function (camera) {
  51786. camera = camera || this._camera;
  51787. this._disposeTextures();
  51788. if (this._scene) {
  51789. var index_1 = this._scene.postProcesses.indexOf(this);
  51790. if (index_1 !== -1) {
  51791. this._scene.postProcesses.splice(index_1, 1);
  51792. }
  51793. }
  51794. else {
  51795. var index_2 = this._engine.postProcesses.indexOf(this);
  51796. if (index_2 !== -1) {
  51797. this._engine.postProcesses.splice(index_2, 1);
  51798. }
  51799. }
  51800. if (!camera) {
  51801. return;
  51802. }
  51803. camera.detachPostProcess(this);
  51804. var index = camera._postProcesses.indexOf(this);
  51805. if (index === 0 && camera._postProcesses.length > 0) {
  51806. this._camera._postProcesses[0].markTextureDirty();
  51807. }
  51808. this.onActivateObservable.clear();
  51809. this.onAfterRenderObservable.clear();
  51810. this.onApplyObservable.clear();
  51811. this.onBeforeRenderObservable.clear();
  51812. this.onSizeChangedObservable.clear();
  51813. };
  51814. return PostProcess;
  51815. }());
  51816. BABYLON.PostProcess = PostProcess;
  51817. })(BABYLON || (BABYLON = {}));
  51818. //# sourceMappingURL=babylon.postProcess.js.map
  51819. var BABYLON;
  51820. (function (BABYLON) {
  51821. var PassPostProcess = /** @class */ (function (_super) {
  51822. __extends(PassPostProcess, _super);
  51823. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51824. if (camera === void 0) { camera = null; }
  51825. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51826. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51827. }
  51828. return PassPostProcess;
  51829. }(BABYLON.PostProcess));
  51830. BABYLON.PassPostProcess = PassPostProcess;
  51831. })(BABYLON || (BABYLON = {}));
  51832. //# sourceMappingURL=babylon.passPostProcess.js.map
  51833. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51834. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51835. s = arguments[i];
  51836. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51837. t[p] = s[p];
  51838. }
  51839. return t;
  51840. };
  51841. var BABYLON;
  51842. (function (BABYLON) {
  51843. var ShadowGenerator = /** @class */ (function () {
  51844. /**
  51845. * Creates a ShadowGenerator object.
  51846. * A ShadowGenerator is the required tool to use the shadows.
  51847. * Each light casting shadows needs to use its own ShadowGenerator.
  51848. * Required parameters :
  51849. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51850. * - `light`: the light object generating the shadows.
  51851. * - `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.
  51852. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51853. */
  51854. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51855. // Members
  51856. this._bias = 0.00005;
  51857. this._blurBoxOffset = 1;
  51858. this._blurScale = 2;
  51859. this._blurKernel = 1;
  51860. this._useKernelBlur = false;
  51861. this._filter = ShadowGenerator.FILTER_NONE;
  51862. this._darkness = 0;
  51863. this._transparencyShadow = false;
  51864. /**
  51865. * Controls the extent to which the shadows fade out at the edge of the frustum
  51866. * Used only by directionals and spots
  51867. */
  51868. this.frustumEdgeFalloff = 0;
  51869. this.forceBackFacesOnly = false;
  51870. this._lightDirection = BABYLON.Vector3.Zero();
  51871. this._viewMatrix = BABYLON.Matrix.Zero();
  51872. this._projectionMatrix = BABYLON.Matrix.Zero();
  51873. this._transformMatrix = BABYLON.Matrix.Zero();
  51874. this._currentFaceIndex = 0;
  51875. this._currentFaceIndexCache = 0;
  51876. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51877. this._mapSize = mapSize;
  51878. this._light = light;
  51879. this._scene = light.getScene();
  51880. light._shadowGenerator = this;
  51881. // Texture type fallback from float to int if not supported.
  51882. var caps = this._scene.getEngine().getCaps();
  51883. if (!useFullFloatFirst) {
  51884. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51885. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51886. }
  51887. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51888. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51889. }
  51890. else {
  51891. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51892. }
  51893. }
  51894. else {
  51895. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51896. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51897. }
  51898. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51899. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51900. }
  51901. else {
  51902. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51903. }
  51904. }
  51905. this._initializeGenerator();
  51906. }
  51907. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51908. // Static
  51909. get: function () {
  51910. return ShadowGenerator._FILTER_NONE;
  51911. },
  51912. enumerable: true,
  51913. configurable: true
  51914. });
  51915. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51916. get: function () {
  51917. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51918. },
  51919. enumerable: true,
  51920. configurable: true
  51921. });
  51922. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51923. get: function () {
  51924. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51925. },
  51926. enumerable: true,
  51927. configurable: true
  51928. });
  51929. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51930. get: function () {
  51931. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51932. },
  51933. enumerable: true,
  51934. configurable: true
  51935. });
  51936. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51937. get: function () {
  51938. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51944. get: function () {
  51945. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51946. },
  51947. enumerable: true,
  51948. configurable: true
  51949. });
  51950. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51951. get: function () {
  51952. return this._bias;
  51953. },
  51954. set: function (bias) {
  51955. this._bias = bias;
  51956. },
  51957. enumerable: true,
  51958. configurable: true
  51959. });
  51960. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51961. get: function () {
  51962. return this._blurBoxOffset;
  51963. },
  51964. set: function (value) {
  51965. if (this._blurBoxOffset === value) {
  51966. return;
  51967. }
  51968. this._blurBoxOffset = value;
  51969. this._disposeBlurPostProcesses();
  51970. },
  51971. enumerable: true,
  51972. configurable: true
  51973. });
  51974. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51975. get: function () {
  51976. return this._blurScale;
  51977. },
  51978. set: function (value) {
  51979. if (this._blurScale === value) {
  51980. return;
  51981. }
  51982. this._blurScale = value;
  51983. this._disposeBlurPostProcesses();
  51984. },
  51985. enumerable: true,
  51986. configurable: true
  51987. });
  51988. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51989. get: function () {
  51990. return this._blurKernel;
  51991. },
  51992. set: function (value) {
  51993. if (this._blurKernel === value) {
  51994. return;
  51995. }
  51996. this._blurKernel = value;
  51997. this._disposeBlurPostProcesses();
  51998. },
  51999. enumerable: true,
  52000. configurable: true
  52001. });
  52002. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  52003. get: function () {
  52004. return this._useKernelBlur;
  52005. },
  52006. set: function (value) {
  52007. if (this._useKernelBlur === value) {
  52008. return;
  52009. }
  52010. this._useKernelBlur = value;
  52011. this._disposeBlurPostProcesses();
  52012. },
  52013. enumerable: true,
  52014. configurable: true
  52015. });
  52016. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  52017. get: function () {
  52018. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  52019. },
  52020. set: function (value) {
  52021. this._depthScale = value;
  52022. },
  52023. enumerable: true,
  52024. configurable: true
  52025. });
  52026. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  52027. get: function () {
  52028. return this._filter;
  52029. },
  52030. set: function (value) {
  52031. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  52032. if (this._light.needCube()) {
  52033. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52034. this.useExponentialShadowMap = true;
  52035. return;
  52036. }
  52037. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52038. this.useCloseExponentialShadowMap = true;
  52039. return;
  52040. }
  52041. }
  52042. if (this._filter === value) {
  52043. return;
  52044. }
  52045. this._filter = value;
  52046. this._disposeBlurPostProcesses();
  52047. this._applyFilterValues();
  52048. this._light._markMeshesAsLightDirty();
  52049. },
  52050. enumerable: true,
  52051. configurable: true
  52052. });
  52053. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  52054. get: function () {
  52055. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  52056. },
  52057. set: function (value) {
  52058. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  52059. return;
  52060. }
  52061. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  52062. },
  52063. enumerable: true,
  52064. configurable: true
  52065. });
  52066. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  52067. get: function () {
  52068. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52069. return this.useExponentialShadowMap;
  52070. },
  52071. set: function (value) {
  52072. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52073. this.useExponentialShadowMap = value;
  52074. },
  52075. enumerable: true,
  52076. configurable: true
  52077. });
  52078. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  52079. get: function () {
  52080. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52081. return this.useBlurExponentialShadowMap;
  52082. },
  52083. set: function (value) {
  52084. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52085. this.useBlurExponentialShadowMap = value;
  52086. },
  52087. enumerable: true,
  52088. configurable: true
  52089. });
  52090. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  52091. get: function () {
  52092. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  52093. },
  52094. set: function (value) {
  52095. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  52096. return;
  52097. }
  52098. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52099. },
  52100. enumerable: true,
  52101. configurable: true
  52102. });
  52103. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  52104. get: function () {
  52105. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  52106. },
  52107. set: function (value) {
  52108. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52109. return;
  52110. }
  52111. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52112. },
  52113. enumerable: true,
  52114. configurable: true
  52115. });
  52116. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52117. get: function () {
  52118. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52119. },
  52120. set: function (value) {
  52121. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52122. return;
  52123. }
  52124. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52125. },
  52126. enumerable: true,
  52127. configurable: true
  52128. });
  52129. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52130. get: function () {
  52131. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52132. },
  52133. set: function (value) {
  52134. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52135. return;
  52136. }
  52137. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52138. },
  52139. enumerable: true,
  52140. configurable: true
  52141. });
  52142. /**
  52143. * Returns the darkness value (float).
  52144. */
  52145. ShadowGenerator.prototype.getDarkness = function () {
  52146. return this._darkness;
  52147. };
  52148. /**
  52149. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52150. * Returns the ShadowGenerator.
  52151. */
  52152. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52153. if (darkness >= 1.0)
  52154. this._darkness = 1.0;
  52155. else if (darkness <= 0.0)
  52156. this._darkness = 0.0;
  52157. else
  52158. this._darkness = darkness;
  52159. return this;
  52160. };
  52161. /**
  52162. * Sets the ability to have transparent shadow (boolean).
  52163. * Returns the ShadowGenerator.
  52164. */
  52165. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52166. this._transparencyShadow = hasShadow;
  52167. return this;
  52168. };
  52169. /**
  52170. * Returns a RenderTargetTexture object : the shadow map texture.
  52171. */
  52172. ShadowGenerator.prototype.getShadowMap = function () {
  52173. return this._shadowMap;
  52174. };
  52175. /**
  52176. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52177. */
  52178. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52179. if (this._shadowMap2) {
  52180. return this._shadowMap2;
  52181. }
  52182. return this._shadowMap;
  52183. };
  52184. /**
  52185. * Helper function to add a mesh and its descendants to the list of shadow casters
  52186. * @param mesh Mesh to add
  52187. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52188. */
  52189. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52190. if (includeDescendants === void 0) { includeDescendants = true; }
  52191. if (!this._shadowMap) {
  52192. return this;
  52193. }
  52194. if (!this._shadowMap.renderList) {
  52195. this._shadowMap.renderList = [];
  52196. }
  52197. this._shadowMap.renderList.push(mesh);
  52198. if (includeDescendants) {
  52199. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52200. }
  52201. return this;
  52202. var _a;
  52203. };
  52204. /**
  52205. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52206. * @param mesh Mesh to remove
  52207. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52208. */
  52209. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52210. if (includeDescendants === void 0) { includeDescendants = true; }
  52211. if (!this._shadowMap || !this._shadowMap.renderList) {
  52212. return this;
  52213. }
  52214. var index = this._shadowMap.renderList.indexOf(mesh);
  52215. if (index !== -1) {
  52216. this._shadowMap.renderList.splice(index, 1);
  52217. }
  52218. if (includeDescendants) {
  52219. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52220. var child = _a[_i];
  52221. this.removeShadowCaster(child);
  52222. }
  52223. }
  52224. return this;
  52225. };
  52226. /**
  52227. * Returns the associated light object.
  52228. */
  52229. ShadowGenerator.prototype.getLight = function () {
  52230. return this._light;
  52231. };
  52232. ShadowGenerator.prototype._initializeGenerator = function () {
  52233. this._light._markMeshesAsLightDirty();
  52234. this._initializeShadowMap();
  52235. };
  52236. ShadowGenerator.prototype._initializeShadowMap = function () {
  52237. var _this = this;
  52238. // Render target
  52239. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52240. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52241. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52242. this._shadowMap.anisotropicFilteringLevel = 1;
  52243. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52244. this._shadowMap.renderParticles = false;
  52245. this._shadowMap.ignoreCameraViewport = true;
  52246. // Record Face Index before render.
  52247. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52248. _this._currentFaceIndex = faceIndex;
  52249. });
  52250. // Custom render function.
  52251. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52252. // Blur if required afer render.
  52253. this._shadowMap.onAfterUnbindObservable.add(function () {
  52254. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52255. return;
  52256. }
  52257. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52258. _this._initializeBlurRTTAndPostProcesses();
  52259. }
  52260. var shadowMap = _this.getShadowMapForRendering();
  52261. if (shadowMap) {
  52262. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52263. }
  52264. });
  52265. // Clear according to the chosen filter.
  52266. this._shadowMap.onClearObservable.add(function (engine) {
  52267. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52268. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52269. }
  52270. else {
  52271. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52272. }
  52273. });
  52274. };
  52275. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52276. var _this = this;
  52277. var engine = this._scene.getEngine();
  52278. var targetSize = this._mapSize / this.blurScale;
  52279. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52280. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52281. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52282. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52283. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52284. }
  52285. if (this.useKernelBlur) {
  52286. 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);
  52287. this._kernelBlurXPostprocess.width = targetSize;
  52288. this._kernelBlurXPostprocess.height = targetSize;
  52289. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52290. effect.setTexture("textureSampler", _this._shadowMap);
  52291. });
  52292. 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);
  52293. this._kernelBlurXPostprocess.autoClear = false;
  52294. this._kernelBlurYPostprocess.autoClear = false;
  52295. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52296. this._kernelBlurXPostprocess.packedFloat = true;
  52297. this._kernelBlurYPostprocess.packedFloat = true;
  52298. }
  52299. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52300. }
  52301. else {
  52302. 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);
  52303. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52304. effect.setFloat2("screenSize", targetSize, targetSize);
  52305. effect.setTexture("textureSampler", _this._shadowMap);
  52306. });
  52307. this._boxBlurPostprocess.autoClear = false;
  52308. this._blurPostProcesses = [this._boxBlurPostprocess];
  52309. }
  52310. };
  52311. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52312. var index;
  52313. var engine = this._scene.getEngine();
  52314. if (depthOnlySubMeshes.length) {
  52315. engine.setColorWrite(false);
  52316. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52317. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52318. }
  52319. engine.setColorWrite(true);
  52320. }
  52321. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52322. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52323. }
  52324. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52325. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52326. }
  52327. if (this._transparencyShadow) {
  52328. for (index = 0; index < transparentSubMeshes.length; index++) {
  52329. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52330. }
  52331. }
  52332. };
  52333. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52334. var _this = this;
  52335. var mesh = subMesh.getRenderingMesh();
  52336. var scene = this._scene;
  52337. var engine = scene.getEngine();
  52338. var material = subMesh.getMaterial();
  52339. if (!material) {
  52340. return;
  52341. }
  52342. // Culling
  52343. engine.setState(material.backFaceCulling);
  52344. // Managing instances
  52345. var batch = mesh._getInstancesRenderList(subMesh._id);
  52346. if (batch.mustReturn) {
  52347. return;
  52348. }
  52349. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52350. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52351. engine.enableEffect(this._effect);
  52352. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52353. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52354. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52355. this._effect.setVector3("lightPosition", this.getLight().position);
  52356. if (scene.activeCamera) {
  52357. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52358. }
  52359. // Alpha test
  52360. if (material && material.needAlphaTesting()) {
  52361. var alphaTexture = material.getAlphaTestTexture();
  52362. if (alphaTexture) {
  52363. this._effect.setTexture("diffuseSampler", alphaTexture);
  52364. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52365. }
  52366. }
  52367. // Bones
  52368. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52369. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52370. }
  52371. if (this.forceBackFacesOnly) {
  52372. engine.setState(true, 0, false, true);
  52373. }
  52374. // Draw
  52375. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52376. if (this.forceBackFacesOnly) {
  52377. engine.setState(true, 0, false, false);
  52378. }
  52379. }
  52380. else {
  52381. // Need to reset refresh rate of the shadowMap
  52382. if (this._shadowMap) {
  52383. this._shadowMap.resetRefreshCounter();
  52384. }
  52385. }
  52386. };
  52387. ShadowGenerator.prototype._applyFilterValues = function () {
  52388. if (!this._shadowMap) {
  52389. return;
  52390. }
  52391. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52392. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52393. }
  52394. else {
  52395. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52396. }
  52397. };
  52398. /**
  52399. * Force shader compilation including textures ready check
  52400. */
  52401. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52402. var _this = this;
  52403. var localOptions = __assign({ useInstances: false }, options);
  52404. var shadowMap = this.getShadowMap();
  52405. if (!shadowMap) {
  52406. if (onCompiled) {
  52407. onCompiled(this);
  52408. }
  52409. return;
  52410. }
  52411. var renderList = shadowMap.renderList;
  52412. if (!renderList) {
  52413. if (onCompiled) {
  52414. onCompiled(this);
  52415. }
  52416. return;
  52417. }
  52418. var subMeshes = new Array();
  52419. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52420. var mesh = renderList_1[_i];
  52421. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52422. }
  52423. if (subMeshes.length === 0) {
  52424. if (onCompiled) {
  52425. onCompiled(this);
  52426. }
  52427. return;
  52428. }
  52429. var currentIndex = 0;
  52430. var checkReady = function () {
  52431. if (!_this._scene || !_this._scene.getEngine()) {
  52432. return;
  52433. }
  52434. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52435. currentIndex++;
  52436. if (currentIndex >= subMeshes.length) {
  52437. if (onCompiled) {
  52438. onCompiled(_this);
  52439. }
  52440. return;
  52441. }
  52442. }
  52443. setTimeout(checkReady, 16);
  52444. };
  52445. checkReady();
  52446. };
  52447. /**
  52448. * Boolean : true when the ShadowGenerator is finally computed.
  52449. */
  52450. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52451. var defines = [];
  52452. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52453. defines.push("#define FLOAT");
  52454. }
  52455. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52456. defines.push("#define ESM");
  52457. }
  52458. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52459. var mesh = subMesh.getMesh();
  52460. var material = subMesh.getMaterial();
  52461. // Alpha test
  52462. if (material && material.needAlphaTesting()) {
  52463. var alphaTexture = material.getAlphaTestTexture();
  52464. if (alphaTexture) {
  52465. defines.push("#define ALPHATEST");
  52466. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52467. attribs.push(BABYLON.VertexBuffer.UVKind);
  52468. defines.push("#define UV1");
  52469. }
  52470. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52471. if (alphaTexture.coordinatesIndex === 1) {
  52472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52473. defines.push("#define UV2");
  52474. }
  52475. }
  52476. }
  52477. }
  52478. // Bones
  52479. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52480. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52481. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52482. if (mesh.numBoneInfluencers > 4) {
  52483. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52484. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52485. }
  52486. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52487. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52488. }
  52489. else {
  52490. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52491. }
  52492. // Instances
  52493. if (useInstances) {
  52494. defines.push("#define INSTANCES");
  52495. attribs.push("world0");
  52496. attribs.push("world1");
  52497. attribs.push("world2");
  52498. attribs.push("world3");
  52499. }
  52500. // Get correct effect
  52501. var join = defines.join("\n");
  52502. if (this._cachedDefines !== join) {
  52503. this._cachedDefines = join;
  52504. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52505. }
  52506. return this._effect.isReady();
  52507. };
  52508. /**
  52509. * This creates the defines related to the standard BJS materials.
  52510. */
  52511. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52512. var scene = this._scene;
  52513. var light = this._light;
  52514. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52515. return;
  52516. }
  52517. defines["SHADOW" + lightIndex] = true;
  52518. if (this.usePoissonSampling) {
  52519. defines["SHADOWPCF" + lightIndex] = true;
  52520. }
  52521. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52522. defines["SHADOWESM" + lightIndex] = true;
  52523. }
  52524. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52525. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52526. }
  52527. if (light.needCube()) {
  52528. defines["SHADOWCUBE" + lightIndex] = true;
  52529. }
  52530. };
  52531. /**
  52532. * This binds shadow lights related to the standard BJS materials.
  52533. * It implies the unifroms available on the materials are the standard BJS ones.
  52534. */
  52535. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52536. var light = this._light;
  52537. var scene = this._scene;
  52538. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52539. return;
  52540. }
  52541. var camera = scene.activeCamera;
  52542. if (!camera) {
  52543. return;
  52544. }
  52545. var shadowMap = this.getShadowMap();
  52546. if (!shadowMap) {
  52547. return;
  52548. }
  52549. if (!light.needCube()) {
  52550. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52551. }
  52552. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52553. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52554. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52555. };
  52556. // Methods
  52557. /**
  52558. * Returns a Matrix object : the updated transformation matrix.
  52559. */
  52560. ShadowGenerator.prototype.getTransformMatrix = function () {
  52561. var scene = this._scene;
  52562. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52563. return this._transformMatrix;
  52564. }
  52565. this._currentRenderID = scene.getRenderId();
  52566. this._currentFaceIndexCache = this._currentFaceIndex;
  52567. var lightPosition = this._light.position;
  52568. if (this._light.computeTransformedInformation()) {
  52569. lightPosition = this._light.transformedPosition;
  52570. }
  52571. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52572. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52573. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52574. }
  52575. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52576. this._cachedPosition = lightPosition.clone();
  52577. this._cachedDirection = this._lightDirection.clone();
  52578. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52579. var shadowMap = this.getShadowMap();
  52580. if (shadowMap) {
  52581. var renderList = shadowMap.renderList;
  52582. if (renderList) {
  52583. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52584. }
  52585. }
  52586. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52587. }
  52588. return this._transformMatrix;
  52589. };
  52590. ShadowGenerator.prototype.recreateShadowMap = function () {
  52591. var shadowMap = this._shadowMap;
  52592. if (!shadowMap) {
  52593. return;
  52594. }
  52595. // Track render list.
  52596. var renderList = shadowMap.renderList;
  52597. // Clean up existing data.
  52598. this._disposeRTTandPostProcesses();
  52599. // Reinitializes.
  52600. this._initializeGenerator();
  52601. // Reaffect the filter to ensure a correct fallback if necessary.
  52602. this.filter = this.filter;
  52603. // Reaffect the filter.
  52604. this._applyFilterValues();
  52605. // Reaffect Render List.
  52606. this._shadowMap.renderList = renderList;
  52607. };
  52608. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52609. if (this._shadowMap2) {
  52610. this._shadowMap2.dispose();
  52611. this._shadowMap2 = null;
  52612. }
  52613. if (this._downSamplePostprocess) {
  52614. this._downSamplePostprocess.dispose();
  52615. this._downSamplePostprocess = null;
  52616. }
  52617. if (this._boxBlurPostprocess) {
  52618. this._boxBlurPostprocess.dispose();
  52619. this._boxBlurPostprocess = null;
  52620. }
  52621. if (this._kernelBlurXPostprocess) {
  52622. this._kernelBlurXPostprocess.dispose();
  52623. this._kernelBlurXPostprocess = null;
  52624. }
  52625. if (this._kernelBlurYPostprocess) {
  52626. this._kernelBlurYPostprocess.dispose();
  52627. this._kernelBlurYPostprocess = null;
  52628. }
  52629. this._blurPostProcesses = [];
  52630. };
  52631. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52632. if (this._shadowMap) {
  52633. this._shadowMap.dispose();
  52634. this._shadowMap = null;
  52635. }
  52636. this._disposeBlurPostProcesses();
  52637. };
  52638. /**
  52639. * Disposes the ShadowGenerator.
  52640. * Returns nothing.
  52641. */
  52642. ShadowGenerator.prototype.dispose = function () {
  52643. this._disposeRTTandPostProcesses();
  52644. if (this._light) {
  52645. this._light._shadowGenerator = null;
  52646. this._light._markMeshesAsLightDirty();
  52647. }
  52648. };
  52649. /**
  52650. * Serializes the ShadowGenerator and returns a serializationObject.
  52651. */
  52652. ShadowGenerator.prototype.serialize = function () {
  52653. var serializationObject = {};
  52654. var shadowMap = this.getShadowMap();
  52655. if (!shadowMap) {
  52656. return serializationObject;
  52657. }
  52658. serializationObject.lightId = this._light.id;
  52659. serializationObject.mapSize = shadowMap.getRenderSize();
  52660. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52661. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52662. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52663. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52664. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52665. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52666. serializationObject.depthScale = this.depthScale;
  52667. serializationObject.darkness = this.getDarkness();
  52668. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52669. serializationObject.blurKernel = this.blurKernel;
  52670. serializationObject.blurScale = this.blurScale;
  52671. serializationObject.useKernelBlur = this.useKernelBlur;
  52672. serializationObject.transparencyShadow = this._transparencyShadow;
  52673. serializationObject.renderList = [];
  52674. if (shadowMap.renderList) {
  52675. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52676. var mesh = shadowMap.renderList[meshIndex];
  52677. serializationObject.renderList.push(mesh.id);
  52678. }
  52679. }
  52680. return serializationObject;
  52681. };
  52682. /**
  52683. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52684. */
  52685. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52686. //casting to point light, as light is missing the position attr and typescript complains.
  52687. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52688. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52689. var shadowMap = shadowGenerator.getShadowMap();
  52690. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52691. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52692. meshes.forEach(function (mesh) {
  52693. if (!shadowMap) {
  52694. return;
  52695. }
  52696. if (!shadowMap.renderList) {
  52697. shadowMap.renderList = [];
  52698. }
  52699. shadowMap.renderList.push(mesh);
  52700. });
  52701. }
  52702. if (parsedShadowGenerator.usePoissonSampling) {
  52703. shadowGenerator.usePoissonSampling = true;
  52704. }
  52705. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52706. shadowGenerator.useExponentialShadowMap = true;
  52707. }
  52708. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52709. shadowGenerator.useBlurExponentialShadowMap = true;
  52710. }
  52711. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52712. shadowGenerator.useCloseExponentialShadowMap = true;
  52713. }
  52714. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52715. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52716. }
  52717. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52718. shadowGenerator.useExponentialShadowMap = true;
  52719. }
  52720. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52721. shadowGenerator.useBlurExponentialShadowMap = true;
  52722. }
  52723. if (parsedShadowGenerator.depthScale) {
  52724. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52725. }
  52726. if (parsedShadowGenerator.blurScale) {
  52727. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52728. }
  52729. if (parsedShadowGenerator.blurBoxOffset) {
  52730. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52731. }
  52732. if (parsedShadowGenerator.useKernelBlur) {
  52733. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52734. }
  52735. if (parsedShadowGenerator.blurKernel) {
  52736. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52737. }
  52738. if (parsedShadowGenerator.bias !== undefined) {
  52739. shadowGenerator.bias = parsedShadowGenerator.bias;
  52740. }
  52741. if (parsedShadowGenerator.darkness) {
  52742. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52743. }
  52744. if (parsedShadowGenerator.transparencyShadow) {
  52745. shadowGenerator.setTransparencyShadow(true);
  52746. }
  52747. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52748. return shadowGenerator;
  52749. };
  52750. ShadowGenerator._FILTER_NONE = 0;
  52751. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52752. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52753. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52754. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52755. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52756. return ShadowGenerator;
  52757. }());
  52758. BABYLON.ShadowGenerator = ShadowGenerator;
  52759. })(BABYLON || (BABYLON = {}));
  52760. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52761. var BABYLON;
  52762. (function (BABYLON) {
  52763. var DefaultLoadingScreen = /** @class */ (function () {
  52764. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52765. if (_loadingText === void 0) { _loadingText = ""; }
  52766. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52767. var _this = this;
  52768. this._renderingCanvas = _renderingCanvas;
  52769. this._loadingText = _loadingText;
  52770. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52771. // Resize
  52772. this._resizeLoadingUI = function () {
  52773. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52774. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52775. if (!_this._loadingDiv) {
  52776. return;
  52777. }
  52778. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52779. _this._loadingDiv.style.left = canvasRect.left + "px";
  52780. _this._loadingDiv.style.top = canvasRect.top + "px";
  52781. _this._loadingDiv.style.width = canvasRect.width + "px";
  52782. _this._loadingDiv.style.height = canvasRect.height + "px";
  52783. };
  52784. }
  52785. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52786. if (this._loadingDiv) {
  52787. // Do not add a loading screen if there is already one
  52788. return;
  52789. }
  52790. this._loadingDiv = document.createElement("div");
  52791. this._loadingDiv.id = "babylonjsLoadingDiv";
  52792. this._loadingDiv.style.opacity = "0";
  52793. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52794. this._loadingDiv.style.pointerEvents = "none";
  52795. // Loading text
  52796. this._loadingTextDiv = document.createElement("div");
  52797. this._loadingTextDiv.style.position = "absolute";
  52798. this._loadingTextDiv.style.left = "0";
  52799. this._loadingTextDiv.style.top = "50%";
  52800. this._loadingTextDiv.style.marginTop = "80px";
  52801. this._loadingTextDiv.style.width = "100%";
  52802. this._loadingTextDiv.style.height = "20px";
  52803. this._loadingTextDiv.style.fontFamily = "Arial";
  52804. this._loadingTextDiv.style.fontSize = "14px";
  52805. this._loadingTextDiv.style.color = "white";
  52806. this._loadingTextDiv.style.textAlign = "center";
  52807. this._loadingTextDiv.innerHTML = "Loading";
  52808. this._loadingDiv.appendChild(this._loadingTextDiv);
  52809. //set the predefined text
  52810. this._loadingTextDiv.innerHTML = this._loadingText;
  52811. // Generating keyframes
  52812. var style = document.createElement('style');
  52813. style.type = 'text/css';
  52814. 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 }";
  52815. style.innerHTML = keyFrames;
  52816. document.getElementsByTagName('head')[0].appendChild(style);
  52817. // Loading img
  52818. var imgBack = new Image();
  52819. 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";
  52820. imgBack.style.position = "absolute";
  52821. imgBack.style.left = "50%";
  52822. imgBack.style.top = "50%";
  52823. imgBack.style.marginLeft = "-60px";
  52824. imgBack.style.marginTop = "-60px";
  52825. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52826. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52827. imgBack.style.transformOrigin = "50% 50%";
  52828. imgBack.style.webkitTransformOrigin = "50% 50%";
  52829. this._loadingDiv.appendChild(imgBack);
  52830. this._resizeLoadingUI();
  52831. window.addEventListener("resize", this._resizeLoadingUI);
  52832. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52833. document.body.appendChild(this._loadingDiv);
  52834. this._loadingDiv.style.opacity = "1";
  52835. };
  52836. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52837. var _this = this;
  52838. if (!this._loadingDiv) {
  52839. return;
  52840. }
  52841. var onTransitionEnd = function () {
  52842. if (!_this._loadingDiv) {
  52843. return;
  52844. }
  52845. document.body.removeChild(_this._loadingDiv);
  52846. window.removeEventListener("resize", _this._resizeLoadingUI);
  52847. _this._loadingDiv = null;
  52848. };
  52849. this._loadingDiv.style.opacity = "0";
  52850. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52851. };
  52852. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52853. set: function (text) {
  52854. this._loadingText = text;
  52855. if (this._loadingTextDiv) {
  52856. this._loadingTextDiv.innerHTML = this._loadingText;
  52857. }
  52858. },
  52859. enumerable: true,
  52860. configurable: true
  52861. });
  52862. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52863. get: function () {
  52864. return this._loadingDivBackgroundColor;
  52865. },
  52866. set: function (color) {
  52867. this._loadingDivBackgroundColor = color;
  52868. if (!this._loadingDiv) {
  52869. return;
  52870. }
  52871. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52872. },
  52873. enumerable: true,
  52874. configurable: true
  52875. });
  52876. return DefaultLoadingScreen;
  52877. }());
  52878. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52879. })(BABYLON || (BABYLON = {}));
  52880. //# sourceMappingURL=babylon.loadingScreen.js.map
  52881. var BABYLON;
  52882. (function (BABYLON) {
  52883. var SceneLoader = /** @class */ (function () {
  52884. function SceneLoader() {
  52885. }
  52886. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52887. get: function () {
  52888. return 0;
  52889. },
  52890. enumerable: true,
  52891. configurable: true
  52892. });
  52893. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52894. get: function () {
  52895. return 1;
  52896. },
  52897. enumerable: true,
  52898. configurable: true
  52899. });
  52900. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52901. get: function () {
  52902. return 2;
  52903. },
  52904. enumerable: true,
  52905. configurable: true
  52906. });
  52907. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52908. get: function () {
  52909. return 3;
  52910. },
  52911. enumerable: true,
  52912. configurable: true
  52913. });
  52914. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52915. get: function () {
  52916. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52917. },
  52918. set: function (value) {
  52919. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52920. },
  52921. enumerable: true,
  52922. configurable: true
  52923. });
  52924. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52925. get: function () {
  52926. return SceneLoader._ShowLoadingScreen;
  52927. },
  52928. set: function (value) {
  52929. SceneLoader._ShowLoadingScreen = value;
  52930. },
  52931. enumerable: true,
  52932. configurable: true
  52933. });
  52934. Object.defineProperty(SceneLoader, "loggingLevel", {
  52935. get: function () {
  52936. return SceneLoader._loggingLevel;
  52937. },
  52938. set: function (value) {
  52939. SceneLoader._loggingLevel = value;
  52940. },
  52941. enumerable: true,
  52942. configurable: true
  52943. });
  52944. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52945. get: function () {
  52946. return SceneLoader._CleanBoneMatrixWeights;
  52947. },
  52948. set: function (value) {
  52949. SceneLoader._CleanBoneMatrixWeights = value;
  52950. },
  52951. enumerable: true,
  52952. configurable: true
  52953. });
  52954. SceneLoader._getDefaultPlugin = function () {
  52955. return SceneLoader._registeredPlugins[".babylon"];
  52956. };
  52957. SceneLoader._getPluginForExtension = function (extension) {
  52958. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52959. if (registeredPlugin) {
  52960. return registeredPlugin;
  52961. }
  52962. return SceneLoader._getDefaultPlugin();
  52963. };
  52964. SceneLoader._getPluginForDirectLoad = function (data) {
  52965. for (var extension in SceneLoader._registeredPlugins) {
  52966. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52967. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52968. return SceneLoader._registeredPlugins[extension];
  52969. }
  52970. }
  52971. return SceneLoader._getDefaultPlugin();
  52972. };
  52973. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52974. if (sceneFilename.name) {
  52975. sceneFilename = sceneFilename.name;
  52976. }
  52977. var queryStringPosition = sceneFilename.indexOf("?");
  52978. if (queryStringPosition !== -1) {
  52979. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  52980. }
  52981. var dotPosition = sceneFilename.lastIndexOf(".");
  52982. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  52983. return SceneLoader._getPluginForExtension(extension);
  52984. };
  52985. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52986. SceneLoader._getDirectLoad = function (sceneFilename) {
  52987. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52988. return sceneFilename.substr(5);
  52989. }
  52990. return null;
  52991. };
  52992. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52993. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52994. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52995. var plugin;
  52996. if (registeredPlugin.plugin.createPlugin) {
  52997. plugin = registeredPlugin.plugin.createPlugin();
  52998. }
  52999. else {
  53000. plugin = registeredPlugin.plugin;
  53001. }
  53002. var useArrayBuffer = registeredPlugin.isBinary;
  53003. var database;
  53004. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  53005. var dataCallback = function (data, responseURL) {
  53006. if (scene.isDisposed) {
  53007. onError("Scene has been disposed");
  53008. return;
  53009. }
  53010. scene.database = database;
  53011. try {
  53012. onSuccess(plugin, data, responseURL);
  53013. }
  53014. catch (e) {
  53015. onError(null, e);
  53016. }
  53017. };
  53018. var manifestChecked = function (success) {
  53019. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  53020. if (request) {
  53021. onError(request.status + " " + request.statusText);
  53022. }
  53023. });
  53024. };
  53025. if (directLoad) {
  53026. dataCallback(directLoad);
  53027. return plugin;
  53028. }
  53029. if (rootUrl.indexOf("file:") === -1) {
  53030. if (scene.getEngine().enableOfflineSupport) {
  53031. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  53032. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  53033. }
  53034. else {
  53035. manifestChecked(true);
  53036. }
  53037. }
  53038. else {
  53039. var fileOrString = sceneFilename;
  53040. if (fileOrString.name) {
  53041. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  53042. }
  53043. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  53044. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  53045. }
  53046. else {
  53047. onError("Unable to find file named " + sceneFilename);
  53048. }
  53049. }
  53050. return plugin;
  53051. };
  53052. // Public functions
  53053. SceneLoader.GetPluginForExtension = function (extension) {
  53054. return SceneLoader._getPluginForExtension(extension).plugin;
  53055. };
  53056. SceneLoader.RegisterPlugin = function (plugin) {
  53057. if (typeof plugin.extensions === "string") {
  53058. var extension = plugin.extensions;
  53059. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53060. plugin: plugin,
  53061. isBinary: false
  53062. };
  53063. }
  53064. else {
  53065. var extensions = plugin.extensions;
  53066. Object.keys(extensions).forEach(function (extension) {
  53067. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53068. plugin: plugin,
  53069. isBinary: extensions[extension].isBinary
  53070. };
  53071. });
  53072. }
  53073. };
  53074. /**
  53075. * Import meshes into a scene
  53076. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  53077. * @param rootUrl a string that defines the root url for scene and resources
  53078. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53079. * @param scene the instance of BABYLON.Scene to append to
  53080. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  53081. * @param onProgress a callback with a progress event for each file being loaded
  53082. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53083. */
  53084. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53085. if (onSuccess === void 0) { onSuccess = null; }
  53086. if (onProgress === void 0) { onProgress = null; }
  53087. if (onError === void 0) { onError = null; }
  53088. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53089. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53090. return null;
  53091. }
  53092. var loadingToken = {};
  53093. scene._addPendingData(loadingToken);
  53094. var errorHandler = function (message, exception) {
  53095. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53096. if (onError) {
  53097. onError(scene, errorMessage, exception);
  53098. }
  53099. else {
  53100. BABYLON.Tools.Error(errorMessage);
  53101. // should the exception be thrown?
  53102. }
  53103. scene._removePendingData(loadingToken);
  53104. };
  53105. var progressHandler = function (event) {
  53106. if (onProgress) {
  53107. onProgress(event);
  53108. }
  53109. };
  53110. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53111. if (plugin.rewriteRootURL) {
  53112. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53113. }
  53114. if (plugin.importMesh) {
  53115. var syncedPlugin = plugin;
  53116. var meshes = new Array();
  53117. var particleSystems = new Array();
  53118. var skeletons = new Array();
  53119. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53120. return;
  53121. }
  53122. if (onSuccess) {
  53123. // wrap onSuccess with try-catch to know if something went wrong.
  53124. try {
  53125. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53126. onSuccess(meshes, particleSystems, skeletons);
  53127. scene._removePendingData(loadingToken);
  53128. }
  53129. catch (e) {
  53130. var message = 'Error in onSuccess callback.';
  53131. errorHandler(message, e);
  53132. }
  53133. }
  53134. }
  53135. else {
  53136. var asyncedPlugin = plugin;
  53137. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53138. if (onSuccess) {
  53139. try {
  53140. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53141. onSuccess(meshes, particleSystems, skeletons);
  53142. scene._removePendingData(loadingToken);
  53143. }
  53144. catch (e) {
  53145. var message = 'Error in onSuccess callback.';
  53146. errorHandler(message, e);
  53147. }
  53148. }
  53149. }, progressHandler, errorHandler);
  53150. }
  53151. }, progressHandler, errorHandler, pluginExtension);
  53152. };
  53153. /**
  53154. * Load a scene
  53155. * @param rootUrl a string that defines the root url for scene and resources
  53156. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53157. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53158. * @param onSuccess a callback with the scene when import succeeds
  53159. * @param onProgress a callback with a progress event for each file being loaded
  53160. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53161. */
  53162. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53163. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53164. };
  53165. /**
  53166. * Append a scene
  53167. * @param rootUrl a string that defines the root url for scene and resources
  53168. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53169. * @param scene is the instance of BABYLON.Scene to append to
  53170. * @param onSuccess a callback with the scene when import succeeds
  53171. * @param onProgress a callback with a progress event for each file being loaded
  53172. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53173. */
  53174. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53175. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53176. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53177. return null;
  53178. }
  53179. if (SceneLoader.ShowLoadingScreen) {
  53180. scene.getEngine().displayLoadingUI();
  53181. }
  53182. var loadingToken = {};
  53183. scene._addPendingData(loadingToken);
  53184. var errorHandler = function (message, exception) {
  53185. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53186. if (onError) {
  53187. onError(scene, errorMessage, exception);
  53188. }
  53189. else {
  53190. BABYLON.Tools.Error(errorMessage);
  53191. // should the exception be thrown?
  53192. }
  53193. scene._removePendingData(loadingToken);
  53194. scene.getEngine().hideLoadingUI();
  53195. };
  53196. var progressHandler = function (event) {
  53197. if (onProgress) {
  53198. onProgress(event);
  53199. }
  53200. };
  53201. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53202. if (plugin.load) {
  53203. var syncedPlugin = plugin;
  53204. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53205. return;
  53206. }
  53207. if (onSuccess) {
  53208. try {
  53209. onSuccess(scene);
  53210. }
  53211. catch (e) {
  53212. errorHandler("Error in onSuccess callback", e);
  53213. }
  53214. }
  53215. scene.loadingPluginName = plugin.name;
  53216. scene._removePendingData(loadingToken);
  53217. }
  53218. else {
  53219. var asyncedPlugin = plugin;
  53220. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53221. if (onSuccess) {
  53222. onSuccess(scene);
  53223. }
  53224. scene.loadingPluginName = plugin.name;
  53225. scene._removePendingData(loadingToken);
  53226. }, progressHandler, errorHandler);
  53227. }
  53228. if (SceneLoader.ShowLoadingScreen) {
  53229. scene.executeWhenReady(function () {
  53230. scene.getEngine().hideLoadingUI();
  53231. });
  53232. }
  53233. }, progressHandler, errorHandler, pluginExtension);
  53234. };
  53235. // Flags
  53236. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53237. SceneLoader._ShowLoadingScreen = true;
  53238. SceneLoader._CleanBoneMatrixWeights = false;
  53239. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53240. // Members
  53241. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53242. SceneLoader._registeredPlugins = {};
  53243. return SceneLoader;
  53244. }());
  53245. BABYLON.SceneLoader = SceneLoader;
  53246. ;
  53247. })(BABYLON || (BABYLON = {}));
  53248. //# sourceMappingURL=babylon.sceneLoader.js.map
  53249. var BABYLON;
  53250. (function (BABYLON) {
  53251. var Internals;
  53252. (function (Internals) {
  53253. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53254. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53255. var parsedMaterial = parsedData.materials[index];
  53256. if (parsedMaterial.id === id) {
  53257. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53258. }
  53259. }
  53260. return null;
  53261. };
  53262. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53263. for (var i in names) {
  53264. if (mesh.name === names[i]) {
  53265. hierarchyIds.push(mesh.id);
  53266. return true;
  53267. }
  53268. }
  53269. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53270. hierarchyIds.push(mesh.id);
  53271. return true;
  53272. }
  53273. return false;
  53274. };
  53275. var logOperation = function (operation, producer) {
  53276. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53277. };
  53278. BABYLON.SceneLoader.RegisterPlugin({
  53279. name: "babylon.js",
  53280. extensions: ".babylon",
  53281. canDirectLoad: function (data) {
  53282. if (data.indexOf("babylon") !== -1) {
  53283. return true;
  53284. }
  53285. return false;
  53286. },
  53287. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53288. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53289. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53290. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53291. // and avoid problems with multiple concurrent .babylon loads.
  53292. var log = "importMesh has failed JSON parse";
  53293. try {
  53294. var parsedData = JSON.parse(data);
  53295. log = "";
  53296. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53297. if (!meshesNames) {
  53298. meshesNames = null;
  53299. }
  53300. else if (!Array.isArray(meshesNames)) {
  53301. meshesNames = [meshesNames];
  53302. }
  53303. var hierarchyIds = new Array();
  53304. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53305. var loadedSkeletonsIds = [];
  53306. var loadedMaterialsIds = [];
  53307. var index;
  53308. var cache;
  53309. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53310. var parsedMesh = parsedData.meshes[index];
  53311. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53312. if (meshesNames !== null) {
  53313. // Remove found mesh name from list.
  53314. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53315. }
  53316. //Geometry?
  53317. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53318. //does the file contain geometries?
  53319. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53320. //find the correct geometry and add it to the scene
  53321. var found = false;
  53322. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53323. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53324. return;
  53325. }
  53326. else {
  53327. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53328. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53329. switch (geometryType) {
  53330. case "boxes":
  53331. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53332. break;
  53333. case "spheres":
  53334. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53335. break;
  53336. case "cylinders":
  53337. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53338. break;
  53339. case "toruses":
  53340. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53341. break;
  53342. case "grounds":
  53343. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53344. break;
  53345. case "planes":
  53346. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53347. break;
  53348. case "torusKnots":
  53349. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53350. break;
  53351. case "vertexData":
  53352. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53353. break;
  53354. }
  53355. found = true;
  53356. }
  53357. });
  53358. }
  53359. });
  53360. if (found === false) {
  53361. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53362. }
  53363. }
  53364. }
  53365. // Material ?
  53366. if (parsedMesh.materialId) {
  53367. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53368. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53369. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53370. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53371. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53372. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53373. var subMatId = parsedMultiMaterial.materials[matIndex];
  53374. loadedMaterialsIds.push(subMatId);
  53375. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53376. log += "\n\tMaterial " + mat.toString(fullDetails);
  53377. }
  53378. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53379. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53380. materialFound = true;
  53381. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53382. break;
  53383. }
  53384. }
  53385. }
  53386. if (materialFound === false) {
  53387. loadedMaterialsIds.push(parsedMesh.materialId);
  53388. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53389. if (!mat) {
  53390. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53391. }
  53392. else {
  53393. log += "\n\tMaterial " + mat.toString(fullDetails);
  53394. }
  53395. }
  53396. }
  53397. // Skeleton ?
  53398. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53399. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53400. if (skeletonAlreadyLoaded === false) {
  53401. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53402. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53403. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53404. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53405. skeletons.push(skeleton);
  53406. loadedSkeletonsIds.push(parsedSkeleton.id);
  53407. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53408. }
  53409. }
  53410. }
  53411. }
  53412. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53413. meshes.push(mesh);
  53414. log += "\n\tMesh " + mesh.toString(fullDetails);
  53415. }
  53416. }
  53417. // Connecting parents
  53418. var currentMesh;
  53419. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53420. currentMesh = scene.meshes[index];
  53421. if (currentMesh._waitingParentId) {
  53422. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53423. currentMesh._waitingParentId = null;
  53424. }
  53425. }
  53426. // freeze and compute world matrix application
  53427. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53428. currentMesh = scene.meshes[index];
  53429. if (currentMesh._waitingFreezeWorldMatrix) {
  53430. currentMesh.freezeWorldMatrix();
  53431. currentMesh._waitingFreezeWorldMatrix = null;
  53432. }
  53433. else {
  53434. currentMesh.computeWorldMatrix(true);
  53435. }
  53436. }
  53437. }
  53438. // Particles
  53439. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53440. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53441. var parsedParticleSystem = parsedData.particleSystems[index];
  53442. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53443. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53444. }
  53445. }
  53446. }
  53447. return true;
  53448. }
  53449. catch (err) {
  53450. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53451. if (onError) {
  53452. onError(msg, err);
  53453. }
  53454. else {
  53455. BABYLON.Tools.Log(msg);
  53456. throw err;
  53457. }
  53458. }
  53459. finally {
  53460. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53461. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53462. }
  53463. }
  53464. return false;
  53465. },
  53466. load: function (scene, data, rootUrl, onError) {
  53467. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53468. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53469. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53470. // and avoid problems with multiple concurrent .babylon loads.
  53471. var log = "importScene has failed JSON parse";
  53472. try {
  53473. var parsedData = JSON.parse(data);
  53474. log = "";
  53475. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53476. // Scene
  53477. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53478. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53479. }
  53480. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53481. scene.autoClear = parsedData.autoClear;
  53482. }
  53483. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53484. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53485. }
  53486. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53487. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53488. }
  53489. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53490. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53491. }
  53492. // Fog
  53493. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53494. scene.fogMode = parsedData.fogMode;
  53495. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53496. scene.fogStart = parsedData.fogStart;
  53497. scene.fogEnd = parsedData.fogEnd;
  53498. scene.fogDensity = parsedData.fogDensity;
  53499. log += "\tFog mode for scene: ";
  53500. switch (scene.fogMode) {
  53501. // getters not compiling, so using hardcoded
  53502. case 1:
  53503. log += "exp\n";
  53504. break;
  53505. case 2:
  53506. log += "exp2\n";
  53507. break;
  53508. case 3:
  53509. log += "linear\n";
  53510. break;
  53511. }
  53512. }
  53513. //Physics
  53514. if (parsedData.physicsEnabled) {
  53515. var physicsPlugin;
  53516. if (parsedData.physicsEngine === "cannon") {
  53517. physicsPlugin = new BABYLON.CannonJSPlugin();
  53518. }
  53519. else if (parsedData.physicsEngine === "oimo") {
  53520. physicsPlugin = new BABYLON.OimoJSPlugin();
  53521. }
  53522. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53523. //else - default engine, which is currently oimo
  53524. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53525. scene.enablePhysics(physicsGravity, physicsPlugin);
  53526. }
  53527. // Metadata
  53528. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53529. scene.metadata = parsedData.metadata;
  53530. }
  53531. //collisions, if defined. otherwise, default is true
  53532. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53533. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53534. }
  53535. scene.workerCollisions = !!parsedData.workerCollisions;
  53536. var index;
  53537. var cache;
  53538. // Lights
  53539. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53540. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53541. var parsedLight = parsedData.lights[index];
  53542. var light = BABYLON.Light.Parse(parsedLight, scene);
  53543. if (light) {
  53544. log += (index === 0 ? "\n\tLights:" : "");
  53545. log += "\n\t\t" + light.toString(fullDetails);
  53546. }
  53547. }
  53548. }
  53549. // Animations
  53550. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53551. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53552. var parsedAnimation = parsedData.animations[index];
  53553. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53554. scene.animations.push(animation);
  53555. log += (index === 0 ? "\n\tAnimations:" : "");
  53556. log += "\n\t\t" + animation.toString(fullDetails);
  53557. }
  53558. }
  53559. if (parsedData.autoAnimate) {
  53560. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53561. }
  53562. // Materials
  53563. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53564. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53565. var parsedMaterial = parsedData.materials[index];
  53566. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53567. log += (index === 0 ? "\n\tMaterials:" : "");
  53568. log += "\n\t\t" + mat.toString(fullDetails);
  53569. }
  53570. }
  53571. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53572. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53573. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53574. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53575. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53576. log += "\n\t\t" + mmat.toString(fullDetails);
  53577. }
  53578. }
  53579. // Morph targets
  53580. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53581. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53582. var managerData = _a[_i];
  53583. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53584. }
  53585. }
  53586. // Skeletons
  53587. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53588. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53589. var parsedSkeleton = parsedData.skeletons[index];
  53590. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53591. log += (index === 0 ? "\n\tSkeletons:" : "");
  53592. log += "\n\t\t" + skeleton.toString(fullDetails);
  53593. }
  53594. }
  53595. // Geometries
  53596. var geometries = parsedData.geometries;
  53597. if (geometries !== undefined && geometries !== null) {
  53598. // Boxes
  53599. var boxes = geometries.boxes;
  53600. if (boxes !== undefined && boxes !== null) {
  53601. for (index = 0, cache = boxes.length; index < cache; index++) {
  53602. var parsedBox = boxes[index];
  53603. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53604. }
  53605. }
  53606. // Spheres
  53607. var spheres = geometries.spheres;
  53608. if (spheres !== undefined && spheres !== null) {
  53609. for (index = 0, cache = spheres.length; index < cache; index++) {
  53610. var parsedSphere = spheres[index];
  53611. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53612. }
  53613. }
  53614. // Cylinders
  53615. var cylinders = geometries.cylinders;
  53616. if (cylinders !== undefined && cylinders !== null) {
  53617. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53618. var parsedCylinder = cylinders[index];
  53619. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53620. }
  53621. }
  53622. // Toruses
  53623. var toruses = geometries.toruses;
  53624. if (toruses !== undefined && toruses !== null) {
  53625. for (index = 0, cache = toruses.length; index < cache; index++) {
  53626. var parsedTorus = toruses[index];
  53627. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53628. }
  53629. }
  53630. // Grounds
  53631. var grounds = geometries.grounds;
  53632. if (grounds !== undefined && grounds !== null) {
  53633. for (index = 0, cache = grounds.length; index < cache; index++) {
  53634. var parsedGround = grounds[index];
  53635. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53636. }
  53637. }
  53638. // Planes
  53639. var planes = geometries.planes;
  53640. if (planes !== undefined && planes !== null) {
  53641. for (index = 0, cache = planes.length; index < cache; index++) {
  53642. var parsedPlane = planes[index];
  53643. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53644. }
  53645. }
  53646. // TorusKnots
  53647. var torusKnots = geometries.torusKnots;
  53648. if (torusKnots !== undefined && torusKnots !== null) {
  53649. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53650. var parsedTorusKnot = torusKnots[index];
  53651. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53652. }
  53653. }
  53654. // VertexData
  53655. var vertexData = geometries.vertexData;
  53656. if (vertexData !== undefined && vertexData !== null) {
  53657. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53658. var parsedVertexData = vertexData[index];
  53659. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53660. }
  53661. }
  53662. }
  53663. // Transform nodes
  53664. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53665. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53666. var parsedTransformNode = parsedData.transformNodes[index];
  53667. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53668. }
  53669. }
  53670. // Meshes
  53671. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53672. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53673. var parsedMesh = parsedData.meshes[index];
  53674. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53675. log += (index === 0 ? "\n\tMeshes:" : "");
  53676. log += "\n\t\t" + mesh.toString(fullDetails);
  53677. }
  53678. }
  53679. // Cameras
  53680. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53681. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53682. var parsedCamera = parsedData.cameras[index];
  53683. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53684. log += (index === 0 ? "\n\tCameras:" : "");
  53685. log += "\n\t\t" + camera.toString(fullDetails);
  53686. }
  53687. }
  53688. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53689. scene.setActiveCameraByID(parsedData.activeCameraID);
  53690. }
  53691. // Browsing all the graph to connect the dots
  53692. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53693. var camera = scene.cameras[index];
  53694. if (camera._waitingParentId) {
  53695. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53696. camera._waitingParentId = null;
  53697. }
  53698. }
  53699. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53700. var light_1 = scene.lights[index];
  53701. if (light_1 && light_1._waitingParentId) {
  53702. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53703. light_1._waitingParentId = null;
  53704. }
  53705. }
  53706. // Sounds
  53707. var loadedSounds = [];
  53708. var loadedSound;
  53709. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53710. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53711. var parsedSound = parsedData.sounds[index];
  53712. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53713. if (!parsedSound.url)
  53714. parsedSound.url = parsedSound.name;
  53715. if (!loadedSounds[parsedSound.url]) {
  53716. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53717. loadedSounds[parsedSound.url] = loadedSound;
  53718. }
  53719. else {
  53720. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53721. }
  53722. }
  53723. else {
  53724. new BABYLON.Sound(parsedSound.name, null, scene);
  53725. }
  53726. }
  53727. }
  53728. loadedSounds = [];
  53729. // Connect parents & children and parse actions
  53730. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53731. var transformNode = scene.transformNodes[index];
  53732. if (transformNode._waitingParentId) {
  53733. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53734. transformNode._waitingParentId = null;
  53735. }
  53736. }
  53737. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53738. var mesh = scene.meshes[index];
  53739. if (mesh._waitingParentId) {
  53740. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53741. mesh._waitingParentId = null;
  53742. }
  53743. if (mesh._waitingActions) {
  53744. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53745. mesh._waitingActions = null;
  53746. }
  53747. }
  53748. // freeze world matrix application
  53749. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53750. var currentMesh = scene.meshes[index];
  53751. if (currentMesh._waitingFreezeWorldMatrix) {
  53752. currentMesh.freezeWorldMatrix();
  53753. currentMesh._waitingFreezeWorldMatrix = null;
  53754. }
  53755. else {
  53756. currentMesh.computeWorldMatrix(true);
  53757. }
  53758. }
  53759. // Particles Systems
  53760. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53761. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53762. var parsedParticleSystem = parsedData.particleSystems[index];
  53763. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53764. }
  53765. }
  53766. // Environment texture
  53767. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53768. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53769. if (parsedData.createDefaultSkybox === true) {
  53770. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53771. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53772. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53773. }
  53774. }
  53775. // Lens flares
  53776. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53777. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53778. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53779. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53780. }
  53781. }
  53782. // Shadows
  53783. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53784. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53785. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53786. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53787. }
  53788. }
  53789. // Lights exclusions / inclusions
  53790. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53791. var light_2 = scene.lights[index];
  53792. // Excluded check
  53793. if (light_2._excludedMeshesIds.length > 0) {
  53794. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53795. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53796. if (excludedMesh) {
  53797. light_2.excludedMeshes.push(excludedMesh);
  53798. }
  53799. }
  53800. light_2._excludedMeshesIds = [];
  53801. }
  53802. // Included check
  53803. if (light_2._includedOnlyMeshesIds.length > 0) {
  53804. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53805. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53806. if (includedOnlyMesh) {
  53807. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53808. }
  53809. }
  53810. light_2._includedOnlyMeshesIds = [];
  53811. }
  53812. }
  53813. // Actions (scene)
  53814. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53815. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53816. }
  53817. // Finish
  53818. return true;
  53819. }
  53820. catch (err) {
  53821. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53822. if (onError) {
  53823. onError(msg, err);
  53824. }
  53825. else {
  53826. BABYLON.Tools.Log(msg);
  53827. throw err;
  53828. }
  53829. }
  53830. finally {
  53831. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53832. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53833. }
  53834. }
  53835. return false;
  53836. }
  53837. });
  53838. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53839. })(BABYLON || (BABYLON = {}));
  53840. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53841. var BABYLON;
  53842. (function (BABYLON) {
  53843. var FilesInput = /** @class */ (function () {
  53844. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53845. this.onProcessFileCallback = function () { return true; };
  53846. this._engine = engine;
  53847. this._currentScene = scene;
  53848. this._sceneLoadedCallback = sceneLoadedCallback;
  53849. this._progressCallback = progressCallback;
  53850. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53851. this._textureLoadingCallback = textureLoadingCallback;
  53852. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53853. this._onReloadCallback = onReloadCallback;
  53854. this._errorCallback = errorCallback;
  53855. }
  53856. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53857. var _this = this;
  53858. if (elementToMonitor) {
  53859. this._elementToMonitor = elementToMonitor;
  53860. this._dragEnterHandler = function (e) { _this.drag(e); };
  53861. this._dragOverHandler = function (e) { _this.drag(e); };
  53862. this._dropHandler = function (e) { _this.drop(e); };
  53863. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53864. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53865. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53866. }
  53867. };
  53868. FilesInput.prototype.dispose = function () {
  53869. if (!this._elementToMonitor) {
  53870. return;
  53871. }
  53872. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53873. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53874. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53875. };
  53876. FilesInput.prototype.renderFunction = function () {
  53877. if (this._additionalRenderLoopLogicCallback) {
  53878. this._additionalRenderLoopLogicCallback();
  53879. }
  53880. if (this._currentScene) {
  53881. if (this._textureLoadingCallback) {
  53882. var remaining = this._currentScene.getWaitingItemsCount();
  53883. if (remaining > 0) {
  53884. this._textureLoadingCallback(remaining);
  53885. }
  53886. }
  53887. this._currentScene.render();
  53888. }
  53889. };
  53890. FilesInput.prototype.drag = function (e) {
  53891. e.stopPropagation();
  53892. e.preventDefault();
  53893. };
  53894. FilesInput.prototype.drop = function (eventDrop) {
  53895. eventDrop.stopPropagation();
  53896. eventDrop.preventDefault();
  53897. this.loadFiles(eventDrop);
  53898. };
  53899. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53900. var _this = this;
  53901. var reader = folder.createReader();
  53902. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53903. reader.readEntries(function (entries) {
  53904. remaining.count += entries.length;
  53905. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53906. var entry = entries_1[_i];
  53907. if (entry.isFile) {
  53908. entry.file(function (file) {
  53909. file.correctName = relativePath + file.name;
  53910. files.push(file);
  53911. if (--remaining.count === 0) {
  53912. callback();
  53913. }
  53914. });
  53915. }
  53916. else if (entry.isDirectory) {
  53917. _this._traverseFolder(entry, files, remaining, callback);
  53918. }
  53919. }
  53920. if (--remaining.count) {
  53921. callback();
  53922. }
  53923. });
  53924. };
  53925. FilesInput.prototype._processFiles = function (files) {
  53926. var skippedFiles = 0;
  53927. for (var i = 0; i < files.length; i++) {
  53928. var name = files[i].correctName.toLowerCase();
  53929. var extension = name.split('.').pop();
  53930. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53931. skippedFiles++;
  53932. continue;
  53933. }
  53934. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53935. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53936. this._sceneFileToLoad = files[i];
  53937. }
  53938. else {
  53939. FilesInput.FilesToLoad[name] = files[i];
  53940. }
  53941. }
  53942. if (this._onReloadCallback) {
  53943. this._onReloadCallback(this._sceneFileToLoad);
  53944. }
  53945. else if (skippedFiles < files.length) {
  53946. this.reload();
  53947. }
  53948. };
  53949. FilesInput.prototype.loadFiles = function (event) {
  53950. var _this = this;
  53951. if (this._startingProcessingFilesCallback)
  53952. this._startingProcessingFilesCallback();
  53953. // Handling data transfer via drag'n'drop
  53954. if (event && event.dataTransfer && event.dataTransfer.files) {
  53955. this._filesToLoad = event.dataTransfer.files;
  53956. }
  53957. // Handling files from input files
  53958. if (event && event.target && event.target.files) {
  53959. this._filesToLoad = event.target.files;
  53960. }
  53961. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53962. var files_1 = new Array();
  53963. var folders = [];
  53964. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53965. for (var i = 0; i < this._filesToLoad.length; i++) {
  53966. var fileToLoad = this._filesToLoad[i];
  53967. var name_1 = fileToLoad.name.toLowerCase();
  53968. var entry = void 0;
  53969. fileToLoad.correctName = name_1;
  53970. if (items) {
  53971. var item = items[i];
  53972. if (item.getAsEntry) {
  53973. entry = item.getAsEntry();
  53974. }
  53975. else if (item.webkitGetAsEntry) {
  53976. entry = item.webkitGetAsEntry();
  53977. }
  53978. }
  53979. if (!entry) {
  53980. files_1.push(fileToLoad);
  53981. }
  53982. else {
  53983. if (entry.isDirectory) {
  53984. folders.push(entry);
  53985. }
  53986. else {
  53987. files_1.push(fileToLoad);
  53988. }
  53989. }
  53990. }
  53991. if (folders.length === 0) {
  53992. this._processFiles(files_1);
  53993. }
  53994. else {
  53995. var remaining = { count: folders.length };
  53996. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53997. var folder = folders_1[_i];
  53998. this._traverseFolder(folder, files_1, remaining, function () {
  53999. _this._processFiles(files_1);
  54000. });
  54001. }
  54002. }
  54003. }
  54004. };
  54005. FilesInput.prototype.reload = function () {
  54006. var _this = this;
  54007. // If a ".babylon" file has been provided
  54008. if (this._sceneFileToLoad) {
  54009. if (this._currentScene) {
  54010. if (BABYLON.Tools.errorsCount > 0) {
  54011. BABYLON.Tools.ClearLogCache();
  54012. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  54013. }
  54014. this._engine.stopRenderLoop();
  54015. this._currentScene.dispose();
  54016. }
  54017. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  54018. _this._currentScene = newScene;
  54019. if (_this._sceneLoadedCallback) {
  54020. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  54021. }
  54022. // Wait for textures and shaders to be ready
  54023. _this._currentScene.executeWhenReady(function () {
  54024. _this._engine.runRenderLoop(function () {
  54025. _this.renderFunction();
  54026. });
  54027. });
  54028. }, function (progress) {
  54029. if (_this._progressCallback) {
  54030. _this._progressCallback(progress);
  54031. }
  54032. }, function (scene, message) {
  54033. _this._currentScene = scene;
  54034. if (_this._errorCallback) {
  54035. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  54036. }
  54037. });
  54038. }
  54039. else {
  54040. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  54041. }
  54042. };
  54043. FilesInput.FilesToLoad = {};
  54044. return FilesInput;
  54045. }());
  54046. BABYLON.FilesInput = FilesInput;
  54047. })(BABYLON || (BABYLON = {}));
  54048. //# sourceMappingURL=babylon.filesInput.js.map
  54049. var BABYLON;
  54050. (function (BABYLON) {
  54051. /**
  54052. * This class implement a typical dictionary using a string as key and the generic type T as value.
  54053. * The underlying implementation relies on an associative array to ensure the best performances.
  54054. * The value can be anything including 'null' but except 'undefined'
  54055. */
  54056. var StringDictionary = /** @class */ (function () {
  54057. function StringDictionary() {
  54058. this._count = 0;
  54059. this._data = {};
  54060. }
  54061. /**
  54062. * This will clear this dictionary and copy the content from the 'source' one.
  54063. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  54064. * @param source the dictionary to take the content from and copy to this dictionary
  54065. */
  54066. StringDictionary.prototype.copyFrom = function (source) {
  54067. var _this = this;
  54068. this.clear();
  54069. source.forEach(function (t, v) { return _this.add(t, v); });
  54070. };
  54071. /**
  54072. * Get a value based from its key
  54073. * @param key the given key to get the matching value from
  54074. * @return the value if found, otherwise undefined is returned
  54075. */
  54076. StringDictionary.prototype.get = function (key) {
  54077. var val = this._data[key];
  54078. if (val !== undefined) {
  54079. return val;
  54080. }
  54081. return undefined;
  54082. };
  54083. /**
  54084. * Get a value from its key or add it if it doesn't exist.
  54085. * This method will ensure you that a given key/data will be present in the dictionary.
  54086. * @param key the given key to get the matching value from
  54087. * @param factory the factory that will create the value if the key is not present in the dictionary.
  54088. * The factory will only be invoked if there's no data for the given key.
  54089. * @return the value corresponding to the key.
  54090. */
  54091. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  54092. var val = this.get(key);
  54093. if (val !== undefined) {
  54094. return val;
  54095. }
  54096. val = factory(key);
  54097. if (val) {
  54098. this.add(key, val);
  54099. }
  54100. return val;
  54101. };
  54102. /**
  54103. * Get a value from its key if present in the dictionary otherwise add it
  54104. * @param key the key to get the value from
  54105. * @param val if there's no such key/value pair in the dictionary add it with this value
  54106. * @return the value corresponding to the key
  54107. */
  54108. StringDictionary.prototype.getOrAdd = function (key, val) {
  54109. var curVal = this.get(key);
  54110. if (curVal !== undefined) {
  54111. return curVal;
  54112. }
  54113. this.add(key, val);
  54114. return val;
  54115. };
  54116. /**
  54117. * Check if there's a given key in the dictionary
  54118. * @param key the key to check for
  54119. * @return true if the key is present, false otherwise
  54120. */
  54121. StringDictionary.prototype.contains = function (key) {
  54122. return this._data[key] !== undefined;
  54123. };
  54124. /**
  54125. * Add a new key and its corresponding value
  54126. * @param key the key to add
  54127. * @param value the value corresponding to the key
  54128. * @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
  54129. */
  54130. StringDictionary.prototype.add = function (key, value) {
  54131. if (this._data[key] !== undefined) {
  54132. return false;
  54133. }
  54134. this._data[key] = value;
  54135. ++this._count;
  54136. return true;
  54137. };
  54138. StringDictionary.prototype.set = function (key, value) {
  54139. if (this._data[key] === undefined) {
  54140. return false;
  54141. }
  54142. this._data[key] = value;
  54143. return true;
  54144. };
  54145. /**
  54146. * Get the element of the given key and remove it from the dictionary
  54147. * @param key
  54148. */
  54149. StringDictionary.prototype.getAndRemove = function (key) {
  54150. var val = this.get(key);
  54151. if (val !== undefined) {
  54152. delete this._data[key];
  54153. --this._count;
  54154. return val;
  54155. }
  54156. return null;
  54157. };
  54158. /**
  54159. * Remove a key/value from the dictionary.
  54160. * @param key the key to remove
  54161. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54162. */
  54163. StringDictionary.prototype.remove = function (key) {
  54164. if (this.contains(key)) {
  54165. delete this._data[key];
  54166. --this._count;
  54167. return true;
  54168. }
  54169. return false;
  54170. };
  54171. /**
  54172. * Clear the whole content of the dictionary
  54173. */
  54174. StringDictionary.prototype.clear = function () {
  54175. this._data = {};
  54176. this._count = 0;
  54177. };
  54178. Object.defineProperty(StringDictionary.prototype, "count", {
  54179. get: function () {
  54180. return this._count;
  54181. },
  54182. enumerable: true,
  54183. configurable: true
  54184. });
  54185. /**
  54186. * Execute a callback on each key/val of the dictionary.
  54187. * Note that you can remove any element in this dictionary in the callback implementation
  54188. * @param callback the callback to execute on a given key/value pair
  54189. */
  54190. StringDictionary.prototype.forEach = function (callback) {
  54191. for (var cur in this._data) {
  54192. var val = this._data[cur];
  54193. callback(cur, val);
  54194. }
  54195. };
  54196. /**
  54197. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54198. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54199. * Note that you can remove any element in this dictionary in the callback implementation
  54200. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54201. */
  54202. StringDictionary.prototype.first = function (callback) {
  54203. for (var cur in this._data) {
  54204. var val = this._data[cur];
  54205. var res = callback(cur, val);
  54206. if (res) {
  54207. return res;
  54208. }
  54209. }
  54210. return null;
  54211. };
  54212. return StringDictionary;
  54213. }());
  54214. BABYLON.StringDictionary = StringDictionary;
  54215. })(BABYLON || (BABYLON = {}));
  54216. //# sourceMappingURL=babylon.stringDictionary.js.map
  54217. var BABYLON;
  54218. (function (BABYLON) {
  54219. var Tags = /** @class */ (function () {
  54220. function Tags() {
  54221. }
  54222. Tags.EnableFor = function (obj) {
  54223. obj._tags = obj._tags || {};
  54224. obj.hasTags = function () {
  54225. return Tags.HasTags(obj);
  54226. };
  54227. obj.addTags = function (tagsString) {
  54228. return Tags.AddTagsTo(obj, tagsString);
  54229. };
  54230. obj.removeTags = function (tagsString) {
  54231. return Tags.RemoveTagsFrom(obj, tagsString);
  54232. };
  54233. obj.matchesTagsQuery = function (tagsQuery) {
  54234. return Tags.MatchesQuery(obj, tagsQuery);
  54235. };
  54236. };
  54237. Tags.DisableFor = function (obj) {
  54238. delete obj._tags;
  54239. delete obj.hasTags;
  54240. delete obj.addTags;
  54241. delete obj.removeTags;
  54242. delete obj.matchesTagsQuery;
  54243. };
  54244. Tags.HasTags = function (obj) {
  54245. if (!obj._tags) {
  54246. return false;
  54247. }
  54248. return !BABYLON.Tools.IsEmpty(obj._tags);
  54249. };
  54250. Tags.GetTags = function (obj, asString) {
  54251. if (asString === void 0) { asString = true; }
  54252. if (!obj._tags) {
  54253. return null;
  54254. }
  54255. if (asString) {
  54256. var tagsArray = [];
  54257. for (var tag in obj._tags) {
  54258. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54259. tagsArray.push(tag);
  54260. }
  54261. }
  54262. return tagsArray.join(" ");
  54263. }
  54264. else {
  54265. return obj._tags;
  54266. }
  54267. };
  54268. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54269. // a tag cannot start with '||', '&&', and '!'
  54270. // it cannot contain whitespaces
  54271. Tags.AddTagsTo = function (obj, tagsString) {
  54272. if (!tagsString) {
  54273. return;
  54274. }
  54275. if (typeof tagsString !== "string") {
  54276. return;
  54277. }
  54278. var tags = tagsString.split(" ");
  54279. tags.forEach(function (tag, index, array) {
  54280. Tags._AddTagTo(obj, tag);
  54281. });
  54282. };
  54283. Tags._AddTagTo = function (obj, tag) {
  54284. tag = tag.trim();
  54285. if (tag === "" || tag === "true" || tag === "false") {
  54286. return;
  54287. }
  54288. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54289. return;
  54290. }
  54291. Tags.EnableFor(obj);
  54292. obj._tags[tag] = true;
  54293. };
  54294. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54295. if (!Tags.HasTags(obj)) {
  54296. return;
  54297. }
  54298. var tags = tagsString.split(" ");
  54299. for (var t in tags) {
  54300. Tags._RemoveTagFrom(obj, tags[t]);
  54301. }
  54302. };
  54303. Tags._RemoveTagFrom = function (obj, tag) {
  54304. delete obj._tags[tag];
  54305. };
  54306. Tags.MatchesQuery = function (obj, tagsQuery) {
  54307. if (tagsQuery === undefined) {
  54308. return true;
  54309. }
  54310. if (tagsQuery === "") {
  54311. return Tags.HasTags(obj);
  54312. }
  54313. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54314. };
  54315. return Tags;
  54316. }());
  54317. BABYLON.Tags = Tags;
  54318. })(BABYLON || (BABYLON = {}));
  54319. //# sourceMappingURL=babylon.tags.js.map
  54320. var BABYLON;
  54321. (function (BABYLON) {
  54322. var Internals;
  54323. (function (Internals) {
  54324. var AndOrNotEvaluator = /** @class */ (function () {
  54325. function AndOrNotEvaluator() {
  54326. }
  54327. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54328. if (!query.match(/\([^\(\)]*\)/g)) {
  54329. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54330. }
  54331. else {
  54332. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54333. // remove parenthesis
  54334. r = r.slice(1, r.length - 1);
  54335. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54336. });
  54337. }
  54338. if (query === "true") {
  54339. return true;
  54340. }
  54341. if (query === "false") {
  54342. return false;
  54343. }
  54344. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54345. };
  54346. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54347. evaluateCallback = evaluateCallback || (function (r) {
  54348. return r === "true" ? true : false;
  54349. });
  54350. var result;
  54351. var or = parenthesisContent.split("||");
  54352. for (var i in or) {
  54353. if (or.hasOwnProperty(i)) {
  54354. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54355. var and = ori.split("&&");
  54356. if (and.length > 1) {
  54357. for (var j = 0; j < and.length; ++j) {
  54358. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54359. if (andj !== "true" && andj !== "false") {
  54360. if (andj[0] === "!") {
  54361. result = !evaluateCallback(andj.substring(1));
  54362. }
  54363. else {
  54364. result = evaluateCallback(andj);
  54365. }
  54366. }
  54367. else {
  54368. result = andj === "true" ? true : false;
  54369. }
  54370. if (!result) {
  54371. ori = "false";
  54372. break;
  54373. }
  54374. }
  54375. }
  54376. if (result || ori === "true") {
  54377. result = true;
  54378. break;
  54379. }
  54380. // result equals false (or undefined)
  54381. if (ori !== "true" && ori !== "false") {
  54382. if (ori[0] === "!") {
  54383. result = !evaluateCallback(ori.substring(1));
  54384. }
  54385. else {
  54386. result = evaluateCallback(ori);
  54387. }
  54388. }
  54389. else {
  54390. result = ori === "true" ? true : false;
  54391. }
  54392. }
  54393. }
  54394. // the whole parenthesis scope is replaced by 'true' or 'false'
  54395. return result ? "true" : "false";
  54396. };
  54397. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54398. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54399. // remove whitespaces
  54400. r = r.replace(/[\s]/g, function () { return ""; });
  54401. return r.length % 2 ? "!" : "";
  54402. });
  54403. booleanString = booleanString.trim();
  54404. if (booleanString === "!true") {
  54405. booleanString = "false";
  54406. }
  54407. else if (booleanString === "!false") {
  54408. booleanString = "true";
  54409. }
  54410. return booleanString;
  54411. };
  54412. return AndOrNotEvaluator;
  54413. }());
  54414. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54415. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54416. })(BABYLON || (BABYLON = {}));
  54417. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54418. var BABYLON;
  54419. (function (BABYLON) {
  54420. var Database = /** @class */ (function () {
  54421. function Database(urlToScene, callbackManifestChecked) {
  54422. // Handling various flavors of prefixed version of IndexedDB
  54423. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54424. this.callbackManifestChecked = callbackManifestChecked;
  54425. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54426. this.db = null;
  54427. this._enableSceneOffline = false;
  54428. this._enableTexturesOffline = false;
  54429. this.manifestVersionFound = 0;
  54430. this.mustUpdateRessources = false;
  54431. this.hasReachedQuota = false;
  54432. if (!Database.IDBStorageEnabled) {
  54433. this.callbackManifestChecked(true);
  54434. }
  54435. else {
  54436. this.checkManifestFile();
  54437. }
  54438. }
  54439. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54440. get: function () {
  54441. return this._enableSceneOffline;
  54442. },
  54443. enumerable: true,
  54444. configurable: true
  54445. });
  54446. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54447. get: function () {
  54448. return this._enableTexturesOffline;
  54449. },
  54450. enumerable: true,
  54451. configurable: true
  54452. });
  54453. Database.prototype.checkManifestFile = function () {
  54454. var _this = this;
  54455. var noManifestFile = function () {
  54456. _this._enableSceneOffline = false;
  54457. _this._enableTexturesOffline = false;
  54458. _this.callbackManifestChecked(false);
  54459. };
  54460. var timeStampUsed = false;
  54461. var manifestURL = this.currentSceneUrl + ".manifest";
  54462. var xhr = new XMLHttpRequest();
  54463. if (navigator.onLine) {
  54464. // Adding a timestamp to by-pass browsers' cache
  54465. timeStampUsed = true;
  54466. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54467. }
  54468. xhr.open("GET", manifestURL, true);
  54469. xhr.addEventListener("load", function () {
  54470. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54471. try {
  54472. var manifestFile = JSON.parse(xhr.response);
  54473. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54474. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54475. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54476. _this.manifestVersionFound = manifestFile.version;
  54477. }
  54478. if (_this.callbackManifestChecked) {
  54479. _this.callbackManifestChecked(true);
  54480. }
  54481. }
  54482. catch (ex) {
  54483. noManifestFile();
  54484. }
  54485. }
  54486. else {
  54487. noManifestFile();
  54488. }
  54489. }, false);
  54490. xhr.addEventListener("error", function (event) {
  54491. if (timeStampUsed) {
  54492. timeStampUsed = false;
  54493. // Let's retry without the timeStamp
  54494. // It could fail when coupled with HTML5 Offline API
  54495. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54496. xhr.open("GET", retryManifestURL, true);
  54497. xhr.send();
  54498. }
  54499. else {
  54500. noManifestFile();
  54501. }
  54502. }, false);
  54503. try {
  54504. xhr.send();
  54505. }
  54506. catch (ex) {
  54507. BABYLON.Tools.Error("Error on XHR send request.");
  54508. this.callbackManifestChecked(false);
  54509. }
  54510. };
  54511. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54512. var _this = this;
  54513. var handleError = function () {
  54514. _this.isSupported = false;
  54515. if (errorCallback)
  54516. errorCallback();
  54517. };
  54518. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54519. // Your browser doesn't support IndexedDB
  54520. this.isSupported = false;
  54521. if (errorCallback)
  54522. errorCallback();
  54523. }
  54524. else {
  54525. // If the DB hasn't been opened or created yet
  54526. if (!this.db) {
  54527. this.hasReachedQuota = false;
  54528. this.isSupported = true;
  54529. var request = this.idbFactory.open("babylonjs", 1);
  54530. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54531. request.onerror = function (event) {
  54532. handleError();
  54533. };
  54534. // executes when a version change transaction cannot complete due to other active transactions
  54535. request.onblocked = function (event) {
  54536. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54537. handleError();
  54538. };
  54539. // DB has been opened successfully
  54540. request.onsuccess = function (event) {
  54541. _this.db = request.result;
  54542. successCallback();
  54543. };
  54544. // Initialization of the DB. Creating Scenes & Textures stores
  54545. request.onupgradeneeded = function (event) {
  54546. _this.db = (event.target).result;
  54547. if (_this.db) {
  54548. try {
  54549. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54550. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54551. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54552. }
  54553. catch (ex) {
  54554. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54555. handleError();
  54556. }
  54557. }
  54558. };
  54559. }
  54560. else {
  54561. if (successCallback)
  54562. successCallback();
  54563. }
  54564. }
  54565. };
  54566. Database.prototype.loadImageFromDB = function (url, image) {
  54567. var _this = this;
  54568. var completeURL = Database.ReturnFullUrlLocation(url);
  54569. var saveAndLoadImage = function () {
  54570. if (!_this.hasReachedQuota && _this.db !== null) {
  54571. // the texture is not yet in the DB, let's try to save it
  54572. _this._saveImageIntoDBAsync(completeURL, image);
  54573. }
  54574. else {
  54575. image.src = url;
  54576. }
  54577. };
  54578. if (!this.mustUpdateRessources) {
  54579. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54580. }
  54581. else {
  54582. saveAndLoadImage();
  54583. }
  54584. };
  54585. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54586. if (this.isSupported && this.db !== null) {
  54587. var texture;
  54588. var transaction = this.db.transaction(["textures"]);
  54589. transaction.onabort = function (event) {
  54590. image.src = url;
  54591. };
  54592. transaction.oncomplete = function (event) {
  54593. var blobTextureURL;
  54594. if (texture) {
  54595. var URL = window.URL || window.webkitURL;
  54596. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54597. image.onerror = function () {
  54598. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54599. image.src = url;
  54600. };
  54601. image.src = blobTextureURL;
  54602. }
  54603. else {
  54604. notInDBCallback();
  54605. }
  54606. };
  54607. var getRequest = transaction.objectStore("textures").get(url);
  54608. getRequest.onsuccess = function (event) {
  54609. texture = (event.target).result;
  54610. };
  54611. getRequest.onerror = function (event) {
  54612. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54613. image.src = url;
  54614. };
  54615. }
  54616. else {
  54617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54618. image.src = url;
  54619. }
  54620. };
  54621. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54622. var _this = this;
  54623. if (this.isSupported) {
  54624. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54625. var generateBlobUrl = function () {
  54626. var blobTextureURL;
  54627. if (blob) {
  54628. var URL = window.URL || window.webkitURL;
  54629. try {
  54630. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54631. }
  54632. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54633. catch (ex) {
  54634. blobTextureURL = URL.createObjectURL(blob);
  54635. }
  54636. }
  54637. if (blobTextureURL) {
  54638. image.src = blobTextureURL;
  54639. }
  54640. };
  54641. if (Database.IsUASupportingBlobStorage) {
  54642. var xhr = new XMLHttpRequest(), blob;
  54643. xhr.open("GET", url, true);
  54644. xhr.responseType = "blob";
  54645. xhr.addEventListener("load", function () {
  54646. if (xhr.status === 200 && _this.db) {
  54647. // Blob as response (XHR2)
  54648. blob = xhr.response;
  54649. var transaction = _this.db.transaction(["textures"], "readwrite");
  54650. // the transaction could abort because of a QuotaExceededError error
  54651. transaction.onabort = function (event) {
  54652. try {
  54653. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54654. var srcElement = (event.srcElement || event.target);
  54655. var error = srcElement.error;
  54656. if (error && error.name === "QuotaExceededError") {
  54657. _this.hasReachedQuota = true;
  54658. }
  54659. }
  54660. catch (ex) { }
  54661. generateBlobUrl();
  54662. };
  54663. transaction.oncomplete = function (event) {
  54664. generateBlobUrl();
  54665. };
  54666. var newTexture = { textureUrl: url, data: blob };
  54667. try {
  54668. // Put the blob into the dabase
  54669. var addRequest = transaction.objectStore("textures").put(newTexture);
  54670. addRequest.onsuccess = function (event) {
  54671. };
  54672. addRequest.onerror = function (event) {
  54673. generateBlobUrl();
  54674. };
  54675. }
  54676. catch (ex) {
  54677. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54678. if (ex.code === 25) {
  54679. Database.IsUASupportingBlobStorage = false;
  54680. }
  54681. image.src = url;
  54682. }
  54683. }
  54684. else {
  54685. image.src = url;
  54686. }
  54687. }, false);
  54688. xhr.addEventListener("error", function (event) {
  54689. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54690. image.src = url;
  54691. }, false);
  54692. xhr.send();
  54693. }
  54694. else {
  54695. image.src = url;
  54696. }
  54697. }
  54698. else {
  54699. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54700. image.src = url;
  54701. }
  54702. };
  54703. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54704. var _this = this;
  54705. var updateVersion = function () {
  54706. // the version is not yet in the DB or we need to update it
  54707. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54708. };
  54709. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54710. };
  54711. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54712. var _this = this;
  54713. if (this.isSupported && this.db) {
  54714. var version;
  54715. try {
  54716. var transaction = this.db.transaction(["versions"]);
  54717. transaction.oncomplete = function (event) {
  54718. if (version) {
  54719. // If the version in the JSON file is > than the version in DB
  54720. if (_this.manifestVersionFound > version.data) {
  54721. _this.mustUpdateRessources = true;
  54722. updateInDBCallback();
  54723. }
  54724. else {
  54725. callback(version.data);
  54726. }
  54727. }
  54728. else {
  54729. _this.mustUpdateRessources = true;
  54730. updateInDBCallback();
  54731. }
  54732. };
  54733. transaction.onabort = function (event) {
  54734. callback(-1);
  54735. };
  54736. var getRequest = transaction.objectStore("versions").get(url);
  54737. getRequest.onsuccess = function (event) {
  54738. version = (event.target).result;
  54739. };
  54740. getRequest.onerror = function (event) {
  54741. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54742. callback(-1);
  54743. };
  54744. }
  54745. catch (ex) {
  54746. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54747. callback(-1);
  54748. }
  54749. }
  54750. else {
  54751. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54752. callback(-1);
  54753. }
  54754. };
  54755. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54756. var _this = this;
  54757. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54758. try {
  54759. // Open a transaction to the database
  54760. var transaction = this.db.transaction(["versions"], "readwrite");
  54761. // the transaction could abort because of a QuotaExceededError error
  54762. transaction.onabort = function (event) {
  54763. try {
  54764. var error = event.srcElement['error'];
  54765. if (error && error.name === "QuotaExceededError") {
  54766. _this.hasReachedQuota = true;
  54767. }
  54768. }
  54769. catch (ex) { }
  54770. callback(-1);
  54771. };
  54772. transaction.oncomplete = function (event) {
  54773. callback(_this.manifestVersionFound);
  54774. };
  54775. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54776. // Put the scene into the database
  54777. var addRequest = transaction.objectStore("versions").put(newVersion);
  54778. addRequest.onsuccess = function (event) {
  54779. };
  54780. addRequest.onerror = function (event) {
  54781. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54782. };
  54783. }
  54784. catch (ex) {
  54785. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54786. callback(-1);
  54787. }
  54788. }
  54789. else {
  54790. callback(-1);
  54791. }
  54792. };
  54793. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54794. var _this = this;
  54795. var completeUrl = Database.ReturnFullUrlLocation(url);
  54796. var saveAndLoadFile = function () {
  54797. // the scene is not yet in the DB, let's try to save it
  54798. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54799. };
  54800. this._checkVersionFromDB(completeUrl, function (version) {
  54801. if (version !== -1) {
  54802. if (!_this.mustUpdateRessources) {
  54803. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54804. }
  54805. else {
  54806. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54807. }
  54808. }
  54809. else {
  54810. if (errorCallback) {
  54811. errorCallback();
  54812. }
  54813. }
  54814. });
  54815. };
  54816. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54817. if (this.isSupported && this.db) {
  54818. var targetStore;
  54819. if (url.indexOf(".babylon") !== -1) {
  54820. targetStore = "scenes";
  54821. }
  54822. else {
  54823. targetStore = "textures";
  54824. }
  54825. var file;
  54826. var transaction = this.db.transaction([targetStore]);
  54827. transaction.oncomplete = function (event) {
  54828. if (file) {
  54829. callback(file.data);
  54830. }
  54831. else {
  54832. notInDBCallback();
  54833. }
  54834. };
  54835. transaction.onabort = function (event) {
  54836. notInDBCallback();
  54837. };
  54838. var getRequest = transaction.objectStore(targetStore).get(url);
  54839. getRequest.onsuccess = function (event) {
  54840. file = (event.target).result;
  54841. };
  54842. getRequest.onerror = function (event) {
  54843. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54844. notInDBCallback();
  54845. };
  54846. }
  54847. else {
  54848. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54849. callback();
  54850. }
  54851. };
  54852. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54853. var _this = this;
  54854. if (this.isSupported) {
  54855. var targetStore;
  54856. if (url.indexOf(".babylon") !== -1) {
  54857. targetStore = "scenes";
  54858. }
  54859. else {
  54860. targetStore = "textures";
  54861. }
  54862. // Create XHR
  54863. var xhr = new XMLHttpRequest();
  54864. var fileData;
  54865. xhr.open("GET", url, true);
  54866. if (useArrayBuffer) {
  54867. xhr.responseType = "arraybuffer";
  54868. }
  54869. if (progressCallback) {
  54870. xhr.onprogress = progressCallback;
  54871. }
  54872. xhr.addEventListener("load", function () {
  54873. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54874. // Blob as response (XHR2)
  54875. //fileData = xhr.responseText;
  54876. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54877. if (!_this.hasReachedQuota && _this.db) {
  54878. // Open a transaction to the database
  54879. var transaction = _this.db.transaction([targetStore], "readwrite");
  54880. // the transaction could abort because of a QuotaExceededError error
  54881. transaction.onabort = function (event) {
  54882. try {
  54883. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54884. var error = event.srcElement['error'];
  54885. if (error && error.name === "QuotaExceededError") {
  54886. _this.hasReachedQuota = true;
  54887. }
  54888. }
  54889. catch (ex) { }
  54890. callback(fileData);
  54891. };
  54892. transaction.oncomplete = function (event) {
  54893. callback(fileData);
  54894. };
  54895. var newFile;
  54896. if (targetStore === "scenes") {
  54897. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54898. }
  54899. else {
  54900. newFile = { textureUrl: url, data: fileData };
  54901. }
  54902. try {
  54903. // Put the scene into the database
  54904. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54905. addRequest.onsuccess = function (event) {
  54906. };
  54907. addRequest.onerror = function (event) {
  54908. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54909. };
  54910. }
  54911. catch (ex) {
  54912. callback(fileData);
  54913. }
  54914. }
  54915. else {
  54916. callback(fileData);
  54917. }
  54918. }
  54919. else {
  54920. callback();
  54921. }
  54922. }, false);
  54923. xhr.addEventListener("error", function (event) {
  54924. BABYLON.Tools.Error("error on XHR request.");
  54925. callback();
  54926. }, false);
  54927. xhr.send();
  54928. }
  54929. else {
  54930. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54931. callback();
  54932. }
  54933. };
  54934. Database.IsUASupportingBlobStorage = true;
  54935. Database.IDBStorageEnabled = true;
  54936. Database.parseURL = function (url) {
  54937. var a = document.createElement('a');
  54938. a.href = url;
  54939. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54940. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54941. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54942. return absLocation;
  54943. };
  54944. Database.ReturnFullUrlLocation = function (url) {
  54945. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54946. return (Database.parseURL(window.location.href) + url);
  54947. }
  54948. else {
  54949. return url;
  54950. }
  54951. };
  54952. return Database;
  54953. }());
  54954. BABYLON.Database = Database;
  54955. })(BABYLON || (BABYLON = {}));
  54956. //# sourceMappingURL=babylon.database.js.map
  54957. var BABYLON;
  54958. (function (BABYLON) {
  54959. var FresnelParameters = /** @class */ (function () {
  54960. function FresnelParameters() {
  54961. this._isEnabled = true;
  54962. this.leftColor = BABYLON.Color3.White();
  54963. this.rightColor = BABYLON.Color3.Black();
  54964. this.bias = 0;
  54965. this.power = 1;
  54966. }
  54967. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54968. get: function () {
  54969. return this._isEnabled;
  54970. },
  54971. set: function (value) {
  54972. if (this._isEnabled === value) {
  54973. return;
  54974. }
  54975. this._isEnabled = value;
  54976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54977. },
  54978. enumerable: true,
  54979. configurable: true
  54980. });
  54981. FresnelParameters.prototype.clone = function () {
  54982. var newFresnelParameters = new FresnelParameters();
  54983. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54984. return newFresnelParameters;
  54985. };
  54986. FresnelParameters.prototype.serialize = function () {
  54987. var serializationObject = {};
  54988. serializationObject.isEnabled = this.isEnabled;
  54989. serializationObject.leftColor = this.leftColor;
  54990. serializationObject.rightColor = this.rightColor;
  54991. serializationObject.bias = this.bias;
  54992. serializationObject.power = this.power;
  54993. return serializationObject;
  54994. };
  54995. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54996. var fresnelParameters = new FresnelParameters();
  54997. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54998. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54999. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  55000. fresnelParameters.bias = parsedFresnelParameters.bias;
  55001. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  55002. return fresnelParameters;
  55003. };
  55004. return FresnelParameters;
  55005. }());
  55006. BABYLON.FresnelParameters = FresnelParameters;
  55007. })(BABYLON || (BABYLON = {}));
  55008. //# sourceMappingURL=babylon.fresnelParameters.js.map
  55009. var BABYLON;
  55010. (function (BABYLON) {
  55011. var MultiMaterial = /** @class */ (function (_super) {
  55012. __extends(MultiMaterial, _super);
  55013. function MultiMaterial(name, scene) {
  55014. var _this = _super.call(this, name, scene, true) || this;
  55015. scene.multiMaterials.push(_this);
  55016. _this.subMaterials = new Array();
  55017. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  55018. return _this;
  55019. }
  55020. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  55021. get: function () {
  55022. return this._subMaterials;
  55023. },
  55024. set: function (value) {
  55025. this._subMaterials = value;
  55026. this._hookArray(value);
  55027. },
  55028. enumerable: true,
  55029. configurable: true
  55030. });
  55031. MultiMaterial.prototype._hookArray = function (array) {
  55032. var _this = this;
  55033. var oldPush = array.push;
  55034. array.push = function () {
  55035. var items = [];
  55036. for (var _i = 0; _i < arguments.length; _i++) {
  55037. items[_i] = arguments[_i];
  55038. }
  55039. var result = oldPush.apply(array, items);
  55040. _this._markAllSubMeshesAsTexturesDirty();
  55041. return result;
  55042. };
  55043. var oldSplice = array.splice;
  55044. array.splice = function (index, deleteCount) {
  55045. var deleted = oldSplice.apply(array, [index, deleteCount]);
  55046. _this._markAllSubMeshesAsTexturesDirty();
  55047. return deleted;
  55048. };
  55049. };
  55050. // Properties
  55051. MultiMaterial.prototype.getSubMaterial = function (index) {
  55052. if (index < 0 || index >= this.subMaterials.length) {
  55053. return this.getScene().defaultMaterial;
  55054. }
  55055. return this.subMaterials[index];
  55056. };
  55057. MultiMaterial.prototype.getActiveTextures = function () {
  55058. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  55059. if (subMaterial) {
  55060. return subMaterial.getActiveTextures();
  55061. }
  55062. else {
  55063. return [];
  55064. }
  55065. }));
  55066. var _a;
  55067. };
  55068. // Methods
  55069. MultiMaterial.prototype.getClassName = function () {
  55070. return "MultiMaterial";
  55071. };
  55072. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  55073. for (var index = 0; index < this.subMaterials.length; index++) {
  55074. var subMaterial = this.subMaterials[index];
  55075. if (subMaterial) {
  55076. if (subMaterial.storeEffectOnSubMeshes) {
  55077. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  55078. return false;
  55079. }
  55080. continue;
  55081. }
  55082. if (!subMaterial.isReady(mesh)) {
  55083. return false;
  55084. }
  55085. }
  55086. }
  55087. return true;
  55088. };
  55089. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  55090. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  55091. for (var index = 0; index < this.subMaterials.length; index++) {
  55092. var subMaterial = null;
  55093. var current = this.subMaterials[index];
  55094. if (cloneChildren && current) {
  55095. subMaterial = current.clone(name + "-" + current.name);
  55096. }
  55097. else {
  55098. subMaterial = this.subMaterials[index];
  55099. }
  55100. newMultiMaterial.subMaterials.push(subMaterial);
  55101. }
  55102. return newMultiMaterial;
  55103. };
  55104. MultiMaterial.prototype.serialize = function () {
  55105. var serializationObject = {};
  55106. serializationObject.name = this.name;
  55107. serializationObject.id = this.id;
  55108. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55109. serializationObject.materials = [];
  55110. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55111. var subMat = this.subMaterials[matIndex];
  55112. if (subMat) {
  55113. serializationObject.materials.push(subMat.id);
  55114. }
  55115. else {
  55116. serializationObject.materials.push(null);
  55117. }
  55118. }
  55119. return serializationObject;
  55120. };
  55121. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55122. var scene = this.getScene();
  55123. if (!scene) {
  55124. return;
  55125. }
  55126. var index = scene.multiMaterials.indexOf(this);
  55127. if (index >= 0) {
  55128. scene.multiMaterials.splice(index, 1);
  55129. }
  55130. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55131. };
  55132. return MultiMaterial;
  55133. }(BABYLON.Material));
  55134. BABYLON.MultiMaterial = MultiMaterial;
  55135. })(BABYLON || (BABYLON = {}));
  55136. //# sourceMappingURL=babylon.multiMaterial.js.map
  55137. var BABYLON;
  55138. (function (BABYLON) {
  55139. var FreeCameraTouchInput = /** @class */ (function () {
  55140. function FreeCameraTouchInput() {
  55141. this._offsetX = null;
  55142. this._offsetY = null;
  55143. this._pointerPressed = new Array();
  55144. this.touchAngularSensibility = 200000.0;
  55145. this.touchMoveSensibility = 250.0;
  55146. }
  55147. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55148. var _this = this;
  55149. var previousPosition = null;
  55150. if (this._pointerInput === undefined) {
  55151. this._onLostFocus = function (evt) {
  55152. _this._offsetX = null;
  55153. _this._offsetY = null;
  55154. };
  55155. this._pointerInput = function (p, s) {
  55156. var evt = p.event;
  55157. if (evt.pointerType === "mouse") {
  55158. return;
  55159. }
  55160. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55161. if (!noPreventDefault) {
  55162. evt.preventDefault();
  55163. }
  55164. _this._pointerPressed.push(evt.pointerId);
  55165. if (_this._pointerPressed.length !== 1) {
  55166. return;
  55167. }
  55168. previousPosition = {
  55169. x: evt.clientX,
  55170. y: evt.clientY
  55171. };
  55172. }
  55173. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55174. if (!noPreventDefault) {
  55175. evt.preventDefault();
  55176. }
  55177. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55178. if (index === -1) {
  55179. return;
  55180. }
  55181. _this._pointerPressed.splice(index, 1);
  55182. if (index != 0) {
  55183. return;
  55184. }
  55185. previousPosition = null;
  55186. _this._offsetX = null;
  55187. _this._offsetY = null;
  55188. }
  55189. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55190. if (!noPreventDefault) {
  55191. evt.preventDefault();
  55192. }
  55193. if (!previousPosition) {
  55194. return;
  55195. }
  55196. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55197. if (index != 0) {
  55198. return;
  55199. }
  55200. _this._offsetX = evt.clientX - previousPosition.x;
  55201. _this._offsetY = -(evt.clientY - previousPosition.y);
  55202. }
  55203. };
  55204. }
  55205. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55206. if (this._onLostFocus) {
  55207. element.addEventListener("blur", this._onLostFocus);
  55208. }
  55209. };
  55210. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55211. if (this._pointerInput && element) {
  55212. if (this._observer) {
  55213. this.camera.getScene().onPointerObservable.remove(this._observer);
  55214. this._observer = null;
  55215. }
  55216. if (this._onLostFocus) {
  55217. element.removeEventListener("blur", this._onLostFocus);
  55218. this._onLostFocus = null;
  55219. }
  55220. this._pointerPressed = [];
  55221. this._offsetX = null;
  55222. this._offsetY = null;
  55223. }
  55224. };
  55225. FreeCameraTouchInput.prototype.checkInputs = function () {
  55226. if (this._offsetX && this._offsetY) {
  55227. var camera = this.camera;
  55228. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55229. if (this._pointerPressed.length > 1) {
  55230. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55231. }
  55232. else {
  55233. var speed = camera._computeLocalCameraSpeed();
  55234. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55235. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55236. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55237. }
  55238. }
  55239. };
  55240. FreeCameraTouchInput.prototype.getClassName = function () {
  55241. return "FreeCameraTouchInput";
  55242. };
  55243. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55244. return "touch";
  55245. };
  55246. __decorate([
  55247. BABYLON.serialize()
  55248. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55249. __decorate([
  55250. BABYLON.serialize()
  55251. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55252. return FreeCameraTouchInput;
  55253. }());
  55254. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55255. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55256. })(BABYLON || (BABYLON = {}));
  55257. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55258. var BABYLON;
  55259. (function (BABYLON) {
  55260. // We're mainly based on the logic defined into the FreeCamera code
  55261. var TouchCamera = /** @class */ (function (_super) {
  55262. __extends(TouchCamera, _super);
  55263. //-- end properties for backward compatibility for inputs
  55264. function TouchCamera(name, position, scene) {
  55265. var _this = _super.call(this, name, position, scene) || this;
  55266. _this.inputs.addTouch();
  55267. _this._setupInputs();
  55268. return _this;
  55269. }
  55270. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55271. //-- Begin properties for backward compatibility for inputs
  55272. get: function () {
  55273. var touch = this.inputs.attached["touch"];
  55274. if (touch)
  55275. return touch.touchAngularSensibility;
  55276. return 0;
  55277. },
  55278. set: function (value) {
  55279. var touch = this.inputs.attached["touch"];
  55280. if (touch)
  55281. touch.touchAngularSensibility = value;
  55282. },
  55283. enumerable: true,
  55284. configurable: true
  55285. });
  55286. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55287. get: function () {
  55288. var touch = this.inputs.attached["touch"];
  55289. if (touch)
  55290. return touch.touchMoveSensibility;
  55291. return 0;
  55292. },
  55293. set: function (value) {
  55294. var touch = this.inputs.attached["touch"];
  55295. if (touch)
  55296. touch.touchMoveSensibility = value;
  55297. },
  55298. enumerable: true,
  55299. configurable: true
  55300. });
  55301. TouchCamera.prototype.getClassName = function () {
  55302. return "TouchCamera";
  55303. };
  55304. TouchCamera.prototype._setupInputs = function () {
  55305. var mouse = this.inputs.attached["mouse"];
  55306. if (mouse) {
  55307. mouse.touchEnabled = false;
  55308. }
  55309. };
  55310. return TouchCamera;
  55311. }(BABYLON.FreeCamera));
  55312. BABYLON.TouchCamera = TouchCamera;
  55313. })(BABYLON || (BABYLON = {}));
  55314. //# sourceMappingURL=babylon.touchCamera.js.map
  55315. var BABYLON;
  55316. (function (BABYLON) {
  55317. var ProceduralTexture = /** @class */ (function (_super) {
  55318. __extends(ProceduralTexture, _super);
  55319. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55320. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55321. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55322. if (isCube === void 0) { isCube = false; }
  55323. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55324. _this.isCube = isCube;
  55325. _this.isEnabled = true;
  55326. _this._currentRefreshId = -1;
  55327. _this._refreshRate = 1;
  55328. _this._vertexBuffers = {};
  55329. _this._uniforms = new Array();
  55330. _this._samplers = new Array();
  55331. _this._textures = {};
  55332. _this._floats = {};
  55333. _this._floatsArrays = {};
  55334. _this._colors3 = {};
  55335. _this._colors4 = {};
  55336. _this._vectors2 = {};
  55337. _this._vectors3 = {};
  55338. _this._matrices = {};
  55339. _this._fallbackTextureUsed = false;
  55340. scene._proceduralTextures.push(_this);
  55341. _this._engine = scene.getEngine();
  55342. _this.name = name;
  55343. _this.isRenderTarget = true;
  55344. _this._size = size;
  55345. _this._generateMipMaps = generateMipMaps;
  55346. _this.setFragment(fragment);
  55347. _this._fallbackTexture = fallbackTexture;
  55348. if (isCube) {
  55349. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55350. _this.setFloat("face", 0);
  55351. }
  55352. else {
  55353. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55354. }
  55355. // VBO
  55356. var vertices = [];
  55357. vertices.push(1, 1);
  55358. vertices.push(-1, 1);
  55359. vertices.push(-1, -1);
  55360. vertices.push(1, -1);
  55361. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55362. _this._createIndexBuffer();
  55363. return _this;
  55364. }
  55365. ProceduralTexture.prototype._createIndexBuffer = function () {
  55366. var engine = this._engine;
  55367. // Indices
  55368. var indices = [];
  55369. indices.push(0);
  55370. indices.push(1);
  55371. indices.push(2);
  55372. indices.push(0);
  55373. indices.push(2);
  55374. indices.push(3);
  55375. this._indexBuffer = engine.createIndexBuffer(indices);
  55376. };
  55377. ProceduralTexture.prototype._rebuild = function () {
  55378. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55379. if (vb) {
  55380. vb._rebuild();
  55381. }
  55382. this._createIndexBuffer();
  55383. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55384. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55385. }
  55386. };
  55387. ProceduralTexture.prototype.reset = function () {
  55388. if (this._effect === undefined) {
  55389. return;
  55390. }
  55391. var engine = this._engine;
  55392. engine._releaseEffect(this._effect);
  55393. };
  55394. ProceduralTexture.prototype.isReady = function () {
  55395. var _this = this;
  55396. var engine = this._engine;
  55397. var shaders;
  55398. if (!this._fragment) {
  55399. return false;
  55400. }
  55401. if (this._fallbackTextureUsed) {
  55402. return true;
  55403. }
  55404. if (this._fragment.fragmentElement !== undefined) {
  55405. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55406. }
  55407. else {
  55408. shaders = { vertex: "procedural", fragment: this._fragment };
  55409. }
  55410. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55411. _this.releaseInternalTexture();
  55412. if (_this._fallbackTexture) {
  55413. _this._texture = _this._fallbackTexture._texture;
  55414. if (_this._texture) {
  55415. _this._texture.incrementReferences();
  55416. }
  55417. }
  55418. _this._fallbackTextureUsed = true;
  55419. });
  55420. return this._effect.isReady();
  55421. };
  55422. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55423. this._currentRefreshId = -1;
  55424. };
  55425. ProceduralTexture.prototype.setFragment = function (fragment) {
  55426. this._fragment = fragment;
  55427. };
  55428. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55429. get: function () {
  55430. return this._refreshRate;
  55431. },
  55432. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55433. set: function (value) {
  55434. this._refreshRate = value;
  55435. this.resetRefreshCounter();
  55436. },
  55437. enumerable: true,
  55438. configurable: true
  55439. });
  55440. ProceduralTexture.prototype._shouldRender = function () {
  55441. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55442. return false;
  55443. }
  55444. if (this._fallbackTextureUsed) {
  55445. return false;
  55446. }
  55447. if (this._currentRefreshId === -1) {
  55448. this._currentRefreshId = 1;
  55449. return true;
  55450. }
  55451. if (this.refreshRate === this._currentRefreshId) {
  55452. this._currentRefreshId = 1;
  55453. return true;
  55454. }
  55455. this._currentRefreshId++;
  55456. return false;
  55457. };
  55458. ProceduralTexture.prototype.getRenderSize = function () {
  55459. return this._size;
  55460. };
  55461. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55462. if (this._fallbackTextureUsed) {
  55463. return;
  55464. }
  55465. this.releaseInternalTexture();
  55466. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55467. };
  55468. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55469. if (this._uniforms.indexOf(uniformName) === -1) {
  55470. this._uniforms.push(uniformName);
  55471. }
  55472. };
  55473. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55474. if (this._samplers.indexOf(name) === -1) {
  55475. this._samplers.push(name);
  55476. }
  55477. this._textures[name] = texture;
  55478. return this;
  55479. };
  55480. ProceduralTexture.prototype.setFloat = function (name, value) {
  55481. this._checkUniform(name);
  55482. this._floats[name] = value;
  55483. return this;
  55484. };
  55485. ProceduralTexture.prototype.setFloats = function (name, value) {
  55486. this._checkUniform(name);
  55487. this._floatsArrays[name] = value;
  55488. return this;
  55489. };
  55490. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55491. this._checkUniform(name);
  55492. this._colors3[name] = value;
  55493. return this;
  55494. };
  55495. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55496. this._checkUniform(name);
  55497. this._colors4[name] = value;
  55498. return this;
  55499. };
  55500. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55501. this._checkUniform(name);
  55502. this._vectors2[name] = value;
  55503. return this;
  55504. };
  55505. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55506. this._checkUniform(name);
  55507. this._vectors3[name] = value;
  55508. return this;
  55509. };
  55510. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55511. this._checkUniform(name);
  55512. this._matrices[name] = value;
  55513. return this;
  55514. };
  55515. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55516. var scene = this.getScene();
  55517. if (!scene) {
  55518. return;
  55519. }
  55520. var engine = this._engine;
  55521. // Render
  55522. engine.enableEffect(this._effect);
  55523. engine.setState(false);
  55524. // Texture
  55525. for (var name in this._textures) {
  55526. this._effect.setTexture(name, this._textures[name]);
  55527. }
  55528. // Float
  55529. for (name in this._floats) {
  55530. this._effect.setFloat(name, this._floats[name]);
  55531. }
  55532. // Floats
  55533. for (name in this._floatsArrays) {
  55534. this._effect.setArray(name, this._floatsArrays[name]);
  55535. }
  55536. // Color3
  55537. for (name in this._colors3) {
  55538. this._effect.setColor3(name, this._colors3[name]);
  55539. }
  55540. // Color4
  55541. for (name in this._colors4) {
  55542. var color = this._colors4[name];
  55543. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55544. }
  55545. // Vector2
  55546. for (name in this._vectors2) {
  55547. this._effect.setVector2(name, this._vectors2[name]);
  55548. }
  55549. // Vector3
  55550. for (name in this._vectors3) {
  55551. this._effect.setVector3(name, this._vectors3[name]);
  55552. }
  55553. // Matrix
  55554. for (name in this._matrices) {
  55555. this._effect.setMatrix(name, this._matrices[name]);
  55556. }
  55557. if (!this._texture) {
  55558. return;
  55559. }
  55560. if (this.isCube) {
  55561. for (var face = 0; face < 6; face++) {
  55562. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55563. // VBOs
  55564. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55565. this._effect.setFloat("face", face);
  55566. // Clear
  55567. engine.clear(scene.clearColor, true, true, true);
  55568. // Draw order
  55569. engine.draw(true, 0, 6);
  55570. // Mipmaps
  55571. if (face === 5) {
  55572. engine.generateMipMapsForCubemap(this._texture);
  55573. }
  55574. }
  55575. }
  55576. else {
  55577. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55578. // VBOs
  55579. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55580. // Clear
  55581. engine.clear(scene.clearColor, true, true, true);
  55582. // Draw order
  55583. engine.draw(true, 0, 6);
  55584. }
  55585. // Unbind
  55586. engine.unBindFramebuffer(this._texture, this.isCube);
  55587. if (this.onGenerated) {
  55588. this.onGenerated();
  55589. }
  55590. };
  55591. ProceduralTexture.prototype.clone = function () {
  55592. var textureSize = this.getSize();
  55593. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55594. // Base texture
  55595. newTexture.hasAlpha = this.hasAlpha;
  55596. newTexture.level = this.level;
  55597. // RenderTarget Texture
  55598. newTexture.coordinatesMode = this.coordinatesMode;
  55599. return newTexture;
  55600. };
  55601. ProceduralTexture.prototype.dispose = function () {
  55602. var scene = this.getScene();
  55603. if (!scene) {
  55604. return;
  55605. }
  55606. var index = scene._proceduralTextures.indexOf(this);
  55607. if (index >= 0) {
  55608. scene._proceduralTextures.splice(index, 1);
  55609. }
  55610. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55611. if (vertexBuffer) {
  55612. vertexBuffer.dispose();
  55613. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55614. }
  55615. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55616. this._indexBuffer = null;
  55617. }
  55618. _super.prototype.dispose.call(this);
  55619. };
  55620. return ProceduralTexture;
  55621. }(BABYLON.Texture));
  55622. BABYLON.ProceduralTexture = ProceduralTexture;
  55623. })(BABYLON || (BABYLON = {}));
  55624. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55625. var BABYLON;
  55626. (function (BABYLON) {
  55627. var CustomProceduralTexture = /** @class */ (function (_super) {
  55628. __extends(CustomProceduralTexture, _super);
  55629. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55630. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55631. _this._animate = true;
  55632. _this._time = 0;
  55633. _this._texturePath = texturePath;
  55634. //Try to load json
  55635. _this.loadJson(texturePath);
  55636. _this.refreshRate = 1;
  55637. return _this;
  55638. }
  55639. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55640. var _this = this;
  55641. var noConfigFile = function () {
  55642. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55643. try {
  55644. _this.setFragment(_this._texturePath);
  55645. }
  55646. catch (ex) {
  55647. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55648. }
  55649. };
  55650. var configFileUrl = jsonUrl + "/config.json";
  55651. var xhr = new XMLHttpRequest();
  55652. xhr.open("GET", configFileUrl, true);
  55653. xhr.addEventListener("load", function () {
  55654. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55655. try {
  55656. _this._config = JSON.parse(xhr.response);
  55657. _this.updateShaderUniforms();
  55658. _this.updateTextures();
  55659. _this.setFragment(_this._texturePath + "/custom");
  55660. _this._animate = _this._config.animate;
  55661. _this.refreshRate = _this._config.refreshrate;
  55662. }
  55663. catch (ex) {
  55664. noConfigFile();
  55665. }
  55666. }
  55667. else {
  55668. noConfigFile();
  55669. }
  55670. }, false);
  55671. xhr.addEventListener("error", function () {
  55672. noConfigFile();
  55673. }, false);
  55674. try {
  55675. xhr.send();
  55676. }
  55677. catch (ex) {
  55678. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55679. }
  55680. };
  55681. CustomProceduralTexture.prototype.isReady = function () {
  55682. if (!_super.prototype.isReady.call(this)) {
  55683. return false;
  55684. }
  55685. for (var name in this._textures) {
  55686. var texture = this._textures[name];
  55687. if (!texture.isReady()) {
  55688. return false;
  55689. }
  55690. }
  55691. return true;
  55692. };
  55693. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55694. var scene = this.getScene();
  55695. if (this._animate && scene) {
  55696. this._time += scene.getAnimationRatio() * 0.03;
  55697. this.updateShaderUniforms();
  55698. }
  55699. _super.prototype.render.call(this, useCameraPostProcess);
  55700. };
  55701. CustomProceduralTexture.prototype.updateTextures = function () {
  55702. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55703. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55704. }
  55705. };
  55706. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55707. if (this._config) {
  55708. for (var j = 0; j < this._config.uniforms.length; j++) {
  55709. var uniform = this._config.uniforms[j];
  55710. switch (uniform.type) {
  55711. case "float":
  55712. this.setFloat(uniform.name, uniform.value);
  55713. break;
  55714. case "color3":
  55715. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55716. break;
  55717. case "color4":
  55718. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55719. break;
  55720. case "vector2":
  55721. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55722. break;
  55723. case "vector3":
  55724. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55725. break;
  55726. }
  55727. }
  55728. }
  55729. this.setFloat("time", this._time);
  55730. };
  55731. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55732. get: function () {
  55733. return this._animate;
  55734. },
  55735. set: function (value) {
  55736. this._animate = value;
  55737. },
  55738. enumerable: true,
  55739. configurable: true
  55740. });
  55741. return CustomProceduralTexture;
  55742. }(BABYLON.ProceduralTexture));
  55743. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55744. })(BABYLON || (BABYLON = {}));
  55745. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55746. var BABYLON;
  55747. (function (BABYLON) {
  55748. var FreeCameraGamepadInput = /** @class */ (function () {
  55749. function FreeCameraGamepadInput() {
  55750. this.gamepadAngularSensibility = 200;
  55751. this.gamepadMoveSensibility = 40;
  55752. // private members
  55753. this._cameraTransform = BABYLON.Matrix.Identity();
  55754. this._deltaTransform = BABYLON.Vector3.Zero();
  55755. this._vector3 = BABYLON.Vector3.Zero();
  55756. this._vector2 = BABYLON.Vector2.Zero();
  55757. }
  55758. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55759. var _this = this;
  55760. var manager = this.camera.getScene().gamepadManager;
  55761. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55762. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55763. // prioritize XBOX gamepads.
  55764. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55765. _this.gamepad = gamepad;
  55766. }
  55767. }
  55768. });
  55769. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55770. if (_this.gamepad === gamepad) {
  55771. _this.gamepad = null;
  55772. }
  55773. });
  55774. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55775. };
  55776. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55777. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55778. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55779. this.gamepad = null;
  55780. };
  55781. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55782. if (this.gamepad && this.gamepad.leftStick) {
  55783. var camera = this.camera;
  55784. var LSValues = this.gamepad.leftStick;
  55785. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55786. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55787. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55788. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55789. var RSValues = this.gamepad.rightStick;
  55790. if (RSValues) {
  55791. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55792. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55793. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55794. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55795. }
  55796. else {
  55797. RSValues = { x: 0, y: 0 };
  55798. }
  55799. if (!camera.rotationQuaternion) {
  55800. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55801. }
  55802. else {
  55803. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55804. }
  55805. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55806. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55807. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55808. camera.cameraDirection.addInPlace(this._deltaTransform);
  55809. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55810. camera.cameraRotation.addInPlace(this._vector2);
  55811. }
  55812. };
  55813. FreeCameraGamepadInput.prototype.getClassName = function () {
  55814. return "FreeCameraGamepadInput";
  55815. };
  55816. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55817. return "gamepad";
  55818. };
  55819. __decorate([
  55820. BABYLON.serialize()
  55821. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55822. __decorate([
  55823. BABYLON.serialize()
  55824. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55825. return FreeCameraGamepadInput;
  55826. }());
  55827. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55828. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55829. })(BABYLON || (BABYLON = {}));
  55830. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55831. var BABYLON;
  55832. (function (BABYLON) {
  55833. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55834. function ArcRotateCameraGamepadInput() {
  55835. this.gamepadRotationSensibility = 80;
  55836. this.gamepadMoveSensibility = 40;
  55837. }
  55838. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55839. var _this = this;
  55840. var manager = this.camera.getScene().gamepadManager;
  55841. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55842. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55843. // prioritize XBOX gamepads.
  55844. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55845. _this.gamepad = gamepad;
  55846. }
  55847. }
  55848. });
  55849. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55850. if (_this.gamepad === gamepad) {
  55851. _this.gamepad = null;
  55852. }
  55853. });
  55854. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55855. };
  55856. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55857. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55858. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55859. this.gamepad = null;
  55860. };
  55861. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55862. if (this.gamepad) {
  55863. var camera = this.camera;
  55864. var RSValues = this.gamepad.rightStick;
  55865. if (RSValues) {
  55866. if (RSValues.x != 0) {
  55867. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55868. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55869. camera.inertialAlphaOffset += normalizedRX;
  55870. }
  55871. }
  55872. if (RSValues.y != 0) {
  55873. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55874. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55875. camera.inertialBetaOffset += normalizedRY;
  55876. }
  55877. }
  55878. }
  55879. var LSValues = this.gamepad.leftStick;
  55880. if (LSValues && LSValues.y != 0) {
  55881. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55882. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55883. this.camera.inertialRadiusOffset -= normalizedLY;
  55884. }
  55885. }
  55886. }
  55887. };
  55888. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55889. return "ArcRotateCameraGamepadInput";
  55890. };
  55891. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55892. return "gamepad";
  55893. };
  55894. __decorate([
  55895. BABYLON.serialize()
  55896. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55897. __decorate([
  55898. BABYLON.serialize()
  55899. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55900. return ArcRotateCameraGamepadInput;
  55901. }());
  55902. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55903. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55904. })(BABYLON || (BABYLON = {}));
  55905. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55906. var BABYLON;
  55907. (function (BABYLON) {
  55908. var GamepadManager = /** @class */ (function () {
  55909. function GamepadManager() {
  55910. var _this = this;
  55911. this._babylonGamepads = [];
  55912. this._oneGamepadConnected = false;
  55913. this._isMonitoring = false;
  55914. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55915. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55916. this._gamepadEventSupported = false;
  55917. }
  55918. else {
  55919. this._gamepadEventSupported = 'GamepadEvent' in window;
  55920. this._gamepadSupport = (navigator.getGamepads ||
  55921. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55922. }
  55923. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55924. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55925. for (var i in _this._babylonGamepads) {
  55926. var gamepad = _this._babylonGamepads[i];
  55927. if (gamepad && gamepad._isConnected) {
  55928. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55929. }
  55930. }
  55931. });
  55932. this._onGamepadConnectedEvent = function (evt) {
  55933. var gamepad = evt.gamepad;
  55934. if (gamepad.index in _this._babylonGamepads) {
  55935. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55936. return;
  55937. }
  55938. }
  55939. var newGamepad;
  55940. if (_this._babylonGamepads[gamepad.index]) {
  55941. newGamepad = _this._babylonGamepads[gamepad.index];
  55942. newGamepad.browserGamepad = gamepad;
  55943. newGamepad._isConnected = true;
  55944. }
  55945. else {
  55946. newGamepad = _this._addNewGamepad(gamepad);
  55947. }
  55948. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55949. _this._startMonitoringGamepads();
  55950. };
  55951. this._onGamepadDisconnectedEvent = function (evt) {
  55952. var gamepad = evt.gamepad;
  55953. // Remove the gamepad from the list of gamepads to monitor.
  55954. for (var i in _this._babylonGamepads) {
  55955. if (_this._babylonGamepads[i].index === gamepad.index) {
  55956. var disconnectedGamepad = _this._babylonGamepads[i];
  55957. disconnectedGamepad._isConnected = false;
  55958. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55959. break;
  55960. }
  55961. }
  55962. };
  55963. if (this._gamepadSupport) {
  55964. //first add already-connected gamepads
  55965. this._updateGamepadObjects();
  55966. if (this._babylonGamepads.length) {
  55967. this._startMonitoringGamepads();
  55968. }
  55969. // Checking if the gamepad connected event is supported (like in Firefox)
  55970. if (this._gamepadEventSupported) {
  55971. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55972. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55973. }
  55974. else {
  55975. this._startMonitoringGamepads();
  55976. }
  55977. }
  55978. }
  55979. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55980. get: function () {
  55981. return this._babylonGamepads;
  55982. },
  55983. enumerable: true,
  55984. configurable: true
  55985. });
  55986. GamepadManager.prototype.getGamepadByType = function (type) {
  55987. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55988. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55989. var gamepad = _a[_i];
  55990. if (gamepad && gamepad.type === type) {
  55991. return gamepad;
  55992. }
  55993. }
  55994. return null;
  55995. };
  55996. GamepadManager.prototype.dispose = function () {
  55997. if (this._gamepadEventSupported) {
  55998. if (this._onGamepadConnectedEvent) {
  55999. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  56000. }
  56001. if (this._onGamepadDisconnectedEvent) {
  56002. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  56003. }
  56004. this._onGamepadConnectedEvent = null;
  56005. this._onGamepadDisconnectedEvent = null;
  56006. }
  56007. this._babylonGamepads.forEach(function (gamepad) {
  56008. gamepad.dispose();
  56009. });
  56010. this.onGamepadConnectedObservable.clear();
  56011. this.onGamepadDisconnectedObservable.clear();
  56012. this._oneGamepadConnected = false;
  56013. this._stopMonitoringGamepads();
  56014. this._babylonGamepads = [];
  56015. };
  56016. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  56017. if (!this._oneGamepadConnected) {
  56018. this._oneGamepadConnected = true;
  56019. }
  56020. var newGamepad;
  56021. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  56022. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  56023. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  56024. }
  56025. else if (gamepad.pose) {
  56026. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  56027. }
  56028. else {
  56029. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  56030. }
  56031. this._babylonGamepads[newGamepad.index] = newGamepad;
  56032. return newGamepad;
  56033. };
  56034. GamepadManager.prototype._startMonitoringGamepads = function () {
  56035. if (!this._isMonitoring) {
  56036. this._isMonitoring = true;
  56037. this._checkGamepadsStatus();
  56038. }
  56039. };
  56040. GamepadManager.prototype._stopMonitoringGamepads = function () {
  56041. this._isMonitoring = false;
  56042. };
  56043. GamepadManager.prototype._checkGamepadsStatus = function () {
  56044. var _this = this;
  56045. // Hack to be compatible Chrome
  56046. this._updateGamepadObjects();
  56047. for (var i in this._babylonGamepads) {
  56048. var gamepad = this._babylonGamepads[i];
  56049. if (!gamepad || !gamepad.isConnected) {
  56050. continue;
  56051. }
  56052. gamepad.update();
  56053. }
  56054. if (this._isMonitoring) {
  56055. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  56056. }
  56057. };
  56058. // This function is called only on Chrome, which does not properly support
  56059. // connection/disconnection events and forces you to recopy again the gamepad object
  56060. GamepadManager.prototype._updateGamepadObjects = function () {
  56061. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  56062. for (var i = 0; i < gamepads.length; i++) {
  56063. if (gamepads[i]) {
  56064. if (!this._babylonGamepads[gamepads[i].index]) {
  56065. var newGamepad = this._addNewGamepad(gamepads[i]);
  56066. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56067. }
  56068. else {
  56069. // Forced to copy again this object for Chrome for unknown reason
  56070. this._babylonGamepads[i].browserGamepad = gamepads[i];
  56071. if (!this._babylonGamepads[i].isConnected) {
  56072. this._babylonGamepads[i]._isConnected = true;
  56073. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  56074. }
  56075. }
  56076. }
  56077. }
  56078. };
  56079. return GamepadManager;
  56080. }());
  56081. BABYLON.GamepadManager = GamepadManager;
  56082. })(BABYLON || (BABYLON = {}));
  56083. //# sourceMappingURL=babylon.gamepadManager.js.map
  56084. var BABYLON;
  56085. (function (BABYLON) {
  56086. var StickValues = /** @class */ (function () {
  56087. function StickValues(x, y) {
  56088. this.x = x;
  56089. this.y = y;
  56090. }
  56091. return StickValues;
  56092. }());
  56093. BABYLON.StickValues = StickValues;
  56094. var Gamepad = /** @class */ (function () {
  56095. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  56096. if (leftStickX === void 0) { leftStickX = 0; }
  56097. if (leftStickY === void 0) { leftStickY = 1; }
  56098. if (rightStickX === void 0) { rightStickX = 2; }
  56099. if (rightStickY === void 0) { rightStickY = 3; }
  56100. this.id = id;
  56101. this.index = index;
  56102. this.browserGamepad = browserGamepad;
  56103. this._isConnected = true;
  56104. this.type = Gamepad.GAMEPAD;
  56105. this._leftStickAxisX = leftStickX;
  56106. this._leftStickAxisY = leftStickY;
  56107. this._rightStickAxisX = rightStickX;
  56108. this._rightStickAxisY = rightStickY;
  56109. if (this.browserGamepad.axes.length >= 2) {
  56110. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56111. }
  56112. if (this.browserGamepad.axes.length >= 4) {
  56113. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56114. }
  56115. }
  56116. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56117. get: function () {
  56118. return this._isConnected;
  56119. },
  56120. enumerable: true,
  56121. configurable: true
  56122. });
  56123. Gamepad.prototype.onleftstickchanged = function (callback) {
  56124. this._onleftstickchanged = callback;
  56125. };
  56126. Gamepad.prototype.onrightstickchanged = function (callback) {
  56127. this._onrightstickchanged = callback;
  56128. };
  56129. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56130. get: function () {
  56131. return this._leftStick;
  56132. },
  56133. set: function (newValues) {
  56134. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56135. this._onleftstickchanged(newValues);
  56136. }
  56137. this._leftStick = newValues;
  56138. },
  56139. enumerable: true,
  56140. configurable: true
  56141. });
  56142. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56143. get: function () {
  56144. return this._rightStick;
  56145. },
  56146. set: function (newValues) {
  56147. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56148. this._onrightstickchanged(newValues);
  56149. }
  56150. this._rightStick = newValues;
  56151. },
  56152. enumerable: true,
  56153. configurable: true
  56154. });
  56155. Gamepad.prototype.update = function () {
  56156. if (this._leftStick) {
  56157. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56158. }
  56159. if (this._rightStick) {
  56160. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56161. }
  56162. };
  56163. Gamepad.prototype.dispose = function () {
  56164. };
  56165. Gamepad.GAMEPAD = 0;
  56166. Gamepad.GENERIC = 1;
  56167. Gamepad.XBOX = 2;
  56168. Gamepad.POSE_ENABLED = 3;
  56169. return Gamepad;
  56170. }());
  56171. BABYLON.Gamepad = Gamepad;
  56172. var GenericPad = /** @class */ (function (_super) {
  56173. __extends(GenericPad, _super);
  56174. function GenericPad(id, index, browserGamepad) {
  56175. var _this = _super.call(this, id, index, browserGamepad) || this;
  56176. _this.onButtonDownObservable = new BABYLON.Observable();
  56177. _this.onButtonUpObservable = new BABYLON.Observable();
  56178. _this.type = Gamepad.GENERIC;
  56179. _this._buttons = new Array(browserGamepad.buttons.length);
  56180. return _this;
  56181. }
  56182. GenericPad.prototype.onbuttondown = function (callback) {
  56183. this._onbuttondown = callback;
  56184. };
  56185. GenericPad.prototype.onbuttonup = function (callback) {
  56186. this._onbuttonup = callback;
  56187. };
  56188. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56189. if (newValue !== currentValue) {
  56190. if (newValue === 1) {
  56191. if (this._onbuttondown) {
  56192. this._onbuttondown(buttonIndex);
  56193. }
  56194. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56195. }
  56196. if (newValue === 0) {
  56197. if (this._onbuttonup) {
  56198. this._onbuttonup(buttonIndex);
  56199. }
  56200. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56201. }
  56202. }
  56203. return newValue;
  56204. };
  56205. GenericPad.prototype.update = function () {
  56206. _super.prototype.update.call(this);
  56207. for (var index = 0; index < this._buttons.length; index++) {
  56208. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56209. }
  56210. };
  56211. return GenericPad;
  56212. }(Gamepad));
  56213. BABYLON.GenericPad = GenericPad;
  56214. })(BABYLON || (BABYLON = {}));
  56215. //# sourceMappingURL=babylon.gamepad.js.map
  56216. var BABYLON;
  56217. (function (BABYLON) {
  56218. var Xbox360Button;
  56219. (function (Xbox360Button) {
  56220. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56221. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56222. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56223. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56224. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56225. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56226. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56227. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56228. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56229. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56230. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56231. var Xbox360Dpad;
  56232. (function (Xbox360Dpad) {
  56233. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56234. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56235. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56236. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56237. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56238. var Xbox360Pad = /** @class */ (function (_super) {
  56239. __extends(Xbox360Pad, _super);
  56240. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56241. if (xboxOne === void 0) { xboxOne = false; }
  56242. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56243. _this._leftTrigger = 0;
  56244. _this._rightTrigger = 0;
  56245. _this.onButtonDownObservable = new BABYLON.Observable();
  56246. _this.onButtonUpObservable = new BABYLON.Observable();
  56247. _this.onPadDownObservable = new BABYLON.Observable();
  56248. _this.onPadUpObservable = new BABYLON.Observable();
  56249. _this._buttonA = 0;
  56250. _this._buttonB = 0;
  56251. _this._buttonX = 0;
  56252. _this._buttonY = 0;
  56253. _this._buttonBack = 0;
  56254. _this._buttonStart = 0;
  56255. _this._buttonLB = 0;
  56256. _this._buttonRB = 0;
  56257. _this._buttonLeftStick = 0;
  56258. _this._buttonRightStick = 0;
  56259. _this._dPadUp = 0;
  56260. _this._dPadDown = 0;
  56261. _this._dPadLeft = 0;
  56262. _this._dPadRight = 0;
  56263. _this._isXboxOnePad = false;
  56264. _this.type = BABYLON.Gamepad.XBOX;
  56265. _this._isXboxOnePad = xboxOne;
  56266. return _this;
  56267. }
  56268. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56269. this._onlefttriggerchanged = callback;
  56270. };
  56271. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56272. this._onrighttriggerchanged = callback;
  56273. };
  56274. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56275. get: function () {
  56276. return this._leftTrigger;
  56277. },
  56278. set: function (newValue) {
  56279. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56280. this._onlefttriggerchanged(newValue);
  56281. }
  56282. this._leftTrigger = newValue;
  56283. },
  56284. enumerable: true,
  56285. configurable: true
  56286. });
  56287. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56288. get: function () {
  56289. return this._rightTrigger;
  56290. },
  56291. set: function (newValue) {
  56292. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56293. this._onrighttriggerchanged(newValue);
  56294. }
  56295. this._rightTrigger = newValue;
  56296. },
  56297. enumerable: true,
  56298. configurable: true
  56299. });
  56300. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56301. this._onbuttondown = callback;
  56302. };
  56303. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56304. this._onbuttonup = callback;
  56305. };
  56306. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56307. this._ondpaddown = callback;
  56308. };
  56309. Xbox360Pad.prototype.ondpadup = function (callback) {
  56310. this._ondpadup = callback;
  56311. };
  56312. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56313. if (newValue !== currentValue) {
  56314. if (newValue === 1) {
  56315. if (this._onbuttondown) {
  56316. this._onbuttondown(buttonType);
  56317. }
  56318. this.onButtonDownObservable.notifyObservers(buttonType);
  56319. }
  56320. if (newValue === 0) {
  56321. if (this._onbuttonup) {
  56322. this._onbuttonup(buttonType);
  56323. }
  56324. this.onButtonUpObservable.notifyObservers(buttonType);
  56325. }
  56326. }
  56327. return newValue;
  56328. };
  56329. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56330. if (newValue !== currentValue) {
  56331. if (newValue === 1) {
  56332. if (this._ondpaddown) {
  56333. this._ondpaddown(buttonType);
  56334. }
  56335. this.onPadDownObservable.notifyObservers(buttonType);
  56336. }
  56337. if (newValue === 0) {
  56338. if (this._ondpadup) {
  56339. this._ondpadup(buttonType);
  56340. }
  56341. this.onPadUpObservable.notifyObservers(buttonType);
  56342. }
  56343. }
  56344. return newValue;
  56345. };
  56346. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56347. get: function () {
  56348. return this._buttonA;
  56349. },
  56350. set: function (value) {
  56351. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56352. },
  56353. enumerable: true,
  56354. configurable: true
  56355. });
  56356. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56357. get: function () {
  56358. return this._buttonB;
  56359. },
  56360. set: function (value) {
  56361. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56362. },
  56363. enumerable: true,
  56364. configurable: true
  56365. });
  56366. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56367. get: function () {
  56368. return this._buttonX;
  56369. },
  56370. set: function (value) {
  56371. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56372. },
  56373. enumerable: true,
  56374. configurable: true
  56375. });
  56376. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56377. get: function () {
  56378. return this._buttonY;
  56379. },
  56380. set: function (value) {
  56381. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56382. },
  56383. enumerable: true,
  56384. configurable: true
  56385. });
  56386. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56387. get: function () {
  56388. return this._buttonStart;
  56389. },
  56390. set: function (value) {
  56391. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56392. },
  56393. enumerable: true,
  56394. configurable: true
  56395. });
  56396. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56397. get: function () {
  56398. return this._buttonBack;
  56399. },
  56400. set: function (value) {
  56401. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56402. },
  56403. enumerable: true,
  56404. configurable: true
  56405. });
  56406. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56407. get: function () {
  56408. return this._buttonLB;
  56409. },
  56410. set: function (value) {
  56411. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56412. },
  56413. enumerable: true,
  56414. configurable: true
  56415. });
  56416. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56417. get: function () {
  56418. return this._buttonRB;
  56419. },
  56420. set: function (value) {
  56421. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56422. },
  56423. enumerable: true,
  56424. configurable: true
  56425. });
  56426. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56427. get: function () {
  56428. return this._buttonLeftStick;
  56429. },
  56430. set: function (value) {
  56431. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56432. },
  56433. enumerable: true,
  56434. configurable: true
  56435. });
  56436. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56437. get: function () {
  56438. return this._buttonRightStick;
  56439. },
  56440. set: function (value) {
  56441. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56442. },
  56443. enumerable: true,
  56444. configurable: true
  56445. });
  56446. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56447. get: function () {
  56448. return this._dPadUp;
  56449. },
  56450. set: function (value) {
  56451. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56452. },
  56453. enumerable: true,
  56454. configurable: true
  56455. });
  56456. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56457. get: function () {
  56458. return this._dPadDown;
  56459. },
  56460. set: function (value) {
  56461. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56462. },
  56463. enumerable: true,
  56464. configurable: true
  56465. });
  56466. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56467. get: function () {
  56468. return this._dPadLeft;
  56469. },
  56470. set: function (value) {
  56471. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56472. },
  56473. enumerable: true,
  56474. configurable: true
  56475. });
  56476. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56477. get: function () {
  56478. return this._dPadRight;
  56479. },
  56480. set: function (value) {
  56481. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56482. },
  56483. enumerable: true,
  56484. configurable: true
  56485. });
  56486. Xbox360Pad.prototype.update = function () {
  56487. _super.prototype.update.call(this);
  56488. if (this._isXboxOnePad) {
  56489. this.buttonA = this.browserGamepad.buttons[0].value;
  56490. this.buttonB = this.browserGamepad.buttons[1].value;
  56491. this.buttonX = this.browserGamepad.buttons[2].value;
  56492. this.buttonY = this.browserGamepad.buttons[3].value;
  56493. this.buttonLB = this.browserGamepad.buttons[4].value;
  56494. this.buttonRB = this.browserGamepad.buttons[5].value;
  56495. this.leftTrigger = this.browserGamepad.axes[2];
  56496. this.rightTrigger = this.browserGamepad.axes[5];
  56497. this.buttonBack = this.browserGamepad.buttons[9].value;
  56498. this.buttonStart = this.browserGamepad.buttons[8].value;
  56499. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56500. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56501. this.dPadUp = this.browserGamepad.buttons[11].value;
  56502. this.dPadDown = this.browserGamepad.buttons[12].value;
  56503. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56504. this.dPadRight = this.browserGamepad.buttons[14].value;
  56505. }
  56506. else {
  56507. this.buttonA = this.browserGamepad.buttons[0].value;
  56508. this.buttonB = this.browserGamepad.buttons[1].value;
  56509. this.buttonX = this.browserGamepad.buttons[2].value;
  56510. this.buttonY = this.browserGamepad.buttons[3].value;
  56511. this.buttonLB = this.browserGamepad.buttons[4].value;
  56512. this.buttonRB = this.browserGamepad.buttons[5].value;
  56513. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56514. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56515. this.buttonBack = this.browserGamepad.buttons[8].value;
  56516. this.buttonStart = this.browserGamepad.buttons[9].value;
  56517. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56518. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56519. this.dPadUp = this.browserGamepad.buttons[12].value;
  56520. this.dPadDown = this.browserGamepad.buttons[13].value;
  56521. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56522. this.dPadRight = this.browserGamepad.buttons[15].value;
  56523. }
  56524. };
  56525. return Xbox360Pad;
  56526. }(BABYLON.Gamepad));
  56527. BABYLON.Xbox360Pad = Xbox360Pad;
  56528. })(BABYLON || (BABYLON = {}));
  56529. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56530. var BABYLON;
  56531. (function (BABYLON) {
  56532. var PoseEnabledControllerType;
  56533. (function (PoseEnabledControllerType) {
  56534. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56535. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56536. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56537. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56538. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56539. var PoseEnabledControllerHelper = /** @class */ (function () {
  56540. function PoseEnabledControllerHelper() {
  56541. }
  56542. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56543. // Oculus Touch
  56544. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56545. return new BABYLON.OculusTouchController(vrGamepad);
  56546. }
  56547. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56548. return new BABYLON.WindowsMotionController(vrGamepad);
  56549. }
  56550. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56551. return new BABYLON.ViveController(vrGamepad);
  56552. }
  56553. else {
  56554. return new BABYLON.GenericController(vrGamepad);
  56555. }
  56556. };
  56557. return PoseEnabledControllerHelper;
  56558. }());
  56559. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56560. var PoseEnabledController = /** @class */ (function (_super) {
  56561. __extends(PoseEnabledController, _super);
  56562. function PoseEnabledController(browserGamepad) {
  56563. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56564. _this.deviceScaleFactor = 1;
  56565. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56566. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56567. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56568. _this.position = BABYLON.Vector3.Zero();
  56569. _this.rotationQuaternion = new BABYLON.Quaternion();
  56570. _this.devicePosition = BABYLON.Vector3.Zero();
  56571. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56572. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56573. _this._calculatedRotation = new BABYLON.Quaternion();
  56574. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56575. return _this;
  56576. }
  56577. PoseEnabledController.prototype.update = function () {
  56578. _super.prototype.update.call(this);
  56579. var pose = this.browserGamepad.pose;
  56580. this.updateFromDevice(pose);
  56581. if (this._mesh) {
  56582. this._mesh.position.copyFrom(this._calculatedPosition);
  56583. if (this._mesh.rotationQuaternion) {
  56584. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  56585. }
  56586. }
  56587. };
  56588. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56589. if (poseData) {
  56590. this.rawPose = poseData;
  56591. if (poseData.position) {
  56592. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56593. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56594. this.devicePosition.z *= -1;
  56595. }
  56596. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56597. this._calculatedPosition.addInPlace(this.position);
  56598. }
  56599. var pose = this.rawPose;
  56600. if (poseData.orientation && pose.orientation) {
  56601. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56602. if (this._mesh) {
  56603. if (this._mesh.getScene().useRightHandedSystem) {
  56604. this.deviceRotationQuaternion.z *= -1;
  56605. this.deviceRotationQuaternion.w *= -1;
  56606. }
  56607. else {
  56608. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  56609. }
  56610. }
  56611. // if the camera is set, rotate to the camera's rotation
  56612. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56613. }
  56614. }
  56615. };
  56616. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56617. if (this._mesh) {
  56618. this._mesh.parent = null;
  56619. }
  56620. this._mesh = mesh;
  56621. if (this._poseControlledCamera) {
  56622. this._mesh.parent = this._poseControlledCamera;
  56623. }
  56624. if (!this._mesh.rotationQuaternion) {
  56625. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56626. }
  56627. };
  56628. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56629. this._poseControlledCamera = camera;
  56630. if (this._mesh) {
  56631. this._mesh.parent = this._poseControlledCamera;
  56632. }
  56633. };
  56634. PoseEnabledController.prototype.dispose = function () {
  56635. if (this._mesh) {
  56636. this._mesh.dispose();
  56637. }
  56638. this._mesh = null;
  56639. _super.prototype.dispose.call(this);
  56640. };
  56641. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56642. get: function () {
  56643. return this._mesh;
  56644. },
  56645. enumerable: true,
  56646. configurable: true
  56647. });
  56648. PoseEnabledController.prototype.getForwardRay = function (length) {
  56649. if (length === void 0) { length = 100; }
  56650. if (!this.mesh) {
  56651. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56652. }
  56653. var m = this.mesh.getWorldMatrix();
  56654. var origin = m.getTranslation();
  56655. var forward = new BABYLON.Vector3(0, 0, -1);
  56656. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56657. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56658. return new BABYLON.Ray(origin, direction, length);
  56659. };
  56660. return PoseEnabledController;
  56661. }(BABYLON.Gamepad));
  56662. BABYLON.PoseEnabledController = PoseEnabledController;
  56663. })(BABYLON || (BABYLON = {}));
  56664. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56665. var BABYLON;
  56666. (function (BABYLON) {
  56667. var WebVRController = /** @class */ (function (_super) {
  56668. __extends(WebVRController, _super);
  56669. function WebVRController(vrGamepad) {
  56670. var _this = _super.call(this, vrGamepad) || this;
  56671. // Observables
  56672. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56673. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56674. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56675. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56676. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56677. _this.pad = { x: 0, y: 0 };
  56678. // avoid GC, store state in a tmp object
  56679. _this._changes = {
  56680. pressChanged: false,
  56681. touchChanged: false,
  56682. valueChanged: false,
  56683. changed: false
  56684. };
  56685. _this._buttons = new Array(vrGamepad.buttons.length);
  56686. _this.hand = vrGamepad.hand;
  56687. return _this;
  56688. }
  56689. WebVRController.prototype.onButtonStateChange = function (callback) {
  56690. this._onButtonStateChange = callback;
  56691. };
  56692. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56693. get: function () {
  56694. return this._defaultModel;
  56695. },
  56696. enumerable: true,
  56697. configurable: true
  56698. });
  56699. WebVRController.prototype.update = function () {
  56700. _super.prototype.update.call(this);
  56701. for (var index = 0; index < this._buttons.length; index++) {
  56702. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56703. }
  56704. ;
  56705. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56706. this.pad.x = this.leftStick.x;
  56707. this.pad.y = this.leftStick.y;
  56708. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56709. }
  56710. };
  56711. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56712. if (!newState) {
  56713. newState = {
  56714. pressed: false,
  56715. touched: false,
  56716. value: 0
  56717. };
  56718. }
  56719. if (!currentState) {
  56720. this._buttons[buttonIndex] = {
  56721. pressed: newState.pressed,
  56722. touched: newState.touched,
  56723. value: newState.value
  56724. };
  56725. return;
  56726. }
  56727. this._checkChanges(newState, currentState);
  56728. if (this._changes.changed) {
  56729. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56730. this.handleButtonChange(buttonIndex, newState, this._changes);
  56731. }
  56732. this._buttons[buttonIndex].pressed = newState.pressed;
  56733. this._buttons[buttonIndex].touched = newState.touched;
  56734. // oculus triggers are never 0, thou not touched.
  56735. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56736. };
  56737. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56738. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56739. this._changes.touchChanged = newState.touched !== currentState.touched;
  56740. this._changes.valueChanged = newState.value !== currentState.value;
  56741. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56742. return this._changes;
  56743. };
  56744. WebVRController.prototype.dispose = function () {
  56745. _super.prototype.dispose.call(this);
  56746. this.onTriggerStateChangedObservable.clear();
  56747. this.onMainButtonStateChangedObservable.clear();
  56748. this.onSecondaryButtonStateChangedObservable.clear();
  56749. this.onPadStateChangedObservable.clear();
  56750. this.onPadValuesChangedObservable.clear();
  56751. };
  56752. return WebVRController;
  56753. }(BABYLON.PoseEnabledController));
  56754. BABYLON.WebVRController = WebVRController;
  56755. })(BABYLON || (BABYLON = {}));
  56756. //# sourceMappingURL=babylon.webVRController.js.map
  56757. var BABYLON;
  56758. (function (BABYLON) {
  56759. var OculusTouchController = /** @class */ (function (_super) {
  56760. __extends(OculusTouchController, _super);
  56761. function OculusTouchController(vrGamepad) {
  56762. var _this = _super.call(this, vrGamepad) || this;
  56763. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56764. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56765. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56766. return _this;
  56767. }
  56768. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56769. var _this = this;
  56770. var meshName;
  56771. // Hand
  56772. if (this.hand === 'left') {
  56773. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56774. }
  56775. else {
  56776. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56777. }
  56778. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56779. /*
  56780. Parent Mesh name: oculus_touch_left
  56781. - body
  56782. - trigger
  56783. - thumbstick
  56784. - grip
  56785. - button_y
  56786. - button_x
  56787. - button_enter
  56788. */
  56789. _this._defaultModel = newMeshes[1];
  56790. _this.attachToMesh(_this._defaultModel);
  56791. if (meshLoaded) {
  56792. meshLoaded(_this._defaultModel);
  56793. }
  56794. });
  56795. };
  56796. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56797. // helper getters for left and right hand.
  56798. get: function () {
  56799. if (this.hand === 'right') {
  56800. return this.onMainButtonStateChangedObservable;
  56801. }
  56802. else {
  56803. throw new Error('No A button on left hand');
  56804. }
  56805. },
  56806. enumerable: true,
  56807. configurable: true
  56808. });
  56809. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56810. get: function () {
  56811. if (this.hand === 'right') {
  56812. return this.onSecondaryButtonStateChangedObservable;
  56813. }
  56814. else {
  56815. throw new Error('No B button on left hand');
  56816. }
  56817. },
  56818. enumerable: true,
  56819. configurable: true
  56820. });
  56821. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56822. get: function () {
  56823. if (this.hand === 'left') {
  56824. return this.onMainButtonStateChangedObservable;
  56825. }
  56826. else {
  56827. throw new Error('No X button on right hand');
  56828. }
  56829. },
  56830. enumerable: true,
  56831. configurable: true
  56832. });
  56833. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56834. get: function () {
  56835. if (this.hand === 'left') {
  56836. return this.onSecondaryButtonStateChangedObservable;
  56837. }
  56838. else {
  56839. throw new Error('No Y button on right hand');
  56840. }
  56841. },
  56842. enumerable: true,
  56843. configurable: true
  56844. });
  56845. /*
  56846. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56847. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56848. 2) secondary trigger (same)
  56849. 3) A (right) X (left), touch, pressed = value
  56850. 4) B / Y
  56851. 5) thumb rest
  56852. */
  56853. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56854. var notifyObject = state; //{ state: state, changes: changes };
  56855. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56856. switch (buttonIdx) {
  56857. case 0:
  56858. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56859. return;
  56860. case 1:// index trigger
  56861. if (this._defaultModel) {
  56862. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56863. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56864. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56865. }
  56866. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56867. return;
  56868. case 2:// secondary trigger
  56869. if (this._defaultModel) {
  56870. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56871. }
  56872. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56873. return;
  56874. case 3:
  56875. if (this._defaultModel) {
  56876. if (notifyObject.pressed) {
  56877. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56878. }
  56879. else {
  56880. (this._defaultModel.getChildren()[1]).position.y = 0;
  56881. }
  56882. }
  56883. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56884. return;
  56885. case 4:
  56886. if (this._defaultModel) {
  56887. if (notifyObject.pressed) {
  56888. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56889. }
  56890. else {
  56891. (this._defaultModel.getChildren()[2]).position.y = 0;
  56892. }
  56893. }
  56894. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56895. return;
  56896. case 5:
  56897. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56898. return;
  56899. }
  56900. };
  56901. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56902. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56903. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56904. return OculusTouchController;
  56905. }(BABYLON.WebVRController));
  56906. BABYLON.OculusTouchController = OculusTouchController;
  56907. })(BABYLON || (BABYLON = {}));
  56908. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56909. var BABYLON;
  56910. (function (BABYLON) {
  56911. var ViveController = /** @class */ (function (_super) {
  56912. __extends(ViveController, _super);
  56913. function ViveController(vrGamepad) {
  56914. var _this = _super.call(this, vrGamepad) || this;
  56915. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56916. return _this;
  56917. }
  56918. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56919. var _this = this;
  56920. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56921. /*
  56922. Parent Mesh name: ViveWand
  56923. - body
  56924. - r_gripper
  56925. - l_gripper
  56926. - menu_button
  56927. - system_button
  56928. - trackpad
  56929. - trigger
  56930. - LED
  56931. */
  56932. _this._defaultModel = newMeshes[1];
  56933. _this.attachToMesh(_this._defaultModel);
  56934. if (meshLoaded) {
  56935. meshLoaded(_this._defaultModel);
  56936. }
  56937. });
  56938. };
  56939. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56940. get: function () {
  56941. return this.onMainButtonStateChangedObservable;
  56942. },
  56943. enumerable: true,
  56944. configurable: true
  56945. });
  56946. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56947. get: function () {
  56948. return this.onMainButtonStateChangedObservable;
  56949. },
  56950. enumerable: true,
  56951. configurable: true
  56952. });
  56953. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56954. get: function () {
  56955. return this.onSecondaryButtonStateChangedObservable;
  56956. },
  56957. enumerable: true,
  56958. configurable: true
  56959. });
  56960. /**
  56961. * Vive mapping:
  56962. * 0: touchpad
  56963. * 1: trigger
  56964. * 2: left AND right buttons
  56965. * 3: menu button
  56966. */
  56967. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56968. var notifyObject = state; //{ state: state, changes: changes };
  56969. switch (buttonIdx) {
  56970. case 0:
  56971. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56972. return;
  56973. case 1:// index trigger
  56974. if (this._defaultModel) {
  56975. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56976. }
  56977. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56978. return;
  56979. case 2:// left AND right button
  56980. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56981. return;
  56982. case 3:
  56983. if (this._defaultModel) {
  56984. if (notifyObject.pressed) {
  56985. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56986. }
  56987. else {
  56988. (this._defaultModel.getChildren()[2]).position.y = 0;
  56989. }
  56990. }
  56991. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56992. return;
  56993. }
  56994. };
  56995. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56996. ViveController.MODEL_FILENAME = 'wand.babylon';
  56997. return ViveController;
  56998. }(BABYLON.WebVRController));
  56999. BABYLON.ViveController = ViveController;
  57000. })(BABYLON || (BABYLON = {}));
  57001. //# sourceMappingURL=babylon.viveController.js.map
  57002. var BABYLON;
  57003. (function (BABYLON) {
  57004. var GenericController = /** @class */ (function (_super) {
  57005. __extends(GenericController, _super);
  57006. function GenericController(vrGamepad) {
  57007. return _super.call(this, vrGamepad) || this;
  57008. }
  57009. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57010. var _this = this;
  57011. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  57012. _this._defaultModel = newMeshes[1];
  57013. _this.attachToMesh(_this._defaultModel);
  57014. if (meshLoaded) {
  57015. meshLoaded(_this._defaultModel);
  57016. }
  57017. });
  57018. };
  57019. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57020. console.log("Button id: " + buttonIdx + "state: ");
  57021. console.dir(state);
  57022. };
  57023. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  57024. GenericController.MODEL_FILENAME = 'generic.babylon';
  57025. return GenericController;
  57026. }(BABYLON.WebVRController));
  57027. BABYLON.GenericController = GenericController;
  57028. })(BABYLON || (BABYLON = {}));
  57029. //# sourceMappingURL=babylon.genericController.js.map
  57030. var BABYLON;
  57031. (function (BABYLON) {
  57032. var LoadedMeshInfo = /** @class */ (function () {
  57033. function LoadedMeshInfo() {
  57034. this.buttonMeshes = {};
  57035. this.axisMeshes = {};
  57036. }
  57037. return LoadedMeshInfo;
  57038. }());
  57039. var WindowsMotionController = /** @class */ (function (_super) {
  57040. __extends(WindowsMotionController, _super);
  57041. function WindowsMotionController(vrGamepad) {
  57042. var _this = _super.call(this, vrGamepad) || this;
  57043. _this._mapping = {
  57044. // Semantic button names
  57045. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  57046. // A mapping of the button name to glTF model node name
  57047. // that should be transformed by button value.
  57048. buttonMeshNames: {
  57049. 'trigger': 'SELECT',
  57050. 'menu': 'MENU',
  57051. 'grip': 'GRASP',
  57052. 'thumbstick': 'THUMBSTICK_PRESS',
  57053. 'trackpad': 'TOUCHPAD_PRESS'
  57054. },
  57055. // This mapping is used to translate from the Motion Controller to Babylon semantics
  57056. buttonObservableNames: {
  57057. 'trigger': 'onTriggerStateChangedObservable',
  57058. 'menu': 'onSecondaryButtonStateChangedObservable',
  57059. 'grip': 'onMainButtonStateChangedObservable',
  57060. 'thumbstick': 'onPadStateChangedObservable',
  57061. 'trackpad': 'onTrackpadChangedObservable'
  57062. },
  57063. // A mapping of the axis name to glTF model node name
  57064. // that should be transformed by axis value.
  57065. // This array mirrors the browserGamepad.axes array, such that
  57066. // the mesh corresponding to axis 0 is in this array index 0.
  57067. axisMeshNames: [
  57068. 'THUMBSTICK_X',
  57069. 'THUMBSTICK_Y',
  57070. 'TOUCHPAD_TOUCH_X',
  57071. 'TOUCHPAD_TOUCH_Y'
  57072. ],
  57073. pointingPoseMeshName: 'POINTING_POSE'
  57074. };
  57075. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  57076. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  57077. _this._loadedMeshInfo = null;
  57078. return _this;
  57079. }
  57080. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  57081. get: function () {
  57082. return this.onTriggerStateChangedObservable;
  57083. },
  57084. enumerable: true,
  57085. configurable: true
  57086. });
  57087. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  57088. get: function () {
  57089. return this.onSecondaryButtonStateChangedObservable;
  57090. },
  57091. enumerable: true,
  57092. configurable: true
  57093. });
  57094. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  57095. get: function () {
  57096. return this.onMainButtonStateChangedObservable;
  57097. },
  57098. enumerable: true,
  57099. configurable: true
  57100. });
  57101. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  57102. get: function () {
  57103. return this.onPadStateChangedObservable;
  57104. },
  57105. enumerable: true,
  57106. configurable: true
  57107. });
  57108. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57109. get: function () {
  57110. return this.onTrackpadChangedObservable;
  57111. },
  57112. enumerable: true,
  57113. configurable: true
  57114. });
  57115. /**
  57116. * Called once per frame by the engine.
  57117. */
  57118. WindowsMotionController.prototype.update = function () {
  57119. _super.prototype.update.call(this);
  57120. // Only need to animate axes if there is a loaded mesh
  57121. if (this._loadedMeshInfo) {
  57122. if (this.browserGamepad.axes) {
  57123. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57124. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57125. }
  57126. }
  57127. }
  57128. };
  57129. /**
  57130. * Called once for each button that changed state since the last frame
  57131. * @param buttonIdx Which button index changed
  57132. * @param state New state of the button
  57133. * @param changes Which properties on the state changed since last frame
  57134. */
  57135. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57136. var buttonName = this._mapping.buttons[buttonIdx];
  57137. if (!buttonName) {
  57138. return;
  57139. }
  57140. // Only emit events for buttons that we know how to map from index to name
  57141. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57142. if (observable) {
  57143. observable.notifyObservers(state);
  57144. }
  57145. this.lerpButtonTransform(buttonName, state.value);
  57146. };
  57147. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57148. // If there is no loaded mesh, there is nothing to transform.
  57149. if (!this._loadedMeshInfo) {
  57150. return;
  57151. }
  57152. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57153. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57154. return;
  57155. }
  57156. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57157. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57158. };
  57159. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57160. if (!this._loadedMeshInfo) {
  57161. return;
  57162. }
  57163. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57164. if (!meshInfo) {
  57165. return;
  57166. }
  57167. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57168. return;
  57169. }
  57170. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57171. var lerpValue = axisValue * 0.5 + 0.5;
  57172. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57173. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57174. };
  57175. /**
  57176. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57177. * @param scene scene in which to add meshes
  57178. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57179. */
  57180. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57181. var _this = this;
  57182. if (forceDefault === void 0) { forceDefault = false; }
  57183. var path;
  57184. var filename;
  57185. // Checking if GLB loader is present
  57186. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  57187. // Determine the device specific folder based on the ID suffix
  57188. var device = 'default';
  57189. if (this.id && !forceDefault) {
  57190. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57191. device = ((match && match[0]) || device);
  57192. }
  57193. // Hand
  57194. if (this.hand === 'left') {
  57195. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57196. }
  57197. else {
  57198. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57199. }
  57200. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57201. }
  57202. else {
  57203. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57204. path = BABYLON.GenericController.MODEL_BASE_URL;
  57205. filename = BABYLON.GenericController.MODEL_FILENAME;
  57206. }
  57207. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57208. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57209. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57210. if (!_this._loadedMeshInfo) {
  57211. return;
  57212. }
  57213. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57214. _this.attachToMesh(_this._defaultModel);
  57215. if (meshLoaded) {
  57216. meshLoaded(_this._defaultModel);
  57217. }
  57218. }, null, function (scene, message) {
  57219. BABYLON.Tools.Log(message);
  57220. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57221. if (!forceDefault) {
  57222. _this.initControllerMesh(scene, meshLoaded, true);
  57223. }
  57224. });
  57225. };
  57226. /**
  57227. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57228. * can be transformed by button presses and axes values, based on this._mapping.
  57229. *
  57230. * @param scene scene in which the meshes exist
  57231. * @param meshes list of meshes that make up the controller model to process
  57232. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57233. */
  57234. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57235. var loadedMeshInfo = null;
  57236. // Create a new mesh to contain the glTF hierarchy
  57237. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57238. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57239. var childMesh = null;
  57240. for (var i = 0; i < meshes.length; i++) {
  57241. var mesh = meshes[i];
  57242. if (!mesh.parent) {
  57243. // Exclude controller meshes from picking results
  57244. mesh.isPickable = false;
  57245. // Handle root node, attach to the new parentMesh
  57246. childMesh = mesh;
  57247. break;
  57248. }
  57249. }
  57250. if (childMesh) {
  57251. childMesh.setParent(parentMesh);
  57252. // Create our mesh info. Note that this method will always return non-null.
  57253. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57254. }
  57255. else {
  57256. BABYLON.Tools.Warn('Could not find root node in model file.');
  57257. }
  57258. return loadedMeshInfo;
  57259. };
  57260. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57261. var loadedMeshInfo = new LoadedMeshInfo();
  57262. var i;
  57263. loadedMeshInfo.rootNode = rootNode;
  57264. // Reset the caches
  57265. loadedMeshInfo.buttonMeshes = {};
  57266. loadedMeshInfo.axisMeshes = {};
  57267. // Button Meshes
  57268. for (i = 0; i < this._mapping.buttons.length; i++) {
  57269. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57270. if (!buttonMeshName) {
  57271. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57272. continue;
  57273. }
  57274. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57275. if (!buttonMesh) {
  57276. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57277. continue;
  57278. }
  57279. var buttonMeshInfo = {
  57280. index: i,
  57281. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57282. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57283. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57284. };
  57285. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57286. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57287. }
  57288. else {
  57289. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57290. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57291. '(VALUE: ' + !!buttonMeshInfo.value +
  57292. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57293. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57294. ')');
  57295. }
  57296. }
  57297. // Axis Meshes
  57298. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57299. var axisMeshName = this._mapping.axisMeshNames[i];
  57300. if (!axisMeshName) {
  57301. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57302. continue;
  57303. }
  57304. var axisMesh = getChildByName(rootNode, axisMeshName);
  57305. if (!axisMesh) {
  57306. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57307. continue;
  57308. }
  57309. var axisMeshInfo = {
  57310. index: i,
  57311. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57312. min: getImmediateChildByName(axisMesh, 'MIN'),
  57313. max: getImmediateChildByName(axisMesh, 'MAX')
  57314. };
  57315. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57316. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57317. }
  57318. else {
  57319. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57320. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57321. '(VALUE: ' + !!axisMeshInfo.value +
  57322. ', MIN: ' + !!axisMeshInfo.min +
  57323. ', MAX:' + !!axisMeshInfo.max +
  57324. ')');
  57325. }
  57326. }
  57327. // Pointing Ray
  57328. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57329. if (!loadedMeshInfo.pointingPoseNode) {
  57330. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57331. }
  57332. return loadedMeshInfo;
  57333. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57334. function getChildByName(node, name) {
  57335. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57336. }
  57337. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57338. function getImmediateChildByName(node, name) {
  57339. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57340. }
  57341. };
  57342. WindowsMotionController.prototype.getForwardRay = function (length) {
  57343. if (length === void 0) { length = 100; }
  57344. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57345. return _super.prototype.getForwardRay.call(this, length);
  57346. }
  57347. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57348. var origin = m.getTranslation();
  57349. var forward = new BABYLON.Vector3(0, 0, -1);
  57350. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57351. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57352. return new BABYLON.Ray(origin, direction, length);
  57353. };
  57354. WindowsMotionController.prototype.dispose = function () {
  57355. _super.prototype.dispose.call(this);
  57356. this.onTrackpadChangedObservable.clear();
  57357. };
  57358. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57359. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57360. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57361. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57362. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57363. return WindowsMotionController;
  57364. }(BABYLON.WebVRController));
  57365. BABYLON.WindowsMotionController = WindowsMotionController;
  57366. })(BABYLON || (BABYLON = {}));
  57367. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57368. var BABYLON;
  57369. (function (BABYLON) {
  57370. var FollowCamera = /** @class */ (function (_super) {
  57371. __extends(FollowCamera, _super);
  57372. function FollowCamera(name, position, scene, lockedTarget) {
  57373. if (lockedTarget === void 0) { lockedTarget = null; }
  57374. var _this = _super.call(this, name, position, scene) || this;
  57375. _this.radius = 12;
  57376. _this.rotationOffset = 0;
  57377. _this.heightOffset = 4;
  57378. _this.cameraAcceleration = 0.05;
  57379. _this.maxCameraSpeed = 20;
  57380. _this.lockedTarget = lockedTarget;
  57381. return _this;
  57382. }
  57383. FollowCamera.prototype.getRadians = function (degrees) {
  57384. return degrees * Math.PI / 180;
  57385. };
  57386. FollowCamera.prototype.follow = function (cameraTarget) {
  57387. if (!cameraTarget)
  57388. return;
  57389. var yRotation;
  57390. if (cameraTarget.rotationQuaternion) {
  57391. var rotMatrix = new BABYLON.Matrix();
  57392. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57393. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57394. }
  57395. else {
  57396. yRotation = cameraTarget.rotation.y;
  57397. }
  57398. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57399. var targetPosition = cameraTarget.getAbsolutePosition();
  57400. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57401. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57402. var dx = targetX - this.position.x;
  57403. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57404. var dz = (targetZ) - this.position.z;
  57405. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57406. var vy = dy * this.cameraAcceleration;
  57407. var vz = dz * this.cameraAcceleration * 2;
  57408. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57409. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57410. }
  57411. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57412. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57413. }
  57414. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57415. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57416. }
  57417. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57418. this.setTarget(targetPosition);
  57419. };
  57420. FollowCamera.prototype._checkInputs = function () {
  57421. _super.prototype._checkInputs.call(this);
  57422. if (this.lockedTarget) {
  57423. this.follow(this.lockedTarget);
  57424. }
  57425. };
  57426. FollowCamera.prototype.getClassName = function () {
  57427. return "FollowCamera";
  57428. };
  57429. __decorate([
  57430. BABYLON.serialize()
  57431. ], FollowCamera.prototype, "radius", void 0);
  57432. __decorate([
  57433. BABYLON.serialize()
  57434. ], FollowCamera.prototype, "rotationOffset", void 0);
  57435. __decorate([
  57436. BABYLON.serialize()
  57437. ], FollowCamera.prototype, "heightOffset", void 0);
  57438. __decorate([
  57439. BABYLON.serialize()
  57440. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57441. __decorate([
  57442. BABYLON.serialize()
  57443. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57444. __decorate([
  57445. BABYLON.serializeAsMeshReference("lockedTargetId")
  57446. ], FollowCamera.prototype, "lockedTarget", void 0);
  57447. return FollowCamera;
  57448. }(BABYLON.TargetCamera));
  57449. BABYLON.FollowCamera = FollowCamera;
  57450. var ArcFollowCamera = /** @class */ (function (_super) {
  57451. __extends(ArcFollowCamera, _super);
  57452. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57453. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57454. _this.alpha = alpha;
  57455. _this.beta = beta;
  57456. _this.radius = radius;
  57457. _this.target = target;
  57458. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57459. _this.follow();
  57460. return _this;
  57461. }
  57462. ArcFollowCamera.prototype.follow = function () {
  57463. if (!this.target) {
  57464. return;
  57465. }
  57466. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57467. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57468. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57469. var targetPosition = this.target.getAbsolutePosition();
  57470. this.position = targetPosition.add(this._cartesianCoordinates);
  57471. this.setTarget(targetPosition);
  57472. };
  57473. ArcFollowCamera.prototype._checkInputs = function () {
  57474. _super.prototype._checkInputs.call(this);
  57475. this.follow();
  57476. };
  57477. ArcFollowCamera.prototype.getClassName = function () {
  57478. return "ArcFollowCamera";
  57479. };
  57480. return ArcFollowCamera;
  57481. }(BABYLON.TargetCamera));
  57482. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57483. })(BABYLON || (BABYLON = {}));
  57484. //# sourceMappingURL=babylon.followCamera.js.map
  57485. var BABYLON;
  57486. (function (BABYLON) {
  57487. // We're mainly based on the logic defined into the FreeCamera code
  57488. var UniversalCamera = /** @class */ (function (_super) {
  57489. __extends(UniversalCamera, _super);
  57490. //-- end properties for backward compatibility for inputs
  57491. function UniversalCamera(name, position, scene) {
  57492. var _this = _super.call(this, name, position, scene) || this;
  57493. _this.inputs.addGamepad();
  57494. return _this;
  57495. }
  57496. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57497. //-- Begin properties for backward compatibility for inputs
  57498. get: function () {
  57499. var gamepad = this.inputs.attached["gamepad"];
  57500. if (gamepad)
  57501. return gamepad.gamepadAngularSensibility;
  57502. return 0;
  57503. },
  57504. set: function (value) {
  57505. var gamepad = this.inputs.attached["gamepad"];
  57506. if (gamepad)
  57507. gamepad.gamepadAngularSensibility = value;
  57508. },
  57509. enumerable: true,
  57510. configurable: true
  57511. });
  57512. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57513. get: function () {
  57514. var gamepad = this.inputs.attached["gamepad"];
  57515. if (gamepad)
  57516. return gamepad.gamepadMoveSensibility;
  57517. return 0;
  57518. },
  57519. set: function (value) {
  57520. var gamepad = this.inputs.attached["gamepad"];
  57521. if (gamepad)
  57522. gamepad.gamepadMoveSensibility = value;
  57523. },
  57524. enumerable: true,
  57525. configurable: true
  57526. });
  57527. UniversalCamera.prototype.getClassName = function () {
  57528. return "UniversalCamera";
  57529. };
  57530. return UniversalCamera;
  57531. }(BABYLON.TouchCamera));
  57532. BABYLON.UniversalCamera = UniversalCamera;
  57533. })(BABYLON || (BABYLON = {}));
  57534. //# sourceMappingURL=babylon.universalCamera.js.map
  57535. var BABYLON;
  57536. (function (BABYLON) {
  57537. // We're mainly based on the logic defined into the FreeCamera code
  57538. var GamepadCamera = /** @class */ (function (_super) {
  57539. __extends(GamepadCamera, _super);
  57540. //-- end properties for backward compatibility for inputs
  57541. function GamepadCamera(name, position, scene) {
  57542. return _super.call(this, name, position, scene) || this;
  57543. }
  57544. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57545. //-- Begin properties for backward compatibility for inputs
  57546. get: function () {
  57547. var gamepad = this.inputs.attached["gamepad"];
  57548. if (gamepad)
  57549. return gamepad.gamepadAngularSensibility;
  57550. return 0;
  57551. },
  57552. set: function (value) {
  57553. var gamepad = this.inputs.attached["gamepad"];
  57554. if (gamepad)
  57555. gamepad.gamepadAngularSensibility = value;
  57556. },
  57557. enumerable: true,
  57558. configurable: true
  57559. });
  57560. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57561. get: function () {
  57562. var gamepad = this.inputs.attached["gamepad"];
  57563. if (gamepad)
  57564. return gamepad.gamepadMoveSensibility;
  57565. return 0;
  57566. },
  57567. set: function (value) {
  57568. var gamepad = this.inputs.attached["gamepad"];
  57569. if (gamepad)
  57570. gamepad.gamepadMoveSensibility = value;
  57571. },
  57572. enumerable: true,
  57573. configurable: true
  57574. });
  57575. GamepadCamera.prototype.getClassName = function () {
  57576. return "GamepadCamera";
  57577. };
  57578. return GamepadCamera;
  57579. }(BABYLON.UniversalCamera));
  57580. BABYLON.GamepadCamera = GamepadCamera;
  57581. })(BABYLON || (BABYLON = {}));
  57582. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57583. var BABYLON;
  57584. (function (BABYLON) {
  57585. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57586. function PostProcessRenderPipelineManager() {
  57587. this._renderPipelines = {};
  57588. }
  57589. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57590. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57591. };
  57592. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57593. if (unique === void 0) { unique = false; }
  57594. var renderPipeline = this._renderPipelines[renderPipelineName];
  57595. if (!renderPipeline) {
  57596. return;
  57597. }
  57598. renderPipeline._attachCameras(cameras, unique);
  57599. };
  57600. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57601. var renderPipeline = this._renderPipelines[renderPipelineName];
  57602. if (!renderPipeline) {
  57603. return;
  57604. }
  57605. renderPipeline._detachCameras(cameras);
  57606. };
  57607. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57608. var renderPipeline = this._renderPipelines[renderPipelineName];
  57609. if (!renderPipeline) {
  57610. return;
  57611. }
  57612. renderPipeline._enableEffect(renderEffectName, cameras);
  57613. };
  57614. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57615. var renderPipeline = this._renderPipelines[renderPipelineName];
  57616. if (!renderPipeline) {
  57617. return;
  57618. }
  57619. renderPipeline._disableEffect(renderEffectName, cameras);
  57620. };
  57621. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57622. var renderPipeline = this._renderPipelines[renderPipelineName];
  57623. if (!renderPipeline) {
  57624. return;
  57625. }
  57626. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57627. };
  57628. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57629. var renderPipeline = this._renderPipelines[renderPipelineName];
  57630. if (!renderPipeline) {
  57631. return;
  57632. }
  57633. renderPipeline._disableDisplayOnlyPass(cameras);
  57634. };
  57635. PostProcessRenderPipelineManager.prototype.update = function () {
  57636. for (var renderPipelineName in this._renderPipelines) {
  57637. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57638. var pipeline = this._renderPipelines[renderPipelineName];
  57639. if (!pipeline.isSupported) {
  57640. pipeline.dispose();
  57641. delete this._renderPipelines[renderPipelineName];
  57642. }
  57643. else {
  57644. pipeline._update();
  57645. }
  57646. }
  57647. }
  57648. };
  57649. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57650. for (var renderPipelineName in this._renderPipelines) {
  57651. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57652. var pipeline = this._renderPipelines[renderPipelineName];
  57653. pipeline._rebuild();
  57654. }
  57655. }
  57656. };
  57657. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57658. for (var renderPipelineName in this._renderPipelines) {
  57659. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57660. var pipeline = this._renderPipelines[renderPipelineName];
  57661. pipeline.dispose();
  57662. }
  57663. }
  57664. };
  57665. return PostProcessRenderPipelineManager;
  57666. }());
  57667. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57668. })(BABYLON || (BABYLON = {}));
  57669. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57670. var BABYLON;
  57671. (function (BABYLON) {
  57672. var PostProcessRenderPass = /** @class */ (function () {
  57673. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57674. this._refCount = 0;
  57675. this._name = name;
  57676. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57677. this.setRenderList(renderList);
  57678. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57679. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57680. this._scene = scene;
  57681. this._renderList = renderList;
  57682. }
  57683. // private
  57684. PostProcessRenderPass.prototype._incRefCount = function () {
  57685. if (this._refCount === 0) {
  57686. this._scene.customRenderTargets.push(this._renderTexture);
  57687. }
  57688. return ++this._refCount;
  57689. };
  57690. PostProcessRenderPass.prototype._decRefCount = function () {
  57691. this._refCount--;
  57692. if (this._refCount <= 0) {
  57693. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57694. }
  57695. return this._refCount;
  57696. };
  57697. PostProcessRenderPass.prototype._update = function () {
  57698. this.setRenderList(this._renderList);
  57699. };
  57700. // public
  57701. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57702. this._renderTexture.renderList = renderList;
  57703. };
  57704. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57705. return this._renderTexture;
  57706. };
  57707. return PostProcessRenderPass;
  57708. }());
  57709. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57710. })(BABYLON || (BABYLON = {}));
  57711. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57712. var BABYLON;
  57713. (function (BABYLON) {
  57714. var PostProcessRenderEffect = /** @class */ (function () {
  57715. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57716. this._name = name;
  57717. this._singleInstance = singleInstance || true;
  57718. this._getPostProcess = getPostProcess;
  57719. this._cameras = {};
  57720. this._indicesForCamera = {};
  57721. this._postProcesses = {};
  57722. this._renderPasses = {};
  57723. this._renderEffectAsPasses = {};
  57724. }
  57725. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57726. get: function () {
  57727. for (var index in this._postProcesses) {
  57728. if (!this._postProcesses[index].isSupported) {
  57729. return false;
  57730. }
  57731. }
  57732. return true;
  57733. },
  57734. enumerable: true,
  57735. configurable: true
  57736. });
  57737. PostProcessRenderEffect.prototype._update = function () {
  57738. for (var renderPassName in this._renderPasses) {
  57739. this._renderPasses[renderPassName]._update();
  57740. }
  57741. };
  57742. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57743. this._renderPasses[renderPass._name] = renderPass;
  57744. this._linkParameters();
  57745. };
  57746. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57747. delete this._renderPasses[renderPass._name];
  57748. this._linkParameters();
  57749. };
  57750. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57751. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57752. this._linkParameters();
  57753. };
  57754. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57755. for (var renderPassName in this._renderPasses) {
  57756. if (renderPassName === passName) {
  57757. return this._renderPasses[passName];
  57758. }
  57759. }
  57760. return null;
  57761. };
  57762. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57763. this._renderPasses = {};
  57764. this._linkParameters();
  57765. };
  57766. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57767. var cameraKey;
  57768. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57769. if (!cams) {
  57770. return;
  57771. }
  57772. for (var i = 0; i < cams.length; i++) {
  57773. var camera = cams[i];
  57774. var cameraName = camera.name;
  57775. if (this._singleInstance) {
  57776. cameraKey = 0;
  57777. }
  57778. else {
  57779. cameraKey = cameraName;
  57780. }
  57781. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57782. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57783. if (!this._indicesForCamera[cameraName]) {
  57784. this._indicesForCamera[cameraName] = [];
  57785. }
  57786. this._indicesForCamera[cameraName].push(index);
  57787. if (!this._cameras[cameraName]) {
  57788. this._cameras[cameraName] = camera;
  57789. }
  57790. for (var passName in this._renderPasses) {
  57791. this._renderPasses[passName]._incRefCount();
  57792. }
  57793. }
  57794. this._linkParameters();
  57795. };
  57796. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57797. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57798. if (!cams) {
  57799. return;
  57800. }
  57801. for (var i = 0; i < cams.length; i++) {
  57802. var camera = cams[i];
  57803. var cameraName = camera.name;
  57804. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57805. if (this._cameras[cameraName]) {
  57806. //this._indicesForCamera.splice(index, 1);
  57807. this._cameras[cameraName] = null;
  57808. }
  57809. for (var passName in this._renderPasses) {
  57810. this._renderPasses[passName]._decRefCount();
  57811. }
  57812. }
  57813. };
  57814. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57815. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57816. if (!cams) {
  57817. return;
  57818. }
  57819. for (var i = 0; i < cams.length; i++) {
  57820. var camera = cams[i];
  57821. var cameraName = camera.name;
  57822. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57823. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57824. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57825. }
  57826. }
  57827. for (var passName in this._renderPasses) {
  57828. this._renderPasses[passName]._incRefCount();
  57829. }
  57830. }
  57831. };
  57832. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57833. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57834. if (!cams) {
  57835. return;
  57836. }
  57837. for (var i = 0; i < cams.length; i++) {
  57838. var camera = cams[i];
  57839. var cameraName = camera.Name;
  57840. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57841. for (var passName in this._renderPasses) {
  57842. this._renderPasses[passName]._decRefCount();
  57843. }
  57844. }
  57845. };
  57846. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57847. if (this._singleInstance) {
  57848. return this._postProcesses[0];
  57849. }
  57850. else {
  57851. if (!camera) {
  57852. return null;
  57853. }
  57854. return this._postProcesses[camera.name];
  57855. }
  57856. };
  57857. PostProcessRenderEffect.prototype._linkParameters = function () {
  57858. var _this = this;
  57859. for (var index in this._postProcesses) {
  57860. if (this.applyParameters) {
  57861. this.applyParameters(this._postProcesses[index]);
  57862. }
  57863. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57864. _this._linkTextures(effect);
  57865. });
  57866. }
  57867. };
  57868. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57869. for (var renderPassName in this._renderPasses) {
  57870. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57871. }
  57872. for (var renderEffectName in this._renderEffectAsPasses) {
  57873. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57874. }
  57875. };
  57876. return PostProcessRenderEffect;
  57877. }());
  57878. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57879. })(BABYLON || (BABYLON = {}));
  57880. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57881. var BABYLON;
  57882. (function (BABYLON) {
  57883. var PostProcessRenderPipeline = /** @class */ (function () {
  57884. function PostProcessRenderPipeline(engine, name) {
  57885. this._engine = engine;
  57886. this._name = name;
  57887. this._renderEffects = {};
  57888. this._renderEffectsForIsolatedPass = new Array();
  57889. this._cameras = [];
  57890. }
  57891. PostProcessRenderPipeline.prototype.getClassName = function () {
  57892. return "PostProcessRenderPipeline";
  57893. };
  57894. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57895. get: function () {
  57896. for (var renderEffectName in this._renderEffects) {
  57897. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57898. if (!this._renderEffects[renderEffectName].isSupported) {
  57899. return false;
  57900. }
  57901. }
  57902. }
  57903. return true;
  57904. },
  57905. enumerable: true,
  57906. configurable: true
  57907. });
  57908. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57909. this._renderEffects[renderEffect._name] = renderEffect;
  57910. };
  57911. // private
  57912. PostProcessRenderPipeline.prototype._rebuild = function () {
  57913. };
  57914. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57915. var renderEffects = this._renderEffects[renderEffectName];
  57916. if (!renderEffects) {
  57917. return;
  57918. }
  57919. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57920. };
  57921. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57922. var renderEffects = this._renderEffects[renderEffectName];
  57923. if (!renderEffects) {
  57924. return;
  57925. }
  57926. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57927. };
  57928. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57929. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57930. if (!cams) {
  57931. return;
  57932. }
  57933. var indicesToDelete = [];
  57934. var i;
  57935. for (i = 0; i < cams.length; i++) {
  57936. var camera = cams[i];
  57937. var cameraName = camera.name;
  57938. if (this._cameras.indexOf(camera) === -1) {
  57939. this._cameras[cameraName] = camera;
  57940. }
  57941. else if (unique) {
  57942. indicesToDelete.push(i);
  57943. }
  57944. }
  57945. for (i = 0; i < indicesToDelete.length; i++) {
  57946. cameras.splice(indicesToDelete[i], 1);
  57947. }
  57948. for (var renderEffectName in this._renderEffects) {
  57949. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57950. this._renderEffects[renderEffectName]._attachCameras(cams);
  57951. }
  57952. }
  57953. };
  57954. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57955. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57956. if (!cams) {
  57957. return;
  57958. }
  57959. for (var renderEffectName in this._renderEffects) {
  57960. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57961. this._renderEffects[renderEffectName]._detachCameras(cams);
  57962. }
  57963. }
  57964. for (var i = 0; i < cams.length; i++) {
  57965. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57966. }
  57967. };
  57968. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57969. var _this = this;
  57970. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57971. if (!cams) {
  57972. return;
  57973. }
  57974. var pass = null;
  57975. var renderEffectName;
  57976. for (renderEffectName in this._renderEffects) {
  57977. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57978. pass = this._renderEffects[renderEffectName].getPass(passName);
  57979. if (pass != null) {
  57980. break;
  57981. }
  57982. }
  57983. }
  57984. if (pass === null) {
  57985. return;
  57986. }
  57987. for (renderEffectName in this._renderEffects) {
  57988. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57989. this._renderEffects[renderEffectName]._disable(cams);
  57990. }
  57991. }
  57992. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57993. for (var i = 0; i < cams.length; i++) {
  57994. var camera = cams[i];
  57995. var cameraName = camera.name;
  57996. 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); });
  57997. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57998. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57999. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  58000. }
  58001. };
  58002. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  58003. var _this = this;
  58004. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58005. if (!cams) {
  58006. return;
  58007. }
  58008. for (var i = 0; i < cams.length; i++) {
  58009. var camera = cams[i];
  58010. var cameraName = camera.name;
  58011. 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); });
  58012. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  58013. }
  58014. for (var renderEffectName in this._renderEffects) {
  58015. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58016. this._renderEffects[renderEffectName]._enable(cams);
  58017. }
  58018. }
  58019. };
  58020. PostProcessRenderPipeline.prototype._update = function () {
  58021. for (var renderEffectName in this._renderEffects) {
  58022. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58023. this._renderEffects[renderEffectName]._update();
  58024. }
  58025. }
  58026. for (var i = 0; i < this._cameras.length; i++) {
  58027. var cameraName = this._cameras[i].name;
  58028. if (this._renderEffectsForIsolatedPass[cameraName]) {
  58029. this._renderEffectsForIsolatedPass[cameraName]._update();
  58030. }
  58031. }
  58032. };
  58033. PostProcessRenderPipeline.prototype._reset = function () {
  58034. this._renderEffects = {};
  58035. this._renderEffectsForIsolatedPass = new Array();
  58036. };
  58037. PostProcessRenderPipeline.prototype.dispose = function () {
  58038. // Must be implemented by children
  58039. };
  58040. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  58041. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  58042. __decorate([
  58043. BABYLON.serialize()
  58044. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  58045. return PostProcessRenderPipeline;
  58046. }());
  58047. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  58048. })(BABYLON || (BABYLON = {}));
  58049. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  58050. var BABYLON;
  58051. (function (BABYLON) {
  58052. var DepthRenderer = /** @class */ (function () {
  58053. function DepthRenderer(scene, type) {
  58054. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  58055. var _this = this;
  58056. this._scene = scene;
  58057. var engine = scene.getEngine();
  58058. // Render target
  58059. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  58060. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58061. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58062. this._depthMap.refreshRate = 1;
  58063. this._depthMap.renderParticles = false;
  58064. this._depthMap.renderList = null;
  58065. // set default depth value to 1.0 (far away)
  58066. this._depthMap.onClearObservable.add(function (engine) {
  58067. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58068. });
  58069. // Custom render function
  58070. var renderSubMesh = function (subMesh) {
  58071. var mesh = subMesh.getRenderingMesh();
  58072. var scene = _this._scene;
  58073. var engine = scene.getEngine();
  58074. var material = subMesh.getMaterial();
  58075. if (!material) {
  58076. return;
  58077. }
  58078. // Culling and reverse (right handed system)
  58079. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  58080. // Managing instances
  58081. var batch = mesh._getInstancesRenderList(subMesh._id);
  58082. if (batch.mustReturn) {
  58083. return;
  58084. }
  58085. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58086. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  58087. engine.enableEffect(_this._effect);
  58088. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58089. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58090. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  58091. // Alpha test
  58092. if (material && material.needAlphaTesting()) {
  58093. var alphaTexture = material.getAlphaTestTexture();
  58094. if (alphaTexture) {
  58095. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58096. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58097. }
  58098. }
  58099. // Bones
  58100. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58101. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58102. }
  58103. // Draw
  58104. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58105. }
  58106. };
  58107. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58108. var index;
  58109. if (depthOnlySubMeshes.length) {
  58110. engine.setColorWrite(false);
  58111. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58112. renderSubMesh(depthOnlySubMeshes.data[index]);
  58113. }
  58114. engine.setColorWrite(true);
  58115. }
  58116. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58117. renderSubMesh(opaqueSubMeshes.data[index]);
  58118. }
  58119. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58120. renderSubMesh(alphaTestSubMeshes.data[index]);
  58121. }
  58122. };
  58123. }
  58124. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58125. var material = subMesh.getMaterial();
  58126. if (material.disableDepthWrite) {
  58127. return false;
  58128. }
  58129. var defines = [];
  58130. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58131. var mesh = subMesh.getMesh();
  58132. // Alpha test
  58133. if (material && material.needAlphaTesting()) {
  58134. defines.push("#define ALPHATEST");
  58135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58136. attribs.push(BABYLON.VertexBuffer.UVKind);
  58137. defines.push("#define UV1");
  58138. }
  58139. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58140. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58141. defines.push("#define UV2");
  58142. }
  58143. }
  58144. // Bones
  58145. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58148. if (mesh.numBoneInfluencers > 4) {
  58149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58151. }
  58152. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58153. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58154. }
  58155. else {
  58156. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58157. }
  58158. // Instances
  58159. if (useInstances) {
  58160. defines.push("#define INSTANCES");
  58161. attribs.push("world0");
  58162. attribs.push("world1");
  58163. attribs.push("world2");
  58164. attribs.push("world3");
  58165. }
  58166. // Get correct effect
  58167. var join = defines.join("\n");
  58168. if (this._cachedDefines !== join) {
  58169. this._cachedDefines = join;
  58170. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58171. }
  58172. return this._effect.isReady();
  58173. };
  58174. DepthRenderer.prototype.getDepthMap = function () {
  58175. return this._depthMap;
  58176. };
  58177. // Methods
  58178. DepthRenderer.prototype.dispose = function () {
  58179. this._depthMap.dispose();
  58180. };
  58181. return DepthRenderer;
  58182. }());
  58183. BABYLON.DepthRenderer = DepthRenderer;
  58184. })(BABYLON || (BABYLON = {}));
  58185. //# sourceMappingURL=babylon.depthRenderer.js.map
  58186. var BABYLON;
  58187. (function (BABYLON) {
  58188. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58189. __extends(SSAORenderingPipeline, _super);
  58190. /**
  58191. * @constructor
  58192. * @param {string} name - The rendering pipeline name
  58193. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58194. * @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 }
  58195. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58196. */
  58197. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58198. var _this = _super.call(this, scene.getEngine(), name) || this;
  58199. // Members
  58200. /**
  58201. * The PassPostProcess id in the pipeline that contains the original scene color
  58202. * @type {string}
  58203. */
  58204. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58205. /**
  58206. * The SSAO PostProcess id in the pipeline
  58207. * @type {string}
  58208. */
  58209. _this.SSAORenderEffect = "SSAORenderEffect";
  58210. /**
  58211. * The horizontal blur PostProcess id in the pipeline
  58212. * @type {string}
  58213. */
  58214. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58215. /**
  58216. * The vertical blur PostProcess id in the pipeline
  58217. * @type {string}
  58218. */
  58219. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58220. /**
  58221. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58222. * @type {string}
  58223. */
  58224. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58225. /**
  58226. * The output strength of the SSAO post-process. Default value is 1.0.
  58227. * @type {number}
  58228. */
  58229. _this.totalStrength = 1.0;
  58230. /**
  58231. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58232. * @type {number}
  58233. */
  58234. _this.radius = 0.0001;
  58235. /**
  58236. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58237. * Must not be equal to fallOff and superior to fallOff.
  58238. * Default value is 0.975
  58239. * @type {number}
  58240. */
  58241. _this.area = 0.0075;
  58242. /**
  58243. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58244. * Must not be equal to area and inferior to area.
  58245. * Default value is 0.0
  58246. * @type {number}
  58247. */
  58248. _this.fallOff = 0.000001;
  58249. /**
  58250. * The base color of the SSAO post-process
  58251. * The final result is "base + ssao" between [0, 1]
  58252. * @type {number}
  58253. */
  58254. _this.base = 0.5;
  58255. _this._firstUpdate = true;
  58256. _this._scene = scene;
  58257. // Set up assets
  58258. _this._createRandomTexture();
  58259. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58260. var ssaoRatio = ratio.ssaoRatio || ratio;
  58261. var combineRatio = ratio.combineRatio || ratio;
  58262. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58263. _this._createSSAOPostProcess(ssaoRatio);
  58264. _this._createBlurPostProcess(ssaoRatio);
  58265. _this._createSSAOCombinePostProcess(combineRatio);
  58266. // Set up pipeline
  58267. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58269. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58270. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58271. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58272. // Finish
  58273. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58274. if (cameras)
  58275. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58276. return _this;
  58277. }
  58278. // Public Methods
  58279. /**
  58280. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58281. */
  58282. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58283. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58284. for (var i = 0; i < this._scene.cameras.length; i++) {
  58285. var camera = this._scene.cameras[i];
  58286. this._originalColorPostProcess.dispose(camera);
  58287. this._ssaoPostProcess.dispose(camera);
  58288. this._blurHPostProcess.dispose(camera);
  58289. this._blurVPostProcess.dispose(camera);
  58290. this._ssaoCombinePostProcess.dispose(camera);
  58291. }
  58292. this._randomTexture.dispose();
  58293. if (disableDepthRender)
  58294. this._scene.disableDepthRenderer();
  58295. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58296. _super.prototype.dispose.call(this);
  58297. };
  58298. // Private Methods
  58299. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58300. var _this = this;
  58301. var size = 16;
  58302. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58303. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58304. this._blurHPostProcess.onActivateObservable.add(function () {
  58305. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58306. _this._blurHPostProcess.kernel = size * dw;
  58307. });
  58308. this._blurVPostProcess.onActivateObservable.add(function () {
  58309. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58310. _this._blurVPostProcess.kernel = size * dw;
  58311. });
  58312. };
  58313. SSAORenderingPipeline.prototype._rebuild = function () {
  58314. this._firstUpdate = true;
  58315. _super.prototype._rebuild.call(this);
  58316. };
  58317. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58318. var _this = this;
  58319. var numSamples = 16;
  58320. var sampleSphere = [
  58321. 0.5381, 0.1856, -0.4319,
  58322. 0.1379, 0.2486, 0.4430,
  58323. 0.3371, 0.5679, -0.0057,
  58324. -0.6999, -0.0451, -0.0019,
  58325. 0.0689, -0.1598, -0.8547,
  58326. 0.0560, 0.0069, -0.1843,
  58327. -0.0146, 0.1402, 0.0762,
  58328. 0.0100, -0.1924, -0.0344,
  58329. -0.3577, -0.5301, -0.4358,
  58330. -0.3169, 0.1063, 0.0158,
  58331. 0.0103, -0.5869, 0.0046,
  58332. -0.0897, -0.4940, 0.3287,
  58333. 0.7119, -0.0154, -0.0918,
  58334. -0.0533, 0.0596, -0.5411,
  58335. 0.0352, -0.0631, 0.5460,
  58336. -0.4776, 0.2847, -0.0271
  58337. ];
  58338. var samplesFactor = 1.0 / numSamples;
  58339. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58340. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58341. "area", "fallOff", "base", "range", "viewport"
  58342. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58343. this._ssaoPostProcess.onApply = function (effect) {
  58344. if (_this._firstUpdate) {
  58345. effect.setArray3("sampleSphere", sampleSphere);
  58346. effect.setFloat("samplesFactor", samplesFactor);
  58347. effect.setFloat("randTextureTiles", 4.0);
  58348. }
  58349. effect.setFloat("totalStrength", _this.totalStrength);
  58350. effect.setFloat("radius", _this.radius);
  58351. effect.setFloat("area", _this.area);
  58352. effect.setFloat("fallOff", _this.fallOff);
  58353. effect.setFloat("base", _this.base);
  58354. effect.setTexture("textureSampler", _this._depthTexture);
  58355. effect.setTexture("randomSampler", _this._randomTexture);
  58356. };
  58357. };
  58358. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58359. var _this = this;
  58360. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58361. this._ssaoCombinePostProcess.onApply = function (effect) {
  58362. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58363. };
  58364. };
  58365. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58366. var size = 512;
  58367. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58368. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58369. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58370. var context = this._randomTexture.getContext();
  58371. var rand = function (min, max) {
  58372. return Math.random() * (max - min) + min;
  58373. };
  58374. var randVector = BABYLON.Vector3.Zero();
  58375. for (var x = 0; x < size; x++) {
  58376. for (var y = 0; y < size; y++) {
  58377. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58378. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58379. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58380. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58381. context.fillRect(x, y, 1, 1);
  58382. }
  58383. }
  58384. this._randomTexture.update(false);
  58385. };
  58386. __decorate([
  58387. BABYLON.serialize()
  58388. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58389. __decorate([
  58390. BABYLON.serialize()
  58391. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58392. __decorate([
  58393. BABYLON.serialize()
  58394. ], SSAORenderingPipeline.prototype, "area", void 0);
  58395. __decorate([
  58396. BABYLON.serialize()
  58397. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58398. __decorate([
  58399. BABYLON.serialize()
  58400. ], SSAORenderingPipeline.prototype, "base", void 0);
  58401. return SSAORenderingPipeline;
  58402. }(BABYLON.PostProcessRenderPipeline));
  58403. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58404. })(BABYLON || (BABYLON = {}));
  58405. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58406. var BABYLON;
  58407. (function (BABYLON) {
  58408. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58409. __extends(SSAO2RenderingPipeline, _super);
  58410. /**
  58411. * @constructor
  58412. * @param {string} name - The rendering pipeline name
  58413. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58414. * @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 }
  58415. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58416. */
  58417. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58418. var _this = _super.call(this, scene.getEngine(), name) || this;
  58419. // Members
  58420. /**
  58421. * The PassPostProcess id in the pipeline that contains the original scene color
  58422. * @type {string}
  58423. */
  58424. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58425. /**
  58426. * The SSAO PostProcess id in the pipeline
  58427. * @type {string}
  58428. */
  58429. _this.SSAORenderEffect = "SSAORenderEffect";
  58430. /**
  58431. * The horizontal blur PostProcess id in the pipeline
  58432. * @type {string}
  58433. */
  58434. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58435. /**
  58436. * The vertical blur PostProcess id in the pipeline
  58437. * @type {string}
  58438. */
  58439. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58440. /**
  58441. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58442. * @type {string}
  58443. */
  58444. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58445. /**
  58446. * The output strength of the SSAO post-process. Default value is 1.0.
  58447. * @type {number}
  58448. */
  58449. _this.totalStrength = 1.0;
  58450. /**
  58451. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58452. * @type {number}
  58453. */
  58454. _this.maxZ = 100.0;
  58455. /**
  58456. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58457. * @type {number}
  58458. */
  58459. _this.minZAspect = 0.2;
  58460. /**
  58461. * Number of samples used for the SSAO calculations. Default value is 8
  58462. * @type {number}
  58463. */
  58464. _this._samples = 8;
  58465. /**
  58466. * Are we using bilateral blur ?
  58467. * @type {boolean}
  58468. */
  58469. _this._expensiveBlur = true;
  58470. /**
  58471. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58472. * @type {number}
  58473. */
  58474. _this.radius = 2.0;
  58475. /**
  58476. * The base color of the SSAO post-process
  58477. * The final result is "base + ssao" between [0, 1]
  58478. * @type {number}
  58479. */
  58480. _this.base = 0.1;
  58481. _this._firstUpdate = true;
  58482. _this._scene = scene;
  58483. if (!_this.isSupported) {
  58484. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58485. return _this;
  58486. }
  58487. var ssaoRatio = ratio.ssaoRatio || ratio;
  58488. var blurRatio = ratio.blurRatio || ratio;
  58489. // Set up assets
  58490. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58491. _this._createRandomTexture();
  58492. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58493. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58494. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58495. _this._createSSAOPostProcess(1.0);
  58496. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58497. _this._createSSAOCombinePostProcess(blurRatio);
  58498. // Set up pipeline
  58499. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58500. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58501. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58502. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58503. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58504. // Finish
  58505. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58506. if (cameras)
  58507. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58508. return _this;
  58509. }
  58510. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58511. get: function () {
  58512. return this._samples;
  58513. },
  58514. set: function (n) {
  58515. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58516. this._samples = n;
  58517. this._sampleSphere = this._generateHemisphere();
  58518. this._firstUpdate = true;
  58519. },
  58520. enumerable: true,
  58521. configurable: true
  58522. });
  58523. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58524. get: function () {
  58525. return this._expensiveBlur;
  58526. },
  58527. set: function (b) {
  58528. 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"]);
  58529. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58530. this._expensiveBlur = b;
  58531. this._firstUpdate = true;
  58532. },
  58533. enumerable: true,
  58534. configurable: true
  58535. });
  58536. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58537. /**
  58538. * Support test.
  58539. * @type {boolean}
  58540. */
  58541. get: function () {
  58542. var engine = BABYLON.Engine.LastCreatedEngine;
  58543. if (!engine) {
  58544. return false;
  58545. }
  58546. return engine.getCaps().drawBuffersExtension;
  58547. },
  58548. enumerable: true,
  58549. configurable: true
  58550. });
  58551. // Public Methods
  58552. /**
  58553. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58554. */
  58555. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58556. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58557. for (var i = 0; i < this._scene.cameras.length; i++) {
  58558. var camera = this._scene.cameras[i];
  58559. this._originalColorPostProcess.dispose(camera);
  58560. this._ssaoPostProcess.dispose(camera);
  58561. this._blurHPostProcess.dispose(camera);
  58562. this._blurVPostProcess.dispose(camera);
  58563. this._ssaoCombinePostProcess.dispose(camera);
  58564. }
  58565. this._randomTexture.dispose();
  58566. if (disableGeometryBufferRenderer)
  58567. this._scene.disableGeometryBufferRenderer();
  58568. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58569. _super.prototype.dispose.call(this);
  58570. };
  58571. // Private Methods
  58572. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58573. var _this = this;
  58574. this._samplerOffsets = [];
  58575. var expensive = this.expensiveBlur;
  58576. for (var i = -8; i < 8; i++) {
  58577. this._samplerOffsets.push(i * 2 + 0.5);
  58578. }
  58579. 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");
  58580. this._blurHPostProcess.onApply = function (effect) {
  58581. if (!_this._scene.activeCamera) {
  58582. return;
  58583. }
  58584. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58585. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58586. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58587. effect.setFloat("radius", _this.radius);
  58588. effect.setTexture("depthSampler", _this._depthTexture);
  58589. if (_this._firstUpdate) {
  58590. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58591. }
  58592. };
  58593. 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");
  58594. this._blurVPostProcess.onApply = function (effect) {
  58595. if (!_this._scene.activeCamera) {
  58596. return;
  58597. }
  58598. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58599. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58600. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58601. effect.setFloat("radius", _this.radius);
  58602. effect.setTexture("depthSampler", _this._depthTexture);
  58603. if (_this._firstUpdate) {
  58604. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58605. _this._firstUpdate = false;
  58606. }
  58607. };
  58608. };
  58609. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58610. this._firstUpdate = true;
  58611. _super.prototype._rebuild.call(this);
  58612. };
  58613. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58614. var numSamples = this.samples;
  58615. var result = [];
  58616. var vector, scale;
  58617. var rand = function (min, max) {
  58618. return Math.random() * (max - min) + min;
  58619. };
  58620. var i = 0;
  58621. while (i < numSamples) {
  58622. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58623. vector.normalize();
  58624. scale = i / numSamples;
  58625. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58626. vector.scaleInPlace(scale);
  58627. result.push(vector.x, vector.y, vector.z);
  58628. i++;
  58629. }
  58630. return result;
  58631. };
  58632. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58633. var _this = this;
  58634. var numSamples = this.samples;
  58635. this._sampleSphere = this._generateHemisphere();
  58636. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58637. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58638. "base", "range", "projection", "near", "far", "texelSize",
  58639. "xViewport", "yViewport", "maxZ", "minZAspect"
  58640. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58641. this._ssaoPostProcess.onApply = function (effect) {
  58642. if (_this._firstUpdate) {
  58643. effect.setArray3("sampleSphere", _this._sampleSphere);
  58644. effect.setFloat("randTextureTiles", 4.0);
  58645. }
  58646. if (!_this._scene.activeCamera) {
  58647. return;
  58648. }
  58649. effect.setFloat("samplesFactor", 1 / _this.samples);
  58650. effect.setFloat("totalStrength", _this.totalStrength);
  58651. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58652. effect.setFloat("radius", _this.radius);
  58653. effect.setFloat("maxZ", _this.maxZ);
  58654. effect.setFloat("minZAspect", _this.minZAspect);
  58655. effect.setFloat("base", _this.base);
  58656. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58657. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58658. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58659. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58660. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58661. effect.setTexture("textureSampler", _this._depthTexture);
  58662. effect.setTexture("normalSampler", _this._normalTexture);
  58663. effect.setTexture("randomSampler", _this._randomTexture);
  58664. };
  58665. };
  58666. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58667. var _this = this;
  58668. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58669. this._ssaoCombinePostProcess.onApply = function (effect) {
  58670. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58671. };
  58672. };
  58673. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58674. var size = 512;
  58675. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58676. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58677. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58678. var context = this._randomTexture.getContext();
  58679. var rand = function (min, max) {
  58680. return Math.random() * (max - min) + min;
  58681. };
  58682. var randVector = BABYLON.Vector3.Zero();
  58683. for (var x = 0; x < size; x++) {
  58684. for (var y = 0; y < size; y++) {
  58685. randVector.x = rand(0.0, 1.0);
  58686. randVector.y = rand(0.0, 1.0);
  58687. randVector.z = 0.0;
  58688. randVector.normalize();
  58689. randVector.scaleInPlace(255);
  58690. randVector.x = Math.floor(randVector.x);
  58691. randVector.y = Math.floor(randVector.y);
  58692. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58693. context.fillRect(x, y, 1, 1);
  58694. }
  58695. }
  58696. this._randomTexture.update(false);
  58697. };
  58698. __decorate([
  58699. BABYLON.serialize()
  58700. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58701. __decorate([
  58702. BABYLON.serialize()
  58703. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58704. __decorate([
  58705. BABYLON.serialize()
  58706. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58707. __decorate([
  58708. BABYLON.serialize("samples")
  58709. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58710. __decorate([
  58711. BABYLON.serialize("expensiveBlur")
  58712. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58713. __decorate([
  58714. BABYLON.serialize()
  58715. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58716. __decorate([
  58717. BABYLON.serialize()
  58718. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58719. return SSAO2RenderingPipeline;
  58720. }(BABYLON.PostProcessRenderPipeline));
  58721. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58722. })(BABYLON || (BABYLON = {}));
  58723. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58724. // BABYLON.JS Chromatic Aberration GLSL Shader
  58725. // Author: Olivier Guyot
  58726. // Separates very slightly R, G and B colors on the edges of the screen
  58727. // Inspired by Francois Tarlier & Martins Upitis
  58728. var BABYLON;
  58729. (function (BABYLON) {
  58730. var LensRenderingPipeline = /** @class */ (function (_super) {
  58731. __extends(LensRenderingPipeline, _super);
  58732. /**
  58733. * @constructor
  58734. *
  58735. * Effect parameters are as follow:
  58736. * {
  58737. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58738. * edge_blur: number; // from 0 to x (1 for realism)
  58739. * distortion: number; // from 0 to x (1 for realism)
  58740. * grain_amount: number; // from 0 to 1
  58741. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58742. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58743. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58744. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58745. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58746. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58747. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58748. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58749. * }
  58750. * Note: if an effect parameter is unset, effect is disabled
  58751. *
  58752. * @param {string} name - The rendering pipeline name
  58753. * @param {object} parameters - An object containing all parameters (see above)
  58754. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58755. * @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)
  58756. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58757. */
  58758. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58759. if (ratio === void 0) { ratio = 1.0; }
  58760. var _this = _super.call(this, scene.getEngine(), name) || this;
  58761. // Lens effects can be of the following:
  58762. // - chromatic aberration (slight shift of RGB colors)
  58763. // - blur on the edge of the lens
  58764. // - lens distortion
  58765. // - depth-of-field blur & highlights enhancing
  58766. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58767. // - grain effect (noise or custom texture)
  58768. // Two additional texture samplers are needed:
  58769. // - depth map (for depth-of-field)
  58770. // - grain texture
  58771. /**
  58772. * The chromatic aberration PostProcess id in the pipeline
  58773. * @type {string}
  58774. */
  58775. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58776. /**
  58777. * The highlights enhancing PostProcess id in the pipeline
  58778. * @type {string}
  58779. */
  58780. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58781. /**
  58782. * The depth-of-field PostProcess id in the pipeline
  58783. * @type {string}
  58784. */
  58785. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58786. _this._scene = scene;
  58787. // Fetch texture samplers
  58788. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58789. if (parameters.grain_texture) {
  58790. _this._grainTexture = parameters.grain_texture;
  58791. }
  58792. else {
  58793. _this._createGrainTexture();
  58794. }
  58795. // save parameters
  58796. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58797. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58798. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58799. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58800. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58801. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58802. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58803. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58804. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58805. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58806. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58807. // Create effects
  58808. _this._createChromaticAberrationPostProcess(ratio);
  58809. _this._createHighlightsPostProcess(ratio);
  58810. _this._createDepthOfFieldPostProcess(ratio / 4);
  58811. // Set up pipeline
  58812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58813. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58814. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58815. if (_this._highlightsGain === -1) {
  58816. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58817. }
  58818. // Finish
  58819. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58820. if (cameras) {
  58821. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58822. }
  58823. return _this;
  58824. }
  58825. // public methods (self explanatory)
  58826. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58827. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58828. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58829. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58830. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58831. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58832. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58833. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58834. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58835. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58836. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58837. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58838. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58839. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58840. };
  58841. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58842. this._highlightsPostProcess.updateEffect();
  58843. };
  58844. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58845. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58846. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58847. this._highlightsGain = amount;
  58848. };
  58849. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58850. if (this._highlightsGain === -1) {
  58851. this._highlightsGain = 1.0;
  58852. }
  58853. this._highlightsThreshold = amount;
  58854. };
  58855. LensRenderingPipeline.prototype.disableHighlights = function () {
  58856. this._highlightsGain = -1;
  58857. };
  58858. /**
  58859. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58860. */
  58861. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58862. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58863. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58864. this._chromaticAberrationPostProcess = null;
  58865. this._highlightsPostProcess = null;
  58866. this._depthOfFieldPostProcess = null;
  58867. this._grainTexture.dispose();
  58868. if (disableDepthRender)
  58869. this._scene.disableDepthRenderer();
  58870. };
  58871. // colors shifting and distortion
  58872. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58873. var _this = this;
  58874. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58875. [], // samplers
  58876. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58877. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58878. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58879. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58880. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58881. };
  58882. };
  58883. // highlights enhancing
  58884. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58885. var _this = this;
  58886. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58887. [], // samplers
  58888. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58889. this._highlightsPostProcess.onApply = function (effect) {
  58890. effect.setFloat('gain', _this._highlightsGain);
  58891. effect.setFloat('threshold', _this._highlightsThreshold);
  58892. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58893. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58894. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58895. };
  58896. };
  58897. // colors shifting and distortion
  58898. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58899. var _this = this;
  58900. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58901. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58902. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58903. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58904. this._depthOfFieldPostProcess.onApply = function (effect) {
  58905. effect.setTexture("depthSampler", _this._depthTexture);
  58906. effect.setTexture("grainSampler", _this._grainTexture);
  58907. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58908. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58909. effect.setFloat('grain_amount', _this._grainAmount);
  58910. effect.setBool('blur_noise', _this._blurNoise);
  58911. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58912. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58913. effect.setFloat('distortion', _this._distortion);
  58914. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58915. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58916. effect.setFloat('aperture', _this._dofAperture);
  58917. effect.setFloat('darken', _this._dofDarken);
  58918. effect.setFloat('edge_blur', _this._edgeBlur);
  58919. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58920. if (_this._scene.activeCamera) {
  58921. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58922. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58923. }
  58924. };
  58925. };
  58926. // creates a black and white random noise texture, 512x512
  58927. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58928. var size = 512;
  58929. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58930. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58931. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58932. var context = this._grainTexture.getContext();
  58933. var rand = function (min, max) {
  58934. return Math.random() * (max - min) + min;
  58935. };
  58936. var value;
  58937. for (var x = 0; x < size; x++) {
  58938. for (var y = 0; y < size; y++) {
  58939. value = Math.floor(rand(0.42, 0.58) * 255);
  58940. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58941. context.fillRect(x, y, 1, 1);
  58942. }
  58943. }
  58944. this._grainTexture.update(false);
  58945. };
  58946. return LensRenderingPipeline;
  58947. }(BABYLON.PostProcessRenderPipeline));
  58948. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58949. })(BABYLON || (BABYLON = {}));
  58950. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58951. var BABYLON;
  58952. (function (BABYLON) {
  58953. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58954. __extends(StandardRenderingPipeline, _super);
  58955. /**
  58956. * @constructor
  58957. * @param {string} name - The rendering pipeline name
  58958. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58959. * @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)
  58960. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58961. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58962. */
  58963. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58964. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58965. var _this = _super.call(this, scene.getEngine(), name) || this;
  58966. _this.downSampleX4PostProcess = null;
  58967. _this.brightPassPostProcess = null;
  58968. _this.blurHPostProcesses = [];
  58969. _this.blurVPostProcesses = [];
  58970. _this.textureAdderPostProcess = null;
  58971. _this.volumetricLightPostProcess = null;
  58972. _this.volumetricLightSmoothXPostProcess = null;
  58973. _this.volumetricLightSmoothYPostProcess = null;
  58974. _this.volumetricLightMergePostProces = null;
  58975. _this.volumetricLightFinalPostProcess = null;
  58976. _this.luminancePostProcess = null;
  58977. _this.luminanceDownSamplePostProcesses = [];
  58978. _this.hdrPostProcess = null;
  58979. _this.textureAdderFinalPostProcess = null;
  58980. _this.lensFlareFinalPostProcess = null;
  58981. _this.hdrFinalPostProcess = null;
  58982. _this.lensFlarePostProcess = null;
  58983. _this.lensFlareComposePostProcess = null;
  58984. _this.motionBlurPostProcess = null;
  58985. _this.depthOfFieldPostProcess = null;
  58986. // Values
  58987. _this.brightThreshold = 1.0;
  58988. _this.blurWidth = 512.0;
  58989. _this.horizontalBlur = false;
  58990. _this.exposure = 1.0;
  58991. _this.lensTexture = null;
  58992. _this.volumetricLightCoefficient = 0.2;
  58993. _this.volumetricLightPower = 4.0;
  58994. _this.volumetricLightBlurScale = 64.0;
  58995. _this.sourceLight = null;
  58996. _this.hdrMinimumLuminance = 1.0;
  58997. _this.hdrDecreaseRate = 0.5;
  58998. _this.hdrIncreaseRate = 0.5;
  58999. _this.lensColorTexture = null;
  59000. _this.lensFlareStrength = 20.0;
  59001. _this.lensFlareGhostDispersal = 1.4;
  59002. _this.lensFlareHaloWidth = 0.7;
  59003. _this.lensFlareDistortionStrength = 16.0;
  59004. _this.lensStarTexture = null;
  59005. _this.lensFlareDirtTexture = null;
  59006. _this.depthOfFieldDistance = 10.0;
  59007. _this.depthOfFieldBlurWidth = 64.0;
  59008. _this.motionStrength = 1.0;
  59009. // IAnimatable
  59010. _this.animations = [];
  59011. _this._currentDepthOfFieldSource = null;
  59012. _this._hdrCurrentLuminance = 1.0;
  59013. // Getters and setters
  59014. _this._bloomEnabled = true;
  59015. _this._depthOfFieldEnabled = false;
  59016. _this._vlsEnabled = false;
  59017. _this._lensFlareEnabled = false;
  59018. _this._hdrEnabled = false;
  59019. _this._motionBlurEnabled = false;
  59020. _this._motionBlurSamples = 64.0;
  59021. _this._volumetricLightStepsCount = 50.0;
  59022. _this._cameras = cameras || [];
  59023. // Initialize
  59024. _this._scene = scene;
  59025. _this._basePostProcess = originalPostProcess;
  59026. _this._ratio = ratio;
  59027. // Misc
  59028. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59029. // Finish
  59030. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59031. _this._buildPipeline();
  59032. return _this;
  59033. }
  59034. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  59035. get: function () {
  59036. return this._bloomEnabled;
  59037. },
  59038. set: function (enabled) {
  59039. if (this._bloomEnabled === enabled) {
  59040. return;
  59041. }
  59042. this._bloomEnabled = enabled;
  59043. this._buildPipeline();
  59044. },
  59045. enumerable: true,
  59046. configurable: true
  59047. });
  59048. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59049. get: function () {
  59050. return this._depthOfFieldEnabled;
  59051. },
  59052. set: function (enabled) {
  59053. if (this._depthOfFieldEnabled === enabled) {
  59054. return;
  59055. }
  59056. this._depthOfFieldEnabled = enabled;
  59057. this._buildPipeline();
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59063. get: function () {
  59064. return this._lensFlareEnabled;
  59065. },
  59066. set: function (enabled) {
  59067. if (this._lensFlareEnabled === enabled) {
  59068. return;
  59069. }
  59070. this._lensFlareEnabled = enabled;
  59071. this._buildPipeline();
  59072. },
  59073. enumerable: true,
  59074. configurable: true
  59075. });
  59076. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  59077. get: function () {
  59078. return this._hdrEnabled;
  59079. },
  59080. set: function (enabled) {
  59081. if (this._hdrEnabled === enabled) {
  59082. return;
  59083. }
  59084. this._hdrEnabled = enabled;
  59085. this._buildPipeline();
  59086. },
  59087. enumerable: true,
  59088. configurable: true
  59089. });
  59090. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  59091. get: function () {
  59092. return this._vlsEnabled;
  59093. },
  59094. set: function (enabled) {
  59095. if (this._vlsEnabled === enabled) {
  59096. return;
  59097. }
  59098. if (enabled) {
  59099. var geometry = this._scene.enableGeometryBufferRenderer();
  59100. if (!geometry) {
  59101. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  59102. return;
  59103. }
  59104. }
  59105. this._vlsEnabled = enabled;
  59106. this._buildPipeline();
  59107. },
  59108. enumerable: true,
  59109. configurable: true
  59110. });
  59111. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59112. get: function () {
  59113. return this._motionBlurEnabled;
  59114. },
  59115. set: function (enabled) {
  59116. if (this._motionBlurEnabled === enabled) {
  59117. return;
  59118. }
  59119. this._motionBlurEnabled = enabled;
  59120. this._buildPipeline();
  59121. },
  59122. enumerable: true,
  59123. configurable: true
  59124. });
  59125. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59126. get: function () {
  59127. return this._volumetricLightStepsCount;
  59128. },
  59129. set: function (count) {
  59130. if (this.volumetricLightPostProcess) {
  59131. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59132. }
  59133. this._volumetricLightStepsCount = count;
  59134. },
  59135. enumerable: true,
  59136. configurable: true
  59137. });
  59138. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59139. get: function () {
  59140. return this._motionBlurSamples;
  59141. },
  59142. set: function (samples) {
  59143. if (this.motionBlurPostProcess) {
  59144. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59145. }
  59146. this._motionBlurSamples = samples;
  59147. },
  59148. enumerable: true,
  59149. configurable: true
  59150. });
  59151. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59152. var _this = this;
  59153. var ratio = this._ratio;
  59154. var scene = this._scene;
  59155. this._disposePostProcesses();
  59156. this._reset();
  59157. // Create pass post-process
  59158. if (!this._basePostProcess) {
  59159. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59160. this.originalPostProcess.onApply = function (effect) {
  59161. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59162. };
  59163. }
  59164. else {
  59165. this.originalPostProcess = this._basePostProcess;
  59166. }
  59167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59168. this._currentDepthOfFieldSource = this.originalPostProcess;
  59169. if (this._vlsEnabled) {
  59170. // Create volumetric light
  59171. this._createVolumetricLightPostProcess(scene, ratio);
  59172. // Create volumetric light final post-process
  59173. 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);
  59174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59175. }
  59176. if (this._bloomEnabled) {
  59177. // Create down sample X4 post-process
  59178. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59179. // Create bright pass post-process
  59180. this._createBrightPassPostProcess(scene, ratio / 2);
  59181. // Create gaussian blur post-processes (down sampling blurs)
  59182. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59183. // Create texture adder post-process
  59184. this._createTextureAdderPostProcess(scene, ratio);
  59185. // Create depth-of-field source post-process
  59186. 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);
  59187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59188. }
  59189. if (this._lensFlareEnabled) {
  59190. // Create lens flare post-process
  59191. this._createLensFlarePostProcess(scene, ratio);
  59192. // Create depth-of-field source post-process post lens-flare and disable it now
  59193. 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);
  59194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59195. }
  59196. if (this._hdrEnabled) {
  59197. // Create luminance
  59198. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59199. // Create HDR
  59200. this._createHdrPostProcess(scene, ratio);
  59201. // Create depth-of-field source post-process post hdr and disable it now
  59202. 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);
  59203. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59204. }
  59205. if (this._depthOfFieldEnabled) {
  59206. // Create gaussian blur used by depth-of-field
  59207. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59208. // Create depth-of-field post-process
  59209. this._createDepthOfFieldPostProcess(scene, ratio);
  59210. }
  59211. if (this._motionBlurEnabled) {
  59212. // Create motion blur post-process
  59213. this._createMotionBlurPostProcess(scene, ratio);
  59214. }
  59215. if (this._cameras !== null) {
  59216. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59217. }
  59218. };
  59219. // Down Sample X4 Post-Processs
  59220. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59221. var _this = this;
  59222. var downSampleX4Offsets = new Array(32);
  59223. 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);
  59224. this.downSampleX4PostProcess.onApply = function (effect) {
  59225. var id = 0;
  59226. var width = _this.downSampleX4PostProcess.width;
  59227. var height = _this.downSampleX4PostProcess.height;
  59228. for (var i = -2; i < 2; i++) {
  59229. for (var j = -2; j < 2; j++) {
  59230. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59231. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59232. id += 2;
  59233. }
  59234. }
  59235. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59236. };
  59237. // Add to pipeline
  59238. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59239. };
  59240. // Brightpass Post-Process
  59241. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59242. var _this = this;
  59243. var brightOffsets = new Array(8);
  59244. 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);
  59245. this.brightPassPostProcess.onApply = function (effect) {
  59246. var sU = (1.0 / _this.brightPassPostProcess.width);
  59247. var sV = (1.0 / _this.brightPassPostProcess.height);
  59248. brightOffsets[0] = -0.5 * sU;
  59249. brightOffsets[1] = 0.5 * sV;
  59250. brightOffsets[2] = 0.5 * sU;
  59251. brightOffsets[3] = 0.5 * sV;
  59252. brightOffsets[4] = -0.5 * sU;
  59253. brightOffsets[5] = -0.5 * sV;
  59254. brightOffsets[6] = 0.5 * sU;
  59255. brightOffsets[7] = -0.5 * sV;
  59256. effect.setArray2("dsOffsets", brightOffsets);
  59257. effect.setFloat("brightThreshold", _this.brightThreshold);
  59258. };
  59259. // Add to pipeline
  59260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59261. };
  59262. // Create blur H&V post-processes
  59263. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59264. var _this = this;
  59265. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59266. var engine = scene.getEngine();
  59267. 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);
  59268. 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);
  59269. blurX.onActivateObservable.add(function () {
  59270. var dw = blurX.width / engine.getRenderWidth();
  59271. blurX.kernel = _this[blurWidthKey] * dw;
  59272. });
  59273. blurY.onActivateObservable.add(function () {
  59274. var dw = blurY.height / engine.getRenderHeight();
  59275. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59276. });
  59277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59279. this.blurHPostProcesses.push(blurX);
  59280. this.blurVPostProcesses.push(blurY);
  59281. };
  59282. // Create texture adder post-process
  59283. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59284. var _this = this;
  59285. 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);
  59286. this.textureAdderPostProcess.onApply = function (effect) {
  59287. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59288. effect.setTexture("lensSampler", _this.lensTexture);
  59289. effect.setFloat("exposure", _this.exposure);
  59290. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59291. };
  59292. // Add to pipeline
  59293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59294. };
  59295. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59296. var _this = this;
  59297. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59298. geometryRenderer.enablePosition = true;
  59299. var geometry = geometryRenderer.getGBuffer();
  59300. // Base post-process
  59301. 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));
  59302. var depthValues = BABYLON.Vector2.Zero();
  59303. this.volumetricLightPostProcess.onApply = function (effect) {
  59304. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59305. var generator = _this.sourceLight.getShadowGenerator();
  59306. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59307. effect.setTexture("positionSampler", geometry.textures[2]);
  59308. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59309. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59310. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59311. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59312. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59313. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59314. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59315. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59316. effect.setVector2("depthValues", depthValues);
  59317. }
  59318. };
  59319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59320. // Smooth
  59321. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59322. // Merge
  59323. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59324. this.volumetricLightMergePostProces.onApply = function (effect) {
  59325. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59326. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59327. };
  59328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59329. };
  59330. // Create luminance
  59331. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59332. var _this = this;
  59333. // Create luminance
  59334. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59335. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59336. var offsets = [];
  59337. this.luminancePostProcess.onApply = function (effect) {
  59338. var sU = (1.0 / _this.luminancePostProcess.width);
  59339. var sV = (1.0 / _this.luminancePostProcess.height);
  59340. offsets[0] = -0.5 * sU;
  59341. offsets[1] = 0.5 * sV;
  59342. offsets[2] = 0.5 * sU;
  59343. offsets[3] = 0.5 * sV;
  59344. offsets[4] = -0.5 * sU;
  59345. offsets[5] = -0.5 * sV;
  59346. offsets[6] = 0.5 * sU;
  59347. offsets[7] = -0.5 * sV;
  59348. effect.setArray2("lumOffsets", offsets);
  59349. };
  59350. // Add to pipeline
  59351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59352. // Create down sample luminance
  59353. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59354. var size = Math.pow(3, i);
  59355. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59356. if (i === 0) {
  59357. defines += "#define FINAL_DOWN_SAMPLER";
  59358. }
  59359. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59360. this.luminanceDownSamplePostProcesses.push(postProcess);
  59361. }
  59362. // Create callbacks and add effects
  59363. var lastLuminance = this.luminancePostProcess;
  59364. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59365. var downSampleOffsets = new Array(18);
  59366. pp.onApply = function (effect) {
  59367. if (!lastLuminance) {
  59368. return;
  59369. }
  59370. var id = 0;
  59371. for (var x = -1; x < 2; x++) {
  59372. for (var y = -1; y < 2; y++) {
  59373. downSampleOffsets[id] = x / lastLuminance.width;
  59374. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59375. id += 2;
  59376. }
  59377. }
  59378. effect.setArray2("dsOffsets", downSampleOffsets);
  59379. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59380. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59381. lastLuminance = _this.luminancePostProcess;
  59382. }
  59383. else {
  59384. lastLuminance = pp;
  59385. }
  59386. };
  59387. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59388. pp.onAfterRender = function (effect) {
  59389. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59390. 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);
  59391. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59392. };
  59393. }
  59394. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59395. });
  59396. };
  59397. // Create HDR post-process
  59398. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59399. var _this = this;
  59400. 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);
  59401. var outputLiminance = 1;
  59402. var time = 0;
  59403. var lastTime = 0;
  59404. this.hdrPostProcess.onApply = function (effect) {
  59405. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59406. time += scene.getEngine().getDeltaTime();
  59407. if (outputLiminance < 0) {
  59408. outputLiminance = _this._hdrCurrentLuminance;
  59409. }
  59410. else {
  59411. var dt = (lastTime - time) / 1000.0;
  59412. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59413. outputLiminance += _this.hdrDecreaseRate * dt;
  59414. }
  59415. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59416. outputLiminance -= _this.hdrIncreaseRate * dt;
  59417. }
  59418. else {
  59419. outputLiminance = _this._hdrCurrentLuminance;
  59420. }
  59421. }
  59422. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59423. effect.setFloat("averageLuminance", outputLiminance);
  59424. lastTime = time;
  59425. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59426. };
  59427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59428. };
  59429. // Create lens flare post-process
  59430. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59431. var _this = this;
  59432. 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);
  59433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59434. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59435. 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);
  59436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59437. var resolution = new BABYLON.Vector2(0, 0);
  59438. // Lens flare
  59439. this.lensFlarePostProcess.onApply = function (effect) {
  59440. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59441. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59442. effect.setFloat("strength", _this.lensFlareStrength);
  59443. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59444. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59445. // Shift
  59446. resolution.x = _this.lensFlarePostProcess.width;
  59447. resolution.y = _this.lensFlarePostProcess.height;
  59448. effect.setVector2("resolution", resolution);
  59449. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59450. };
  59451. // Compose
  59452. 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);
  59453. 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);
  59454. this.lensFlareComposePostProcess.onApply = function (effect) {
  59455. if (!_this._scene.activeCamera) {
  59456. return;
  59457. }
  59458. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59459. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59460. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59461. // Lens start rotation matrix
  59462. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59463. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59464. 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));
  59465. camRot *= 4.0;
  59466. 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);
  59467. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59468. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59469. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59470. };
  59471. };
  59472. // Create depth-of-field post-process
  59473. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59474. var _this = this;
  59475. 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);
  59476. this.depthOfFieldPostProcess.onApply = function (effect) {
  59477. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59478. effect.setTexture("depthSampler", _this._getDepthTexture());
  59479. effect.setFloat("distance", _this.depthOfFieldDistance);
  59480. };
  59481. // Add to pipeline
  59482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59483. };
  59484. // Create motion blur post-process
  59485. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59486. var _this = this;
  59487. 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);
  59488. var motionScale = 0;
  59489. var prevViewProjection = BABYLON.Matrix.Identity();
  59490. var invViewProjection = BABYLON.Matrix.Identity();
  59491. var viewProjection = BABYLON.Matrix.Identity();
  59492. var screenSize = BABYLON.Vector2.Zero();
  59493. this.motionBlurPostProcess.onApply = function (effect) {
  59494. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59495. viewProjection.invertToRef(invViewProjection);
  59496. effect.setMatrix("inverseViewProjection", invViewProjection);
  59497. effect.setMatrix("prevViewProjection", prevViewProjection);
  59498. prevViewProjection = viewProjection;
  59499. screenSize.x = _this.motionBlurPostProcess.width;
  59500. screenSize.y = _this.motionBlurPostProcess.height;
  59501. effect.setVector2("screenSize", screenSize);
  59502. motionScale = scene.getEngine().getFps() / 60.0;
  59503. effect.setFloat("motionScale", motionScale);
  59504. effect.setFloat("motionStrength", _this.motionStrength);
  59505. effect.setTexture("depthSampler", _this._getDepthTexture());
  59506. };
  59507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59508. };
  59509. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59510. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59511. var renderer = this._scene.enableGeometryBufferRenderer();
  59512. return renderer.getGBuffer().textures[0];
  59513. }
  59514. return this._scene.enableDepthRenderer().getDepthMap();
  59515. };
  59516. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59517. for (var i = 0; i < this._cameras.length; i++) {
  59518. var camera = this._cameras[i];
  59519. if (this.originalPostProcess) {
  59520. this.originalPostProcess.dispose(camera);
  59521. }
  59522. if (this.downSampleX4PostProcess) {
  59523. this.downSampleX4PostProcess.dispose(camera);
  59524. }
  59525. if (this.brightPassPostProcess) {
  59526. this.brightPassPostProcess.dispose(camera);
  59527. }
  59528. if (this.textureAdderPostProcess) {
  59529. this.textureAdderPostProcess.dispose(camera);
  59530. }
  59531. if (this.textureAdderFinalPostProcess) {
  59532. this.textureAdderFinalPostProcess.dispose(camera);
  59533. }
  59534. if (this.volumetricLightPostProcess) {
  59535. this.volumetricLightPostProcess.dispose(camera);
  59536. }
  59537. if (this.volumetricLightSmoothXPostProcess) {
  59538. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59539. }
  59540. if (this.volumetricLightSmoothYPostProcess) {
  59541. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59542. }
  59543. if (this.volumetricLightMergePostProces) {
  59544. this.volumetricLightMergePostProces.dispose(camera);
  59545. }
  59546. if (this.volumetricLightFinalPostProcess) {
  59547. this.volumetricLightFinalPostProcess.dispose(camera);
  59548. }
  59549. if (this.lensFlarePostProcess) {
  59550. this.lensFlarePostProcess.dispose(camera);
  59551. }
  59552. if (this.lensFlareComposePostProcess) {
  59553. this.lensFlareComposePostProcess.dispose(camera);
  59554. }
  59555. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59556. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59557. }
  59558. if (this.luminancePostProcess) {
  59559. this.luminancePostProcess.dispose(camera);
  59560. }
  59561. if (this.hdrPostProcess) {
  59562. this.hdrPostProcess.dispose(camera);
  59563. }
  59564. if (this.hdrFinalPostProcess) {
  59565. this.hdrFinalPostProcess.dispose(camera);
  59566. }
  59567. if (this.depthOfFieldPostProcess) {
  59568. this.depthOfFieldPostProcess.dispose(camera);
  59569. }
  59570. if (this.motionBlurPostProcess) {
  59571. this.motionBlurPostProcess.dispose(camera);
  59572. }
  59573. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59574. this.blurHPostProcesses[j].dispose(camera);
  59575. }
  59576. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59577. this.blurVPostProcesses[j].dispose(camera);
  59578. }
  59579. }
  59580. this.originalPostProcess = null;
  59581. this.downSampleX4PostProcess = null;
  59582. this.brightPassPostProcess = null;
  59583. this.textureAdderPostProcess = null;
  59584. this.textureAdderFinalPostProcess = null;
  59585. this.volumetricLightPostProcess = null;
  59586. this.volumetricLightSmoothXPostProcess = null;
  59587. this.volumetricLightSmoothYPostProcess = null;
  59588. this.volumetricLightMergePostProces = null;
  59589. this.volumetricLightFinalPostProcess = null;
  59590. this.lensFlarePostProcess = null;
  59591. this.lensFlareComposePostProcess = null;
  59592. this.luminancePostProcess = null;
  59593. this.hdrPostProcess = null;
  59594. this.hdrFinalPostProcess = null;
  59595. this.depthOfFieldPostProcess = null;
  59596. this.motionBlurPostProcess = null;
  59597. this.luminanceDownSamplePostProcesses = [];
  59598. this.blurHPostProcesses = [];
  59599. this.blurVPostProcesses = [];
  59600. };
  59601. // Dispose
  59602. StandardRenderingPipeline.prototype.dispose = function () {
  59603. this._disposePostProcesses();
  59604. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59605. _super.prototype.dispose.call(this);
  59606. };
  59607. // Serialize rendering pipeline
  59608. StandardRenderingPipeline.prototype.serialize = function () {
  59609. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59610. serializationObject.customType = "StandardRenderingPipeline";
  59611. return serializationObject;
  59612. };
  59613. /**
  59614. * Static members
  59615. */
  59616. // Parse serialized pipeline
  59617. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59618. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59619. };
  59620. // Luminance steps
  59621. StandardRenderingPipeline.LuminanceSteps = 6;
  59622. __decorate([
  59623. BABYLON.serialize()
  59624. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59625. __decorate([
  59626. BABYLON.serialize()
  59627. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59628. __decorate([
  59629. BABYLON.serialize()
  59630. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59631. __decorate([
  59632. BABYLON.serialize()
  59633. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59634. __decorate([
  59635. BABYLON.serializeAsTexture("lensTexture")
  59636. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59637. __decorate([
  59638. BABYLON.serialize()
  59639. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59640. __decorate([
  59641. BABYLON.serialize()
  59642. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59643. __decorate([
  59644. BABYLON.serialize()
  59645. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59646. __decorate([
  59647. BABYLON.serialize()
  59648. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59649. __decorate([
  59650. BABYLON.serialize()
  59651. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59652. __decorate([
  59653. BABYLON.serialize()
  59654. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59655. __decorate([
  59656. BABYLON.serializeAsTexture("lensColorTexture")
  59657. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59658. __decorate([
  59659. BABYLON.serialize()
  59660. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59661. __decorate([
  59662. BABYLON.serialize()
  59663. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59664. __decorate([
  59665. BABYLON.serialize()
  59666. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59667. __decorate([
  59668. BABYLON.serialize()
  59669. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59670. __decorate([
  59671. BABYLON.serializeAsTexture("lensStarTexture")
  59672. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59673. __decorate([
  59674. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59675. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59676. __decorate([
  59677. BABYLON.serialize()
  59678. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59679. __decorate([
  59680. BABYLON.serialize()
  59681. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59682. __decorate([
  59683. BABYLON.serialize()
  59684. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59685. __decorate([
  59686. BABYLON.serialize()
  59687. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59688. __decorate([
  59689. BABYLON.serialize()
  59690. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59691. __decorate([
  59692. BABYLON.serialize()
  59693. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59694. __decorate([
  59695. BABYLON.serialize()
  59696. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59697. __decorate([
  59698. BABYLON.serialize()
  59699. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59700. __decorate([
  59701. BABYLON.serialize()
  59702. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59703. __decorate([
  59704. BABYLON.serialize()
  59705. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59706. __decorate([
  59707. BABYLON.serialize()
  59708. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59709. return StandardRenderingPipeline;
  59710. }(BABYLON.PostProcessRenderPipeline));
  59711. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59712. })(BABYLON || (BABYLON = {}));
  59713. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59714. var BABYLON;
  59715. (function (BABYLON) {
  59716. var FxaaPostProcess = /** @class */ (function (_super) {
  59717. __extends(FxaaPostProcess, _super);
  59718. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59719. if (camera === void 0) { camera = null; }
  59720. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59721. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59722. _this.onApplyObservable.add(function (effect) {
  59723. var texelSize = _this.texelSize;
  59724. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59725. });
  59726. return _this;
  59727. }
  59728. return FxaaPostProcess;
  59729. }(BABYLON.PostProcess));
  59730. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59731. })(BABYLON || (BABYLON = {}));
  59732. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59733. var BABYLON;
  59734. (function (BABYLON) {
  59735. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59736. __extends(DefaultRenderingPipeline, _super);
  59737. /**
  59738. * @constructor
  59739. * @param {string} name - The rendering pipeline name
  59740. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59741. * @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)
  59742. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59743. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59744. */
  59745. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59746. if (automaticBuild === void 0) { automaticBuild = true; }
  59747. var _this = _super.call(this, scene.getEngine(), name) || this;
  59748. _this.PassPostProcessId = "PassPostProcessEffect";
  59749. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59750. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59751. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59752. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59753. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59754. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59755. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59756. // IAnimatable
  59757. _this.animations = [];
  59758. // Values
  59759. _this._bloomEnabled = false;
  59760. _this._fxaaEnabled = false;
  59761. _this._imageProcessingEnabled = true;
  59762. _this._bloomScale = 0.6;
  59763. _this._buildAllowed = true;
  59764. /**
  59765. * Specifies the size of the bloom blur kernel, relative to the final output size
  59766. */
  59767. _this.bloomKernel = 64;
  59768. /**
  59769. * Specifies the weight of the bloom in the final rendering
  59770. */
  59771. _this._bloomWeight = 0.15;
  59772. _this._cameras = cameras || [];
  59773. _this._buildAllowed = automaticBuild;
  59774. // Initialize
  59775. _this._scene = scene;
  59776. var caps = _this._scene.getEngine().getCaps();
  59777. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59778. // Misc
  59779. if (_this._hdr) {
  59780. if (caps.textureHalfFloatRender) {
  59781. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59782. }
  59783. else if (caps.textureFloatRender) {
  59784. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59785. }
  59786. }
  59787. else {
  59788. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59789. }
  59790. // Attach
  59791. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59792. _this._buildPipeline();
  59793. return _this;
  59794. }
  59795. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59796. get: function () {
  59797. return this._bloomWeight;
  59798. },
  59799. set: function (value) {
  59800. if (this._bloomWeight === value) {
  59801. return;
  59802. }
  59803. this._bloomWeight = value;
  59804. if (this._hdr && this.copyBack) {
  59805. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59806. }
  59807. },
  59808. enumerable: true,
  59809. configurable: true
  59810. });
  59811. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59812. get: function () {
  59813. return this._bloomScale;
  59814. },
  59815. set: function (value) {
  59816. if (this._bloomScale === value) {
  59817. return;
  59818. }
  59819. this._bloomScale = value;
  59820. this._buildPipeline();
  59821. },
  59822. enumerable: true,
  59823. configurable: true
  59824. });
  59825. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59826. get: function () {
  59827. return this._bloomEnabled;
  59828. },
  59829. set: function (enabled) {
  59830. if (this._bloomEnabled === enabled) {
  59831. return;
  59832. }
  59833. this._bloomEnabled = enabled;
  59834. this._buildPipeline();
  59835. },
  59836. enumerable: true,
  59837. configurable: true
  59838. });
  59839. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59840. get: function () {
  59841. return this._fxaaEnabled;
  59842. },
  59843. set: function (enabled) {
  59844. if (this._fxaaEnabled === enabled) {
  59845. return;
  59846. }
  59847. this._fxaaEnabled = enabled;
  59848. this._buildPipeline();
  59849. },
  59850. enumerable: true,
  59851. configurable: true
  59852. });
  59853. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59854. get: function () {
  59855. return this._imageProcessingEnabled;
  59856. },
  59857. set: function (enabled) {
  59858. if (this._imageProcessingEnabled === enabled) {
  59859. return;
  59860. }
  59861. this._imageProcessingEnabled = enabled;
  59862. this._buildPipeline();
  59863. },
  59864. enumerable: true,
  59865. configurable: true
  59866. });
  59867. /**
  59868. * Force the compilation of the entire pipeline.
  59869. */
  59870. DefaultRenderingPipeline.prototype.prepare = function () {
  59871. var previousState = this._buildAllowed;
  59872. this._buildAllowed = true;
  59873. this._buildPipeline();
  59874. this._buildAllowed = previousState;
  59875. };
  59876. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59877. var _this = this;
  59878. if (!this._buildAllowed) {
  59879. return;
  59880. }
  59881. var engine = this._scene.getEngine();
  59882. this._disposePostProcesses();
  59883. this._reset();
  59884. if (this.bloomEnabled) {
  59885. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59886. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59887. if (!this._hdr) {
  59888. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59889. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59890. this.highlights.autoClear = false;
  59891. this.highlights.alwaysForcePOT = true;
  59892. }
  59893. 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);
  59894. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59895. this.blurX.alwaysForcePOT = true;
  59896. this.blurX.autoClear = false;
  59897. this.blurX.onActivateObservable.add(function () {
  59898. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59899. _this.blurX.kernel = _this.bloomKernel * dw;
  59900. });
  59901. 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);
  59902. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59903. this.blurY.alwaysForcePOT = true;
  59904. this.blurY.autoClear = false;
  59905. this.blurY.onActivateObservable.add(function () {
  59906. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59907. _this.blurY.kernel = _this.bloomKernel * dh;
  59908. });
  59909. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59910. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59911. this.copyBack.alwaysForcePOT = true;
  59912. if (this._hdr) {
  59913. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59914. var w = this.bloomWeight;
  59915. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59916. }
  59917. else {
  59918. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59919. }
  59920. this.copyBack.autoClear = false;
  59921. }
  59922. if (this._imageProcessingEnabled) {
  59923. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59924. if (this._hdr) {
  59925. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59926. }
  59927. else {
  59928. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59929. }
  59930. }
  59931. if (this.fxaaEnabled) {
  59932. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59933. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59934. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59935. }
  59936. else if (this._hdr && this.imageProcessing) {
  59937. this.finalMerge = this.imageProcessing;
  59938. }
  59939. else {
  59940. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59941. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59942. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59943. }
  59944. if (this.bloomEnabled) {
  59945. if (this._hdr) {
  59946. this.copyBack.shareOutputWith(this.blurX);
  59947. if (this.imageProcessing) {
  59948. this.imageProcessing.shareOutputWith(this.pass);
  59949. this.imageProcessing.autoClear = false;
  59950. }
  59951. else if (this.fxaa) {
  59952. this.fxaa.shareOutputWith(this.pass);
  59953. }
  59954. else {
  59955. this.finalMerge.shareOutputWith(this.pass);
  59956. }
  59957. }
  59958. else {
  59959. if (this.fxaa) {
  59960. this.fxaa.shareOutputWith(this.pass);
  59961. }
  59962. else {
  59963. this.finalMerge.shareOutputWith(this.pass);
  59964. }
  59965. }
  59966. }
  59967. if (this._cameras !== null) {
  59968. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59969. }
  59970. };
  59971. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59972. for (var i = 0; i < this._cameras.length; i++) {
  59973. var camera = this._cameras[i];
  59974. if (this.pass) {
  59975. this.pass.dispose(camera);
  59976. }
  59977. if (this.highlights) {
  59978. this.highlights.dispose(camera);
  59979. }
  59980. if (this.blurX) {
  59981. this.blurX.dispose(camera);
  59982. }
  59983. if (this.blurY) {
  59984. this.blurY.dispose(camera);
  59985. }
  59986. if (this.copyBack) {
  59987. this.copyBack.dispose(camera);
  59988. }
  59989. if (this.imageProcessing) {
  59990. this.imageProcessing.dispose(camera);
  59991. }
  59992. if (this.fxaa) {
  59993. this.fxaa.dispose(camera);
  59994. }
  59995. if (this.finalMerge) {
  59996. this.finalMerge.dispose(camera);
  59997. }
  59998. }
  59999. this.pass = null;
  60000. this.highlights = null;
  60001. this.blurX = null;
  60002. this.blurY = null;
  60003. this.copyBack = null;
  60004. this.imageProcessing = null;
  60005. this.fxaa = null;
  60006. this.finalMerge = null;
  60007. };
  60008. // Dispose
  60009. DefaultRenderingPipeline.prototype.dispose = function () {
  60010. this._disposePostProcesses();
  60011. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60012. _super.prototype.dispose.call(this);
  60013. };
  60014. // Serialize rendering pipeline
  60015. DefaultRenderingPipeline.prototype.serialize = function () {
  60016. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60017. serializationObject.customType = "DefaultRenderingPipeline";
  60018. return serializationObject;
  60019. };
  60020. // Parse serialized pipeline
  60021. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60022. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  60023. };
  60024. __decorate([
  60025. BABYLON.serialize()
  60026. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  60027. __decorate([
  60028. BABYLON.serialize()
  60029. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  60030. __decorate([
  60031. BABYLON.serialize()
  60032. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  60033. __decorate([
  60034. BABYLON.serialize()
  60035. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  60036. __decorate([
  60037. BABYLON.serialize()
  60038. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  60039. __decorate([
  60040. BABYLON.serialize()
  60041. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  60042. __decorate([
  60043. BABYLON.serialize()
  60044. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  60045. __decorate([
  60046. BABYLON.serialize()
  60047. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  60048. return DefaultRenderingPipeline;
  60049. }(BABYLON.PostProcessRenderPipeline));
  60050. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  60051. })(BABYLON || (BABYLON = {}));
  60052. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  60053. var BABYLON;
  60054. (function (BABYLON) {
  60055. var GeometryBufferRenderer = /** @class */ (function () {
  60056. function GeometryBufferRenderer(scene, ratio) {
  60057. if (ratio === void 0) { ratio = 1; }
  60058. this._enablePosition = false;
  60059. this._scene = scene;
  60060. this._ratio = ratio;
  60061. // Render target
  60062. this._createRenderTargets();
  60063. }
  60064. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  60065. set: function (meshes) {
  60066. this._multiRenderTarget.renderList = meshes;
  60067. },
  60068. enumerable: true,
  60069. configurable: true
  60070. });
  60071. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  60072. get: function () {
  60073. return this._multiRenderTarget.isSupported;
  60074. },
  60075. enumerable: true,
  60076. configurable: true
  60077. });
  60078. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  60079. get: function () {
  60080. return this._enablePosition;
  60081. },
  60082. set: function (enable) {
  60083. this._enablePosition = enable;
  60084. this.dispose();
  60085. this._createRenderTargets();
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  60091. var material = subMesh.getMaterial();
  60092. if (material && material.disableDepthWrite) {
  60093. return false;
  60094. }
  60095. var defines = [];
  60096. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60097. var mesh = subMesh.getMesh();
  60098. // Alpha test
  60099. if (material && material.needAlphaTesting()) {
  60100. defines.push("#define ALPHATEST");
  60101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60102. attribs.push(BABYLON.VertexBuffer.UVKind);
  60103. defines.push("#define UV1");
  60104. }
  60105. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60106. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60107. defines.push("#define UV2");
  60108. }
  60109. }
  60110. // Buffers
  60111. if (this._enablePosition) {
  60112. defines.push("#define POSITION");
  60113. }
  60114. // Bones
  60115. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60116. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60117. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60118. if (mesh.numBoneInfluencers > 4) {
  60119. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60120. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60121. }
  60122. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60123. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60124. }
  60125. else {
  60126. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60127. }
  60128. // Instances
  60129. if (useInstances) {
  60130. defines.push("#define INSTANCES");
  60131. attribs.push("world0");
  60132. attribs.push("world1");
  60133. attribs.push("world2");
  60134. attribs.push("world3");
  60135. }
  60136. // Get correct effect
  60137. var join = defines.join("\n");
  60138. if (this._cachedDefines !== join) {
  60139. this._cachedDefines = join;
  60140. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60141. }
  60142. return this._effect.isReady();
  60143. };
  60144. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60145. return this._multiRenderTarget;
  60146. };
  60147. // Methods
  60148. GeometryBufferRenderer.prototype.dispose = function () {
  60149. this.getGBuffer().dispose();
  60150. };
  60151. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60152. var _this = this;
  60153. var engine = this._scene.getEngine();
  60154. var count = this._enablePosition ? 3 : 2;
  60155. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60156. if (!this.isSupported) {
  60157. return;
  60158. }
  60159. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60160. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60161. this._multiRenderTarget.refreshRate = 1;
  60162. this._multiRenderTarget.renderParticles = false;
  60163. this._multiRenderTarget.renderList = null;
  60164. // set default depth value to 1.0 (far away)
  60165. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60166. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60167. });
  60168. // Custom render function
  60169. var renderSubMesh = function (subMesh) {
  60170. var mesh = subMesh.getRenderingMesh();
  60171. var scene = _this._scene;
  60172. var engine = scene.getEngine();
  60173. var material = subMesh.getMaterial();
  60174. if (!material) {
  60175. return;
  60176. }
  60177. // Culling
  60178. engine.setState(material.backFaceCulling);
  60179. // Managing instances
  60180. var batch = mesh._getInstancesRenderList(subMesh._id);
  60181. if (batch.mustReturn) {
  60182. return;
  60183. }
  60184. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60185. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60186. engine.enableEffect(_this._effect);
  60187. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60188. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60189. _this._effect.setMatrix("view", scene.getViewMatrix());
  60190. // Alpha test
  60191. if (material && material.needAlphaTesting()) {
  60192. var alphaTexture = material.getAlphaTestTexture();
  60193. if (alphaTexture) {
  60194. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60195. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60196. }
  60197. }
  60198. // Bones
  60199. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60200. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60201. }
  60202. // Draw
  60203. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60204. }
  60205. };
  60206. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60207. var index;
  60208. if (depthOnlySubMeshes.length) {
  60209. engine.setColorWrite(false);
  60210. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60211. renderSubMesh(depthOnlySubMeshes.data[index]);
  60212. }
  60213. engine.setColorWrite(true);
  60214. }
  60215. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60216. renderSubMesh(opaqueSubMeshes.data[index]);
  60217. }
  60218. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60219. renderSubMesh(alphaTestSubMeshes.data[index]);
  60220. }
  60221. };
  60222. };
  60223. return GeometryBufferRenderer;
  60224. }());
  60225. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60226. })(BABYLON || (BABYLON = {}));
  60227. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60228. var BABYLON;
  60229. (function (BABYLON) {
  60230. var RefractionPostProcess = /** @class */ (function (_super) {
  60231. __extends(RefractionPostProcess, _super);
  60232. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60233. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60234. _this.color = color;
  60235. _this.depth = depth;
  60236. _this.colorLevel = colorLevel;
  60237. _this.onActivateObservable.add(function (cam) {
  60238. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60239. });
  60240. _this.onApplyObservable.add(function (effect) {
  60241. effect.setColor3("baseColor", _this.color);
  60242. effect.setFloat("depth", _this.depth);
  60243. effect.setFloat("colorLevel", _this.colorLevel);
  60244. effect.setTexture("refractionSampler", _this._refRexture);
  60245. });
  60246. return _this;
  60247. }
  60248. // Methods
  60249. RefractionPostProcess.prototype.dispose = function (camera) {
  60250. if (this._refRexture) {
  60251. this._refRexture.dispose();
  60252. }
  60253. _super.prototype.dispose.call(this, camera);
  60254. };
  60255. return RefractionPostProcess;
  60256. }(BABYLON.PostProcess));
  60257. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60258. })(BABYLON || (BABYLON = {}));
  60259. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60260. var BABYLON;
  60261. (function (BABYLON) {
  60262. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60263. __extends(BlackAndWhitePostProcess, _super);
  60264. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60265. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60266. _this.degree = 1;
  60267. _this.onApplyObservable.add(function (effect) {
  60268. effect.setFloat("degree", _this.degree);
  60269. });
  60270. return _this;
  60271. }
  60272. return BlackAndWhitePostProcess;
  60273. }(BABYLON.PostProcess));
  60274. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60275. })(BABYLON || (BABYLON = {}));
  60276. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60277. var BABYLON;
  60278. (function (BABYLON) {
  60279. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60280. __extends(ConvolutionPostProcess, _super);
  60281. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60282. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60283. _this.kernel = kernel;
  60284. _this.onApply = function (effect) {
  60285. effect.setFloat2("screenSize", _this.width, _this.height);
  60286. effect.setArray("kernel", _this.kernel);
  60287. };
  60288. return _this;
  60289. }
  60290. // Statics
  60291. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60292. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60293. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60294. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60295. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60296. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60297. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60298. return ConvolutionPostProcess;
  60299. }(BABYLON.PostProcess));
  60300. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60301. })(BABYLON || (BABYLON = {}));
  60302. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60303. var BABYLON;
  60304. (function (BABYLON) {
  60305. var FilterPostProcess = /** @class */ (function (_super) {
  60306. __extends(FilterPostProcess, _super);
  60307. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60308. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60309. _this.kernelMatrix = kernelMatrix;
  60310. _this.onApply = function (effect) {
  60311. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60312. };
  60313. return _this;
  60314. }
  60315. return FilterPostProcess;
  60316. }(BABYLON.PostProcess));
  60317. BABYLON.FilterPostProcess = FilterPostProcess;
  60318. })(BABYLON || (BABYLON = {}));
  60319. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60320. var BABYLON;
  60321. (function (BABYLON) {
  60322. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60323. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60324. __extends(VolumetricLightScatteringPostProcess, _super);
  60325. /**
  60326. * @constructor
  60327. * @param {string} name - The post-process name
  60328. * @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)
  60329. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60330. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60331. * @param {number} samples - The post-process quality, default 100
  60332. * @param {number} samplingMode - The post-process filtering mode
  60333. * @param {BABYLON.Engine} engine - The babylon engine
  60334. * @param {boolean} reusable - If the post-process is reusable
  60335. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60336. */
  60337. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60338. if (samples === void 0) { samples = 100; }
  60339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60340. 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;
  60341. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60342. /**
  60343. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60344. * @type {Vector3}
  60345. */
  60346. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60347. /**
  60348. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60349. * @type {boolean}
  60350. */
  60351. _this.useCustomMeshPosition = false;
  60352. /**
  60353. * If the post-process should inverse the light scattering direction
  60354. * @type {boolean}
  60355. */
  60356. _this.invert = true;
  60357. /**
  60358. * Array containing the excluded meshes not rendered in the internal pass
  60359. */
  60360. _this.excludedMeshes = new Array();
  60361. /**
  60362. * Controls the overall intensity of the post-process
  60363. * @type {number}
  60364. */
  60365. _this.exposure = 0.3;
  60366. /**
  60367. * Dissipates each sample's contribution in range [0, 1]
  60368. * @type {number}
  60369. */
  60370. _this.decay = 0.96815;
  60371. /**
  60372. * Controls the overall intensity of each sample
  60373. * @type {number}
  60374. */
  60375. _this.weight = 0.58767;
  60376. /**
  60377. * Controls the density of each sample
  60378. * @type {number}
  60379. */
  60380. _this.density = 0.926;
  60381. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60382. engine = scene.getEngine();
  60383. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60384. // Configure mesh
  60385. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60386. // Configure
  60387. _this._createPass(scene, ratio.passRatio || ratio);
  60388. _this.onActivate = function (camera) {
  60389. if (!_this.isSupported) {
  60390. _this.dispose(camera);
  60391. }
  60392. _this.onActivate = null;
  60393. };
  60394. _this.onApplyObservable.add(function (effect) {
  60395. _this._updateMeshScreenCoordinates(scene);
  60396. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60397. effect.setFloat("exposure", _this.exposure);
  60398. effect.setFloat("decay", _this.decay);
  60399. effect.setFloat("weight", _this.weight);
  60400. effect.setFloat("density", _this.density);
  60401. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60402. });
  60403. return _this;
  60404. }
  60405. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60406. get: function () {
  60407. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60408. return false;
  60409. },
  60410. set: function (useDiffuseColor) {
  60411. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60412. },
  60413. enumerable: true,
  60414. configurable: true
  60415. });
  60416. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60417. return "VolumetricLightScatteringPostProcess";
  60418. };
  60419. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60420. var mesh = subMesh.getMesh();
  60421. // Render this.mesh as default
  60422. if (mesh === this.mesh && mesh.material) {
  60423. return mesh.material.isReady(mesh);
  60424. }
  60425. var defines = [];
  60426. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60427. var material = subMesh.getMaterial();
  60428. // Alpha test
  60429. if (material) {
  60430. if (material.needAlphaTesting()) {
  60431. defines.push("#define ALPHATEST");
  60432. }
  60433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60434. attribs.push(BABYLON.VertexBuffer.UVKind);
  60435. defines.push("#define UV1");
  60436. }
  60437. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60438. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60439. defines.push("#define UV2");
  60440. }
  60441. }
  60442. // Bones
  60443. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60444. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60445. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60446. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60447. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60448. }
  60449. else {
  60450. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60451. }
  60452. // Instances
  60453. if (useInstances) {
  60454. defines.push("#define INSTANCES");
  60455. attribs.push("world0");
  60456. attribs.push("world1");
  60457. attribs.push("world2");
  60458. attribs.push("world3");
  60459. }
  60460. // Get correct effect
  60461. var join = defines.join("\n");
  60462. if (this._cachedDefines !== join) {
  60463. this._cachedDefines = join;
  60464. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60465. }
  60466. return this._volumetricLightScatteringPass.isReady();
  60467. };
  60468. /**
  60469. * Sets the new light position for light scattering effect
  60470. * @param {BABYLON.Vector3} The new custom light position
  60471. */
  60472. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60473. this.customMeshPosition = position;
  60474. };
  60475. /**
  60476. * Returns the light position for light scattering effect
  60477. * @return {BABYLON.Vector3} The custom light position
  60478. */
  60479. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60480. return this.customMeshPosition;
  60481. };
  60482. /**
  60483. * Disposes the internal assets and detaches the post-process from the camera
  60484. */
  60485. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60486. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60487. if (rttIndex !== -1) {
  60488. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60489. }
  60490. this._volumetricLightScatteringRTT.dispose();
  60491. _super.prototype.dispose.call(this, camera);
  60492. };
  60493. /**
  60494. * Returns the render target texture used by the post-process
  60495. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60496. */
  60497. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60498. return this._volumetricLightScatteringRTT;
  60499. };
  60500. // Private methods
  60501. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60502. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60503. return true;
  60504. }
  60505. return false;
  60506. };
  60507. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60508. var _this = this;
  60509. var engine = scene.getEngine();
  60510. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60511. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60512. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60513. this._volumetricLightScatteringRTT.renderList = null;
  60514. this._volumetricLightScatteringRTT.renderParticles = false;
  60515. var camera = this.getCamera();
  60516. if (camera) {
  60517. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60518. }
  60519. else {
  60520. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60521. }
  60522. // Custom render function for submeshes
  60523. var renderSubMesh = function (subMesh) {
  60524. var mesh = subMesh.getRenderingMesh();
  60525. if (_this._meshExcluded(mesh)) {
  60526. return;
  60527. }
  60528. var material = subMesh.getMaterial();
  60529. if (!material) {
  60530. return;
  60531. }
  60532. var scene = mesh.getScene();
  60533. var engine = scene.getEngine();
  60534. // Culling
  60535. engine.setState(material.backFaceCulling);
  60536. // Managing instances
  60537. var batch = mesh._getInstancesRenderList(subMesh._id);
  60538. if (batch.mustReturn) {
  60539. return;
  60540. }
  60541. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60542. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60543. var effect = _this._volumetricLightScatteringPass;
  60544. if (mesh === _this.mesh) {
  60545. if (subMesh.effect) {
  60546. effect = subMesh.effect;
  60547. }
  60548. else {
  60549. effect = material.getEffect();
  60550. }
  60551. }
  60552. engine.enableEffect(effect);
  60553. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60554. if (mesh === _this.mesh) {
  60555. material.bind(mesh.getWorldMatrix(), mesh);
  60556. }
  60557. else {
  60558. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60559. // Alpha test
  60560. if (material && material.needAlphaTesting()) {
  60561. var alphaTexture = material.getAlphaTestTexture();
  60562. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60563. if (alphaTexture) {
  60564. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60565. }
  60566. }
  60567. // Bones
  60568. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60569. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60570. }
  60571. }
  60572. // Draw
  60573. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60574. }
  60575. };
  60576. // Render target texture callbacks
  60577. var savedSceneClearColor;
  60578. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60579. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60580. savedSceneClearColor = scene.clearColor;
  60581. scene.clearColor = sceneClearColor;
  60582. });
  60583. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60584. scene.clearColor = savedSceneClearColor;
  60585. });
  60586. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60587. var engine = scene.getEngine();
  60588. var index;
  60589. if (depthOnlySubMeshes.length) {
  60590. engine.setColorWrite(false);
  60591. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60592. renderSubMesh(depthOnlySubMeshes.data[index]);
  60593. }
  60594. engine.setColorWrite(true);
  60595. }
  60596. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60597. renderSubMesh(opaqueSubMeshes.data[index]);
  60598. }
  60599. engine.setAlphaTesting(true);
  60600. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60601. renderSubMesh(alphaTestSubMeshes.data[index]);
  60602. }
  60603. engine.setAlphaTesting(false);
  60604. if (transparentSubMeshes.length) {
  60605. // Sort sub meshes
  60606. for (index = 0; index < transparentSubMeshes.length; index++) {
  60607. var submesh = transparentSubMeshes.data[index];
  60608. var boundingInfo = submesh.getBoundingInfo();
  60609. if (boundingInfo && scene.activeCamera) {
  60610. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60611. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60612. }
  60613. }
  60614. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60615. sortedArray.sort(function (a, b) {
  60616. // Alpha index first
  60617. if (a._alphaIndex > b._alphaIndex) {
  60618. return 1;
  60619. }
  60620. if (a._alphaIndex < b._alphaIndex) {
  60621. return -1;
  60622. }
  60623. // Then distance to camera
  60624. if (a._distanceToCamera < b._distanceToCamera) {
  60625. return 1;
  60626. }
  60627. if (a._distanceToCamera > b._distanceToCamera) {
  60628. return -1;
  60629. }
  60630. return 0;
  60631. });
  60632. // Render sub meshes
  60633. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60634. for (index = 0; index < sortedArray.length; index++) {
  60635. renderSubMesh(sortedArray[index]);
  60636. }
  60637. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60638. }
  60639. };
  60640. };
  60641. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60642. var transform = scene.getTransformMatrix();
  60643. var meshPosition;
  60644. if (this.useCustomMeshPosition) {
  60645. meshPosition = this.customMeshPosition;
  60646. }
  60647. else if (this.attachedNode) {
  60648. meshPosition = this.attachedNode.position;
  60649. }
  60650. else {
  60651. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60652. }
  60653. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60654. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60655. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60656. if (this.invert)
  60657. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60658. };
  60659. // Static methods
  60660. /**
  60661. * Creates a default mesh for the Volumeric Light Scattering post-process
  60662. * @param {string} The mesh name
  60663. * @param {BABYLON.Scene} The scene where to create the mesh
  60664. * @return {BABYLON.Mesh} the default mesh
  60665. */
  60666. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60667. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60668. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60669. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60670. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60671. mesh.material = material;
  60672. return mesh;
  60673. };
  60674. __decorate([
  60675. BABYLON.serializeAsVector3()
  60676. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60677. __decorate([
  60678. BABYLON.serialize()
  60679. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60680. __decorate([
  60681. BABYLON.serialize()
  60682. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60683. __decorate([
  60684. BABYLON.serializeAsMeshReference()
  60685. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60686. __decorate([
  60687. BABYLON.serialize()
  60688. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60689. __decorate([
  60690. BABYLON.serialize()
  60691. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60692. __decorate([
  60693. BABYLON.serialize()
  60694. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60695. __decorate([
  60696. BABYLON.serialize()
  60697. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60698. __decorate([
  60699. BABYLON.serialize()
  60700. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60701. return VolumetricLightScatteringPostProcess;
  60702. }(BABYLON.PostProcess));
  60703. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60704. })(BABYLON || (BABYLON = {}));
  60705. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60706. //
  60707. // This post-process allows the modification of rendered colors by using
  60708. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60709. //
  60710. // The object needs to be provided an url to a texture containing the color
  60711. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60712. // Use an image editing software to tweak the LUT to match your needs.
  60713. //
  60714. // For an example of a color LUT, see here:
  60715. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60716. // For explanations on color grading, see here:
  60717. // http://udn.epicgames.com/Three/ColorGrading.html
  60718. //
  60719. var BABYLON;
  60720. (function (BABYLON) {
  60721. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60722. __extends(ColorCorrectionPostProcess, _super);
  60723. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60724. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60725. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60726. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60727. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60728. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60729. _this.onApply = function (effect) {
  60730. effect.setTexture("colorTable", _this._colorTableTexture);
  60731. };
  60732. return _this;
  60733. }
  60734. return ColorCorrectionPostProcess;
  60735. }(BABYLON.PostProcess));
  60736. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60737. })(BABYLON || (BABYLON = {}));
  60738. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60739. var BABYLON;
  60740. (function (BABYLON) {
  60741. var TonemappingOperator;
  60742. (function (TonemappingOperator) {
  60743. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60744. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60745. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60746. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60747. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60748. ;
  60749. var TonemapPostProcess = /** @class */ (function (_super) {
  60750. __extends(TonemapPostProcess, _super);
  60751. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60753. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60754. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60755. _this._operator = _operator;
  60756. _this.exposureAdjustment = exposureAdjustment;
  60757. var defines = "#define ";
  60758. if (_this._operator === TonemappingOperator.Hable)
  60759. defines += "HABLE_TONEMAPPING";
  60760. else if (_this._operator === TonemappingOperator.Reinhard)
  60761. defines += "REINHARD_TONEMAPPING";
  60762. else if (_this._operator === TonemappingOperator.HejiDawson)
  60763. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60764. else if (_this._operator === TonemappingOperator.Photographic)
  60765. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60766. //sadly a second call to create the effect.
  60767. _this.updateEffect(defines);
  60768. _this.onApply = function (effect) {
  60769. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60770. };
  60771. return _this;
  60772. }
  60773. return TonemapPostProcess;
  60774. }(BABYLON.PostProcess));
  60775. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60776. })(BABYLON || (BABYLON = {}));
  60777. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60778. var BABYLON;
  60779. (function (BABYLON) {
  60780. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60781. __extends(DisplayPassPostProcess, _super);
  60782. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60783. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60784. }
  60785. return DisplayPassPostProcess;
  60786. }(BABYLON.PostProcess));
  60787. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60788. })(BABYLON || (BABYLON = {}));
  60789. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60790. var BABYLON;
  60791. (function (BABYLON) {
  60792. var HighlightsPostProcess = /** @class */ (function (_super) {
  60793. __extends(HighlightsPostProcess, _super);
  60794. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60796. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60797. }
  60798. return HighlightsPostProcess;
  60799. }(BABYLON.PostProcess));
  60800. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60801. })(BABYLON || (BABYLON = {}));
  60802. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60803. var BABYLON;
  60804. (function (BABYLON) {
  60805. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60806. __extends(ImageProcessingPostProcess, _super);
  60807. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  60808. if (camera === void 0) { camera = null; }
  60809. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60810. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60811. _this._fromLinearSpace = true;
  60812. /**
  60813. * Defines cache preventing GC.
  60814. */
  60815. _this._defines = {
  60816. IMAGEPROCESSING: false,
  60817. VIGNETTE: false,
  60818. VIGNETTEBLENDMODEMULTIPLY: false,
  60819. VIGNETTEBLENDMODEOPAQUE: false,
  60820. TONEMAPPING: false,
  60821. CONTRAST: false,
  60822. COLORCURVES: false,
  60823. COLORGRADING: false,
  60824. COLORGRADING3D: false,
  60825. FROMLINEARSPACE: false,
  60826. SAMPLER3DGREENDEPTH: false,
  60827. SAMPLER3DBGRMAP: false,
  60828. IMAGEPROCESSINGPOSTPROCESS: false,
  60829. EXPOSURE: false,
  60830. };
  60831. // Setup the configuration as forced by the constructor. This would then not force the
  60832. // scene materials output in linear space and let untouched the default forward pass.
  60833. if (imageProcessingConfiguration) {
  60834. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  60835. _this.imageProcessingConfiguration.applyByPostProcess = false;
  60836. _this.fromLinearSpace = false;
  60837. }
  60838. else {
  60839. _this._attachImageProcessingConfiguration(null, true);
  60840. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60841. }
  60842. _this.onApply = function (effect) {
  60843. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60844. };
  60845. return _this;
  60846. }
  60847. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60848. /**
  60849. * Gets the image processing configuration used either in this material.
  60850. */
  60851. get: function () {
  60852. return this._imageProcessingConfiguration;
  60853. },
  60854. /**
  60855. * Sets the Default image processing configuration used either in the this material.
  60856. *
  60857. * If sets to null, the scene one is in use.
  60858. */
  60859. set: function (value) {
  60860. this._attachImageProcessingConfiguration(value);
  60861. },
  60862. enumerable: true,
  60863. configurable: true
  60864. });
  60865. /**
  60866. * Attaches a new image processing configuration to the PBR Material.
  60867. * @param configuration
  60868. */
  60869. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60870. var _this = this;
  60871. if (doNotBuild === void 0) { doNotBuild = false; }
  60872. if (configuration === this._imageProcessingConfiguration) {
  60873. return;
  60874. }
  60875. // Detaches observer.
  60876. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60877. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60878. }
  60879. // Pick the scene configuration if needed.
  60880. if (!configuration) {
  60881. var scene = null;
  60882. var engine = this.getEngine();
  60883. var camera = this.getCamera();
  60884. if (camera) {
  60885. scene = camera.getScene();
  60886. }
  60887. else if (engine && engine.scenes) {
  60888. var scenes = engine.scenes;
  60889. scene = scenes[scenes.length - 1];
  60890. }
  60891. else {
  60892. scene = BABYLON.Engine.LastCreatedScene;
  60893. }
  60894. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60895. }
  60896. else {
  60897. this._imageProcessingConfiguration = configuration;
  60898. }
  60899. // Attaches observer.
  60900. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60901. _this._updateParameters();
  60902. });
  60903. // Ensure the effect will be rebuilt.
  60904. if (!doNotBuild) {
  60905. this._updateParameters();
  60906. }
  60907. };
  60908. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60909. /**
  60910. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60911. */
  60912. get: function () {
  60913. return this.imageProcessingConfiguration.colorCurves;
  60914. },
  60915. /**
  60916. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60917. */
  60918. set: function (value) {
  60919. this.imageProcessingConfiguration.colorCurves = value;
  60920. },
  60921. enumerable: true,
  60922. configurable: true
  60923. });
  60924. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60925. /**
  60926. * Gets wether the color curves effect is enabled.
  60927. */
  60928. get: function () {
  60929. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60930. },
  60931. /**
  60932. * Sets wether the color curves effect is enabled.
  60933. */
  60934. set: function (value) {
  60935. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60936. },
  60937. enumerable: true,
  60938. configurable: true
  60939. });
  60940. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60941. /**
  60942. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60943. */
  60944. get: function () {
  60945. return this.imageProcessingConfiguration.colorGradingTexture;
  60946. },
  60947. /**
  60948. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60949. */
  60950. set: function (value) {
  60951. this.imageProcessingConfiguration.colorGradingTexture = value;
  60952. },
  60953. enumerable: true,
  60954. configurable: true
  60955. });
  60956. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60957. /**
  60958. * Gets wether the color grading effect is enabled.
  60959. */
  60960. get: function () {
  60961. return this.imageProcessingConfiguration.colorGradingEnabled;
  60962. },
  60963. /**
  60964. * Gets wether the color grading effect is enabled.
  60965. */
  60966. set: function (value) {
  60967. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60968. },
  60969. enumerable: true,
  60970. configurable: true
  60971. });
  60972. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60973. /**
  60974. * Gets exposure used in the effect.
  60975. */
  60976. get: function () {
  60977. return this.imageProcessingConfiguration.exposure;
  60978. },
  60979. /**
  60980. * Sets exposure used in the effect.
  60981. */
  60982. set: function (value) {
  60983. this.imageProcessingConfiguration.exposure = value;
  60984. },
  60985. enumerable: true,
  60986. configurable: true
  60987. });
  60988. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60989. /**
  60990. * Gets wether tonemapping is enabled or not.
  60991. */
  60992. get: function () {
  60993. return this._imageProcessingConfiguration.toneMappingEnabled;
  60994. },
  60995. /**
  60996. * Sets wether tonemapping is enabled or not
  60997. */
  60998. set: function (value) {
  60999. this._imageProcessingConfiguration.toneMappingEnabled = value;
  61000. },
  61001. enumerable: true,
  61002. configurable: true
  61003. });
  61004. ;
  61005. ;
  61006. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  61007. /**
  61008. * Gets contrast used in the effect.
  61009. */
  61010. get: function () {
  61011. return this.imageProcessingConfiguration.contrast;
  61012. },
  61013. /**
  61014. * Sets contrast used in the effect.
  61015. */
  61016. set: function (value) {
  61017. this.imageProcessingConfiguration.contrast = value;
  61018. },
  61019. enumerable: true,
  61020. configurable: true
  61021. });
  61022. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  61023. /**
  61024. * Gets Vignette stretch size.
  61025. */
  61026. get: function () {
  61027. return this.imageProcessingConfiguration.vignetteStretch;
  61028. },
  61029. /**
  61030. * Sets Vignette stretch size.
  61031. */
  61032. set: function (value) {
  61033. this.imageProcessingConfiguration.vignetteStretch = value;
  61034. },
  61035. enumerable: true,
  61036. configurable: true
  61037. });
  61038. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  61039. /**
  61040. * Gets Vignette centre X Offset.
  61041. */
  61042. get: function () {
  61043. return this.imageProcessingConfiguration.vignetteCentreX;
  61044. },
  61045. /**
  61046. * Sets Vignette centre X Offset.
  61047. */
  61048. set: function (value) {
  61049. this.imageProcessingConfiguration.vignetteCentreX = value;
  61050. },
  61051. enumerable: true,
  61052. configurable: true
  61053. });
  61054. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  61055. /**
  61056. * Gets Vignette centre Y Offset.
  61057. */
  61058. get: function () {
  61059. return this.imageProcessingConfiguration.vignetteCentreY;
  61060. },
  61061. /**
  61062. * Sets Vignette centre Y Offset.
  61063. */
  61064. set: function (value) {
  61065. this.imageProcessingConfiguration.vignetteCentreY = value;
  61066. },
  61067. enumerable: true,
  61068. configurable: true
  61069. });
  61070. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  61071. /**
  61072. * Gets Vignette weight or intensity of the vignette effect.
  61073. */
  61074. get: function () {
  61075. return this.imageProcessingConfiguration.vignetteWeight;
  61076. },
  61077. /**
  61078. * Sets Vignette weight or intensity of the vignette effect.
  61079. */
  61080. set: function (value) {
  61081. this.imageProcessingConfiguration.vignetteWeight = value;
  61082. },
  61083. enumerable: true,
  61084. configurable: true
  61085. });
  61086. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  61087. /**
  61088. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61089. * if vignetteEnabled is set to true.
  61090. */
  61091. get: function () {
  61092. return this.imageProcessingConfiguration.vignetteColor;
  61093. },
  61094. /**
  61095. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61096. * if vignetteEnabled is set to true.
  61097. */
  61098. set: function (value) {
  61099. this.imageProcessingConfiguration.vignetteColor = value;
  61100. },
  61101. enumerable: true,
  61102. configurable: true
  61103. });
  61104. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61105. /**
  61106. * Gets Camera field of view used by the Vignette effect.
  61107. */
  61108. get: function () {
  61109. return this.imageProcessingConfiguration.vignetteCameraFov;
  61110. },
  61111. /**
  61112. * Sets Camera field of view used by the Vignette effect.
  61113. */
  61114. set: function (value) {
  61115. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61116. },
  61117. enumerable: true,
  61118. configurable: true
  61119. });
  61120. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61121. /**
  61122. * Gets the vignette blend mode allowing different kind of effect.
  61123. */
  61124. get: function () {
  61125. return this.imageProcessingConfiguration.vignetteBlendMode;
  61126. },
  61127. /**
  61128. * Sets the vignette blend mode allowing different kind of effect.
  61129. */
  61130. set: function (value) {
  61131. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61132. },
  61133. enumerable: true,
  61134. configurable: true
  61135. });
  61136. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61137. /**
  61138. * Gets wether the vignette effect is enabled.
  61139. */
  61140. get: function () {
  61141. return this.imageProcessingConfiguration.vignetteEnabled;
  61142. },
  61143. /**
  61144. * Sets wether the vignette effect is enabled.
  61145. */
  61146. set: function (value) {
  61147. this.imageProcessingConfiguration.vignetteEnabled = value;
  61148. },
  61149. enumerable: true,
  61150. configurable: true
  61151. });
  61152. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61153. /**
  61154. * Gets wether the input of the processing is in Gamma or Linear Space.
  61155. */
  61156. get: function () {
  61157. return this._fromLinearSpace;
  61158. },
  61159. /**
  61160. * Sets wether the input of the processing is in Gamma or Linear Space.
  61161. */
  61162. set: function (value) {
  61163. if (this._fromLinearSpace === value) {
  61164. return;
  61165. }
  61166. this._fromLinearSpace = value;
  61167. this._updateParameters();
  61168. },
  61169. enumerable: true,
  61170. configurable: true
  61171. });
  61172. ImageProcessingPostProcess.prototype.getClassName = function () {
  61173. return "ImageProcessingPostProcess";
  61174. };
  61175. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61176. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61177. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61178. var defines = "";
  61179. for (var define in this._defines) {
  61180. if (this._defines[define]) {
  61181. defines += "#define " + define + ";\r\n";
  61182. }
  61183. }
  61184. var samplers = ["textureSampler"];
  61185. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61186. var uniforms = ["scale"];
  61187. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61188. this.updateEffect(defines, uniforms, samplers);
  61189. };
  61190. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61191. _super.prototype.dispose.call(this, camera);
  61192. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61193. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61194. }
  61195. this.imageProcessingConfiguration.applyByPostProcess = false;
  61196. };
  61197. __decorate([
  61198. BABYLON.serialize()
  61199. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61200. return ImageProcessingPostProcess;
  61201. }(BABYLON.PostProcess));
  61202. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61203. })(BABYLON || (BABYLON = {}));
  61204. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61205. var BABYLON;
  61206. (function (BABYLON) {
  61207. var BlurPostProcess = /** @class */ (function (_super) {
  61208. __extends(BlurPostProcess, _super);
  61209. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61211. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61212. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61213. _this.direction = direction;
  61214. _this._packedFloat = false;
  61215. _this.onApplyObservable.add(function (effect) {
  61216. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61217. });
  61218. _this.kernel = kernel;
  61219. return _this;
  61220. }
  61221. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61222. /**
  61223. * Gets the length in pixels of the blur sample region
  61224. */
  61225. get: function () {
  61226. return this._idealKernel;
  61227. },
  61228. /**
  61229. * Sets the length in pixels of the blur sample region
  61230. */
  61231. set: function (v) {
  61232. if (this._idealKernel === v) {
  61233. return;
  61234. }
  61235. v = Math.max(v, 1);
  61236. this._idealKernel = v;
  61237. this._kernel = this._nearestBestKernel(v);
  61238. this._updateParameters();
  61239. },
  61240. enumerable: true,
  61241. configurable: true
  61242. });
  61243. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61244. /**
  61245. * Gets wether or not the blur is unpacking/repacking floats
  61246. */
  61247. get: function () {
  61248. return this._packedFloat;
  61249. },
  61250. /**
  61251. * Sets wether or not the blur needs to unpack/repack floats
  61252. */
  61253. set: function (v) {
  61254. if (this._packedFloat === v) {
  61255. return;
  61256. }
  61257. this._packedFloat = v;
  61258. this._updateParameters();
  61259. },
  61260. enumerable: true,
  61261. configurable: true
  61262. });
  61263. BlurPostProcess.prototype._updateParameters = function () {
  61264. // Generate sampling offsets and weights
  61265. var N = this._kernel;
  61266. var centerIndex = (N - 1) / 2;
  61267. // Generate Gaussian sampling weights over kernel
  61268. var offsets = [];
  61269. var weights = [];
  61270. var totalWeight = 0;
  61271. for (var i = 0; i < N; i++) {
  61272. var u = i / (N - 1);
  61273. var w = this._gaussianWeight(u * 2.0 - 1);
  61274. offsets[i] = (i - centerIndex);
  61275. weights[i] = w;
  61276. totalWeight += w;
  61277. }
  61278. // Normalize weights
  61279. for (var i = 0; i < weights.length; i++) {
  61280. weights[i] /= totalWeight;
  61281. }
  61282. // Optimize: combine samples to take advantage of hardware linear sampling
  61283. // Walk from left to center, combining pairs (symmetrically)
  61284. var linearSamplingWeights = [];
  61285. var linearSamplingOffsets = [];
  61286. var linearSamplingMap = [];
  61287. for (var i = 0; i <= centerIndex; i += 2) {
  61288. var j = Math.min(i + 1, Math.floor(centerIndex));
  61289. var singleCenterSample = i === j;
  61290. if (singleCenterSample) {
  61291. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61292. }
  61293. else {
  61294. var sharedCell = j === centerIndex;
  61295. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61296. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61297. if (offsetLinear === 0) {
  61298. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61299. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61300. }
  61301. else {
  61302. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61303. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61304. }
  61305. }
  61306. }
  61307. for (var i = 0; i < linearSamplingMap.length; i++) {
  61308. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61309. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61310. }
  61311. // Replace with optimized
  61312. offsets = linearSamplingOffsets;
  61313. weights = linearSamplingWeights;
  61314. // Generate shaders
  61315. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61316. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61317. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61318. var defines = "";
  61319. for (var i = 0; i < varyingCount; i++) {
  61320. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61321. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61322. }
  61323. var depCount = 0;
  61324. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61325. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61326. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61327. depCount++;
  61328. }
  61329. if (this.packedFloat) {
  61330. defines += "#define PACKEDFLOAT 1";
  61331. }
  61332. this.updateEffect(defines, null, null, {
  61333. varyingCount: varyingCount,
  61334. depCount: depCount
  61335. });
  61336. };
  61337. /**
  61338. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61339. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61340. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61341. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61342. * The gaps between physical kernels are compensated for in the weighting of the samples
  61343. * @param idealKernel Ideal blur kernel.
  61344. * @return Nearest best kernel.
  61345. */
  61346. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61347. var v = Math.round(idealKernel);
  61348. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61349. var k = _a[_i];
  61350. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61351. return Math.max(k, 3);
  61352. }
  61353. }
  61354. return Math.max(v, 3);
  61355. };
  61356. /**
  61357. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61358. * @param x The point on the Gaussian distribution to sample.
  61359. * @return the value of the Gaussian function at x.
  61360. */
  61361. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61362. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61363. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61364. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61365. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61366. // truncated at around 1.3% of peak strength.
  61367. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61368. var sigma = (1 / 3);
  61369. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61370. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61371. var weight = (1.0 / denominator) * Math.exp(exponent);
  61372. return weight;
  61373. };
  61374. /**
  61375. * Generates a string that can be used as a floating point number in GLSL.
  61376. * @param x Value to print.
  61377. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61378. * @return GLSL float string.
  61379. */
  61380. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61381. if (decimalFigures === void 0) { decimalFigures = 8; }
  61382. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61383. };
  61384. return BlurPostProcess;
  61385. }(BABYLON.PostProcess));
  61386. BABYLON.BlurPostProcess = BlurPostProcess;
  61387. })(BABYLON || (BABYLON = {}));
  61388. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61389. var BABYLON;
  61390. (function (BABYLON) {
  61391. var Bone = /** @class */ (function (_super) {
  61392. __extends(Bone, _super);
  61393. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61394. if (parentBone === void 0) { parentBone = null; }
  61395. if (localMatrix === void 0) { localMatrix = null; }
  61396. if (restPose === void 0) { restPose = null; }
  61397. if (baseMatrix === void 0) { baseMatrix = null; }
  61398. if (index === void 0) { index = null; }
  61399. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61400. _this.name = name;
  61401. _this.children = new Array();
  61402. _this.animations = new Array();
  61403. // Set this value to map this bone to a different index in the transform matrices.
  61404. // Set this value to -1 to exclude the bone from the transform matrices.
  61405. _this._index = null;
  61406. _this._worldTransform = new BABYLON.Matrix();
  61407. _this._absoluteTransform = new BABYLON.Matrix();
  61408. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61409. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61410. _this._scaleVector = BABYLON.Vector3.One();
  61411. _this._negateScaleChildren = BABYLON.Vector3.One();
  61412. _this._scalingDeterminant = 1;
  61413. _this._skeleton = skeleton;
  61414. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61415. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61416. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61417. _this._index = index;
  61418. skeleton.bones.push(_this);
  61419. _this.setParent(parentBone, false);
  61420. _this._updateDifferenceMatrix();
  61421. return _this;
  61422. }
  61423. Object.defineProperty(Bone.prototype, "_matrix", {
  61424. get: function () {
  61425. return this._localMatrix;
  61426. },
  61427. set: function (val) {
  61428. if (this._localMatrix) {
  61429. this._localMatrix.copyFrom(val);
  61430. }
  61431. else {
  61432. this._localMatrix = val;
  61433. }
  61434. },
  61435. enumerable: true,
  61436. configurable: true
  61437. });
  61438. // Members
  61439. Bone.prototype.getSkeleton = function () {
  61440. return this._skeleton;
  61441. };
  61442. Bone.prototype.getParent = function () {
  61443. return this._parent;
  61444. };
  61445. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61446. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61447. if (this._parent === parent) {
  61448. return;
  61449. }
  61450. if (this._parent) {
  61451. var index = this._parent.children.indexOf(this);
  61452. if (index !== -1) {
  61453. this._parent.children.splice(index, 1);
  61454. }
  61455. }
  61456. this._parent = parent;
  61457. if (this._parent) {
  61458. this._parent.children.push(this);
  61459. }
  61460. if (updateDifferenceMatrix) {
  61461. this._updateDifferenceMatrix();
  61462. }
  61463. };
  61464. Bone.prototype.getLocalMatrix = function () {
  61465. return this._localMatrix;
  61466. };
  61467. Bone.prototype.getBaseMatrix = function () {
  61468. return this._baseMatrix;
  61469. };
  61470. Bone.prototype.getRestPose = function () {
  61471. return this._restPose;
  61472. };
  61473. Bone.prototype.returnToRest = function () {
  61474. this.updateMatrix(this._restPose.clone());
  61475. };
  61476. Bone.prototype.getWorldMatrix = function () {
  61477. return this._worldTransform;
  61478. };
  61479. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61480. return this._invertedAbsoluteTransform;
  61481. };
  61482. Bone.prototype.getAbsoluteTransform = function () {
  61483. return this._absoluteTransform;
  61484. };
  61485. Object.defineProperty(Bone.prototype, "position", {
  61486. // Properties (matches AbstractMesh properties)
  61487. get: function () {
  61488. return this.getPosition();
  61489. },
  61490. set: function (newPosition) {
  61491. this.setPosition(newPosition);
  61492. },
  61493. enumerable: true,
  61494. configurable: true
  61495. });
  61496. Object.defineProperty(Bone.prototype, "rotation", {
  61497. get: function () {
  61498. return this.getRotation();
  61499. },
  61500. set: function (newRotation) {
  61501. this.setRotation(newRotation);
  61502. },
  61503. enumerable: true,
  61504. configurable: true
  61505. });
  61506. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61507. get: function () {
  61508. return this.getRotationQuaternion();
  61509. },
  61510. set: function (newRotation) {
  61511. this.setRotationQuaternion(newRotation);
  61512. },
  61513. enumerable: true,
  61514. configurable: true
  61515. });
  61516. Object.defineProperty(Bone.prototype, "scaling", {
  61517. get: function () {
  61518. return this.getScale();
  61519. },
  61520. set: function (newScaling) {
  61521. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61522. },
  61523. enumerable: true,
  61524. configurable: true
  61525. });
  61526. // Methods
  61527. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61528. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61529. this._baseMatrix = matrix.clone();
  61530. this._localMatrix = matrix.clone();
  61531. this._skeleton._markAsDirty();
  61532. if (updateDifferenceMatrix) {
  61533. this._updateDifferenceMatrix();
  61534. }
  61535. };
  61536. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61537. if (!rootMatrix) {
  61538. rootMatrix = this._baseMatrix;
  61539. }
  61540. if (this._parent) {
  61541. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61542. }
  61543. else {
  61544. this._absoluteTransform.copyFrom(rootMatrix);
  61545. }
  61546. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61547. for (var index = 0; index < this.children.length; index++) {
  61548. this.children[index]._updateDifferenceMatrix();
  61549. }
  61550. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61551. };
  61552. Bone.prototype.markAsDirty = function () {
  61553. this._currentRenderId++;
  61554. this._skeleton._markAsDirty();
  61555. };
  61556. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61557. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61558. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61559. // all animation may be coming from a library skeleton, so may need to create animation
  61560. if (this.animations.length === 0) {
  61561. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61562. this.animations[0].setKeys([]);
  61563. }
  61564. // get animation info / verify there is such a range from the source bone
  61565. var sourceRange = source.animations[0].getRange(rangeName);
  61566. if (!sourceRange) {
  61567. return false;
  61568. }
  61569. var from = sourceRange.from;
  61570. var to = sourceRange.to;
  61571. var sourceKeys = source.animations[0].getKeys();
  61572. // rescaling prep
  61573. var sourceBoneLength = source.length;
  61574. var sourceParent = source.getParent();
  61575. var parent = this.getParent();
  61576. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61577. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61578. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61579. var destKeys = this.animations[0].getKeys();
  61580. // loop vars declaration
  61581. var orig;
  61582. var origTranslation;
  61583. var mat;
  61584. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61585. orig = sourceKeys[key];
  61586. if (orig.frame >= from && orig.frame <= to) {
  61587. if (rescaleAsRequired) {
  61588. mat = orig.value.clone();
  61589. // scale based on parent ratio, when bone has parent
  61590. if (parentScalingReqd) {
  61591. origTranslation = mat.getTranslation();
  61592. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61593. // scale based on skeleton dimension ratio when root bone, and value is passed
  61594. }
  61595. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61596. origTranslation = mat.getTranslation();
  61597. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61598. // use original when root bone, and no data for skelDimensionsRatio
  61599. }
  61600. else {
  61601. mat = orig.value;
  61602. }
  61603. }
  61604. else {
  61605. mat = orig.value;
  61606. }
  61607. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61608. }
  61609. }
  61610. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61611. return true;
  61612. };
  61613. /**
  61614. * Translate the bone in local or world space.
  61615. * @param vec The amount to translate the bone.
  61616. * @param space The space that the translation is in.
  61617. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61618. */
  61619. Bone.prototype.translate = function (vec, space, mesh) {
  61620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61621. var lm = this.getLocalMatrix();
  61622. if (space == BABYLON.Space.LOCAL) {
  61623. lm.m[12] += vec.x;
  61624. lm.m[13] += vec.y;
  61625. lm.m[14] += vec.z;
  61626. }
  61627. else {
  61628. var wm = null;
  61629. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61630. if (mesh) {
  61631. wm = mesh.getWorldMatrix();
  61632. }
  61633. this._skeleton.computeAbsoluteTransforms();
  61634. var tmat = Bone._tmpMats[0];
  61635. var tvec = Bone._tmpVecs[0];
  61636. if (this._parent) {
  61637. if (mesh && wm) {
  61638. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61639. tmat.multiplyToRef(wm, tmat);
  61640. }
  61641. else {
  61642. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61643. }
  61644. }
  61645. tmat.m[12] = 0;
  61646. tmat.m[13] = 0;
  61647. tmat.m[14] = 0;
  61648. tmat.invert();
  61649. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61650. lm.m[12] += tvec.x;
  61651. lm.m[13] += tvec.y;
  61652. lm.m[14] += tvec.z;
  61653. }
  61654. this.markAsDirty();
  61655. };
  61656. /**
  61657. * Set the postion of the bone in local or world space.
  61658. * @param position The position to set the bone.
  61659. * @param space The space that the position is in.
  61660. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61661. */
  61662. Bone.prototype.setPosition = function (position, space, mesh) {
  61663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61664. var lm = this.getLocalMatrix();
  61665. if (space == BABYLON.Space.LOCAL) {
  61666. lm.m[12] = position.x;
  61667. lm.m[13] = position.y;
  61668. lm.m[14] = position.z;
  61669. }
  61670. else {
  61671. var wm = null;
  61672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61673. if (mesh) {
  61674. wm = mesh.getWorldMatrix();
  61675. }
  61676. this._skeleton.computeAbsoluteTransforms();
  61677. var tmat = Bone._tmpMats[0];
  61678. var vec = Bone._tmpVecs[0];
  61679. if (this._parent) {
  61680. if (mesh && wm) {
  61681. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61682. tmat.multiplyToRef(wm, tmat);
  61683. }
  61684. else {
  61685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61686. }
  61687. }
  61688. tmat.invert();
  61689. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61690. lm.m[12] = vec.x;
  61691. lm.m[13] = vec.y;
  61692. lm.m[14] = vec.z;
  61693. }
  61694. this.markAsDirty();
  61695. };
  61696. /**
  61697. * Set the absolute postion of the bone (world space).
  61698. * @param position The position to set the bone.
  61699. * @param mesh The mesh that this bone is attached to.
  61700. */
  61701. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61702. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61703. };
  61704. /**
  61705. * Set the scale of the bone on the x, y and z axes.
  61706. * @param x The scale of the bone on the x axis.
  61707. * @param x The scale of the bone on the y axis.
  61708. * @param z The scale of the bone on the z axis.
  61709. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61710. */
  61711. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61712. if (scaleChildren === void 0) { scaleChildren = false; }
  61713. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61714. if (!scaleChildren) {
  61715. this._negateScaleChildren.x = 1 / x;
  61716. this._negateScaleChildren.y = 1 / y;
  61717. this._negateScaleChildren.z = 1 / z;
  61718. }
  61719. this._syncScaleVector();
  61720. }
  61721. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61722. };
  61723. /**
  61724. * Scale the bone on the x, y and z axes.
  61725. * @param x The amount to scale the bone on the x axis.
  61726. * @param x The amount to scale the bone on the y axis.
  61727. * @param z The amount to scale the bone on the z axis.
  61728. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61729. */
  61730. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61731. if (scaleChildren === void 0) { scaleChildren = false; }
  61732. var locMat = this.getLocalMatrix();
  61733. var origLocMat = Bone._tmpMats[0];
  61734. origLocMat.copyFrom(locMat);
  61735. var origLocMatInv = Bone._tmpMats[1];
  61736. origLocMatInv.copyFrom(origLocMat);
  61737. origLocMatInv.invert();
  61738. var scaleMat = Bone._tmpMats[2];
  61739. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61740. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61741. this._scaleVector.x *= x;
  61742. this._scaleVector.y *= y;
  61743. this._scaleVector.z *= z;
  61744. locMat.multiplyToRef(origLocMatInv, locMat);
  61745. locMat.multiplyToRef(scaleMat, locMat);
  61746. locMat.multiplyToRef(origLocMat, locMat);
  61747. var parent = this.getParent();
  61748. if (parent) {
  61749. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61750. }
  61751. else {
  61752. this.getAbsoluteTransform().copyFrom(locMat);
  61753. }
  61754. var len = this.children.length;
  61755. scaleMat.invert();
  61756. for (var i = 0; i < len; i++) {
  61757. var child = this.children[i];
  61758. var cm = child.getLocalMatrix();
  61759. cm.multiplyToRef(scaleMat, cm);
  61760. var lm = child.getLocalMatrix();
  61761. lm.m[12] *= x;
  61762. lm.m[13] *= y;
  61763. lm.m[14] *= z;
  61764. }
  61765. this.computeAbsoluteTransforms();
  61766. if (scaleChildren) {
  61767. for (var i = 0; i < len; i++) {
  61768. this.children[i].scale(x, y, z, scaleChildren);
  61769. }
  61770. }
  61771. this.markAsDirty();
  61772. };
  61773. /**
  61774. * Set the yaw, pitch, and roll of the bone in local or world space.
  61775. * @param yaw The rotation of the bone on the y axis.
  61776. * @param pitch The rotation of the bone on the x axis.
  61777. * @param roll The rotation of the bone on the z axis.
  61778. * @param space The space that the axes of rotation are in.
  61779. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61780. */
  61781. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61783. var rotMat = Bone._tmpMats[0];
  61784. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61785. var rotMatInv = Bone._tmpMats[1];
  61786. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61787. rotMatInv.multiplyToRef(rotMat, rotMat);
  61788. this._rotateWithMatrix(rotMat, space, mesh);
  61789. };
  61790. /**
  61791. * Rotate the bone on an axis in local or world space.
  61792. * @param axis The axis to rotate the bone on.
  61793. * @param amount The amount to rotate the bone.
  61794. * @param space The space that the axis is in.
  61795. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61796. */
  61797. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61799. var rmat = Bone._tmpMats[0];
  61800. rmat.m[12] = 0;
  61801. rmat.m[13] = 0;
  61802. rmat.m[14] = 0;
  61803. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61804. this._rotateWithMatrix(rmat, space, mesh);
  61805. };
  61806. /**
  61807. * Set the rotation of the bone to a particular axis angle in local or world space.
  61808. * @param axis The axis to rotate the bone on.
  61809. * @param angle The angle that the bone should be rotated to.
  61810. * @param space The space that the axis is in.
  61811. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61812. */
  61813. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61815. var rotMat = Bone._tmpMats[0];
  61816. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61817. var rotMatInv = Bone._tmpMats[1];
  61818. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61819. rotMatInv.multiplyToRef(rotMat, rotMat);
  61820. this._rotateWithMatrix(rotMat, space, mesh);
  61821. };
  61822. /**
  61823. * Set the euler rotation of the bone in local of world space.
  61824. * @param rotation The euler rotation that the bone should be set to.
  61825. * @param space The space that the rotation is in.
  61826. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61827. */
  61828. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61829. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61830. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61831. };
  61832. /**
  61833. * Set the quaternion rotation of the bone in local of world space.
  61834. * @param quat The quaternion rotation that the bone should be set to.
  61835. * @param space The space that the rotation is in.
  61836. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61837. */
  61838. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61840. var rotMatInv = Bone._tmpMats[0];
  61841. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61842. var rotMat = Bone._tmpMats[1];
  61843. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61844. rotMatInv.multiplyToRef(rotMat, rotMat);
  61845. this._rotateWithMatrix(rotMat, space, mesh);
  61846. };
  61847. /**
  61848. * Set the rotation matrix of the bone in local of world space.
  61849. * @param rotMat The rotation matrix that the bone should be set to.
  61850. * @param space The space that the rotation is in.
  61851. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61852. */
  61853. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61854. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61855. var rotMatInv = Bone._tmpMats[0];
  61856. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61857. var rotMat2 = Bone._tmpMats[1];
  61858. rotMat2.copyFrom(rotMat);
  61859. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61860. this._rotateWithMatrix(rotMat2, space, mesh);
  61861. };
  61862. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61863. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61864. var lmat = this.getLocalMatrix();
  61865. var lx = lmat.m[12];
  61866. var ly = lmat.m[13];
  61867. var lz = lmat.m[14];
  61868. var parent = this.getParent();
  61869. var parentScale = Bone._tmpMats[3];
  61870. var parentScaleInv = Bone._tmpMats[4];
  61871. if (parent) {
  61872. if (space == BABYLON.Space.WORLD) {
  61873. if (mesh) {
  61874. parentScale.copyFrom(mesh.getWorldMatrix());
  61875. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61876. }
  61877. else {
  61878. parentScale.copyFrom(parent.getAbsoluteTransform());
  61879. }
  61880. }
  61881. else {
  61882. parentScale = parent._scaleMatrix;
  61883. }
  61884. parentScaleInv.copyFrom(parentScale);
  61885. parentScaleInv.invert();
  61886. lmat.multiplyToRef(parentScale, lmat);
  61887. lmat.multiplyToRef(rmat, lmat);
  61888. lmat.multiplyToRef(parentScaleInv, lmat);
  61889. }
  61890. else {
  61891. if (space == BABYLON.Space.WORLD && mesh) {
  61892. parentScale.copyFrom(mesh.getWorldMatrix());
  61893. parentScaleInv.copyFrom(parentScale);
  61894. parentScaleInv.invert();
  61895. lmat.multiplyToRef(parentScale, lmat);
  61896. lmat.multiplyToRef(rmat, lmat);
  61897. lmat.multiplyToRef(parentScaleInv, lmat);
  61898. }
  61899. else {
  61900. lmat.multiplyToRef(rmat, lmat);
  61901. }
  61902. }
  61903. lmat.m[12] = lx;
  61904. lmat.m[13] = ly;
  61905. lmat.m[14] = lz;
  61906. this.computeAbsoluteTransforms();
  61907. this.markAsDirty();
  61908. };
  61909. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61911. if (space == BABYLON.Space.WORLD) {
  61912. var scaleMatrix = Bone._tmpMats[2];
  61913. scaleMatrix.copyFrom(this._scaleMatrix);
  61914. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61915. if (mesh) {
  61916. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61917. var meshScale = Bone._tmpMats[3];
  61918. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61919. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61920. }
  61921. rotMatInv.invert();
  61922. scaleMatrix.m[0] *= this._scalingDeterminant;
  61923. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61924. }
  61925. else {
  61926. rotMatInv.copyFrom(this.getLocalMatrix());
  61927. rotMatInv.invert();
  61928. var scaleMatrix = Bone._tmpMats[2];
  61929. scaleMatrix.copyFrom(this._scaleMatrix);
  61930. if (this._parent) {
  61931. var pscaleMatrix = Bone._tmpMats[3];
  61932. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61933. pscaleMatrix.invert();
  61934. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61935. }
  61936. else {
  61937. scaleMatrix.m[0] *= this._scalingDeterminant;
  61938. }
  61939. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61940. }
  61941. };
  61942. /**
  61943. * Get the scale of the bone
  61944. * @returns the scale of the bone
  61945. */
  61946. Bone.prototype.getScale = function () {
  61947. return this._scaleVector.clone();
  61948. };
  61949. /**
  61950. * Copy the scale of the bone to a vector3.
  61951. * @param result The vector3 to copy the scale to
  61952. */
  61953. Bone.prototype.getScaleToRef = function (result) {
  61954. result.copyFrom(this._scaleVector);
  61955. };
  61956. /**
  61957. * Get the position of the bone in local or world space.
  61958. * @param space The space that the returned position is in.
  61959. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61960. * @returns The position of the bone
  61961. */
  61962. Bone.prototype.getPosition = function (space, mesh) {
  61963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61964. if (mesh === void 0) { mesh = null; }
  61965. var pos = BABYLON.Vector3.Zero();
  61966. this.getPositionToRef(space, mesh, pos);
  61967. return pos;
  61968. };
  61969. /**
  61970. * Copy the position of the bone to a vector3 in local or world space.
  61971. * @param space The space that the returned position is in.
  61972. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61973. * @param result The vector3 to copy the position to.
  61974. */
  61975. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61976. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61977. if (space == BABYLON.Space.LOCAL) {
  61978. var lm = this.getLocalMatrix();
  61979. result.x = lm.m[12];
  61980. result.y = lm.m[13];
  61981. result.z = lm.m[14];
  61982. }
  61983. else {
  61984. var wm = null;
  61985. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61986. if (mesh) {
  61987. wm = mesh.getWorldMatrix();
  61988. }
  61989. this._skeleton.computeAbsoluteTransforms();
  61990. var tmat = Bone._tmpMats[0];
  61991. if (mesh && wm) {
  61992. tmat.copyFrom(this.getAbsoluteTransform());
  61993. tmat.multiplyToRef(wm, tmat);
  61994. }
  61995. else {
  61996. tmat = this.getAbsoluteTransform();
  61997. }
  61998. result.x = tmat.m[12];
  61999. result.y = tmat.m[13];
  62000. result.z = tmat.m[14];
  62001. }
  62002. };
  62003. /**
  62004. * Get the absolute position of the bone (world space).
  62005. * @param mesh The mesh that this bone is attached to.
  62006. * @returns The absolute position of the bone
  62007. */
  62008. Bone.prototype.getAbsolutePosition = function (mesh) {
  62009. if (mesh === void 0) { mesh = null; }
  62010. var pos = BABYLON.Vector3.Zero();
  62011. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  62012. return pos;
  62013. };
  62014. /**
  62015. * Copy the absolute position of the bone (world space) to the result param.
  62016. * @param mesh The mesh that this bone is attached to.
  62017. * @param result The vector3 to copy the absolute position to.
  62018. */
  62019. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  62020. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  62021. };
  62022. /**
  62023. * Compute the absolute transforms of this bone and its children.
  62024. */
  62025. Bone.prototype.computeAbsoluteTransforms = function () {
  62026. if (this._parent) {
  62027. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62028. }
  62029. else {
  62030. this._absoluteTransform.copyFrom(this._localMatrix);
  62031. var poseMatrix = this._skeleton.getPoseMatrix();
  62032. if (poseMatrix) {
  62033. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  62034. }
  62035. }
  62036. var children = this.children;
  62037. var len = children.length;
  62038. for (var i = 0; i < len; i++) {
  62039. children[i].computeAbsoluteTransforms();
  62040. }
  62041. };
  62042. Bone.prototype._syncScaleVector = function () {
  62043. var lm = this.getLocalMatrix();
  62044. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  62045. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  62046. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  62047. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  62048. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  62049. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  62050. this._scaleVector.x = xs * Math.sqrt(xsq);
  62051. this._scaleVector.y = ys * Math.sqrt(ysq);
  62052. this._scaleVector.z = zs * Math.sqrt(zsq);
  62053. if (this._parent) {
  62054. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  62055. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  62056. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  62057. }
  62058. 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);
  62059. };
  62060. /**
  62061. * Get the world direction from an axis that is in the local space of the bone.
  62062. * @param localAxis The local direction that is used to compute the world direction.
  62063. * @param mesh The mesh that this bone is attached to.
  62064. * @returns The world direction
  62065. */
  62066. Bone.prototype.getDirection = function (localAxis, mesh) {
  62067. if (mesh === void 0) { mesh = null; }
  62068. var result = BABYLON.Vector3.Zero();
  62069. this.getDirectionToRef(localAxis, mesh, result);
  62070. return result;
  62071. };
  62072. /**
  62073. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  62074. * @param localAxis The local direction that is used to compute the world direction.
  62075. * @param mesh The mesh that this bone is attached to.
  62076. * @param result The vector3 that the world direction will be copied to.
  62077. */
  62078. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  62079. if (mesh === void 0) { mesh = null; }
  62080. var wm = null;
  62081. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62082. if (mesh) {
  62083. wm = mesh.getWorldMatrix();
  62084. }
  62085. this._skeleton.computeAbsoluteTransforms();
  62086. var mat = Bone._tmpMats[0];
  62087. mat.copyFrom(this.getAbsoluteTransform());
  62088. if (mesh && wm) {
  62089. mat.multiplyToRef(wm, mat);
  62090. }
  62091. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  62092. result.normalize();
  62093. };
  62094. /**
  62095. * Get the euler rotation of the bone in local or world space.
  62096. * @param space The space that the rotation should be in.
  62097. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62098. * @returns The euler rotation
  62099. */
  62100. Bone.prototype.getRotation = function (space, mesh) {
  62101. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62102. if (mesh === void 0) { mesh = null; }
  62103. var result = BABYLON.Vector3.Zero();
  62104. this.getRotationToRef(space, mesh, result);
  62105. return result;
  62106. };
  62107. /**
  62108. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62109. * @param space The space that the rotation should be in.
  62110. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62111. * @param result The vector3 that the rotation should be copied to.
  62112. */
  62113. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62115. if (mesh === void 0) { mesh = null; }
  62116. var quat = Bone._tmpQuat;
  62117. this.getRotationQuaternionToRef(space, mesh, quat);
  62118. quat.toEulerAnglesToRef(result);
  62119. };
  62120. /**
  62121. * Get the quaternion rotation of the bone in either local or world space.
  62122. * @param space The space that the rotation should be in.
  62123. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62124. * @returns The quaternion rotation
  62125. */
  62126. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62127. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62128. if (mesh === void 0) { mesh = null; }
  62129. var result = BABYLON.Quaternion.Identity();
  62130. this.getRotationQuaternionToRef(space, mesh, result);
  62131. return result;
  62132. };
  62133. /**
  62134. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62135. * @param space The space that the rotation should be in.
  62136. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62137. * @param result The quaternion that the rotation should be copied to.
  62138. */
  62139. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62140. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62141. if (mesh === void 0) { mesh = null; }
  62142. if (space == BABYLON.Space.LOCAL) {
  62143. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62144. }
  62145. else {
  62146. var mat = Bone._tmpMats[0];
  62147. var amat = this.getAbsoluteTransform();
  62148. if (mesh) {
  62149. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62150. }
  62151. else {
  62152. mat.copyFrom(amat);
  62153. }
  62154. mat.m[0] *= this._scalingDeterminant;
  62155. mat.m[1] *= this._scalingDeterminant;
  62156. mat.m[2] *= this._scalingDeterminant;
  62157. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62158. }
  62159. };
  62160. /**
  62161. * Get the rotation matrix of the bone in local or world space.
  62162. * @param space The space that the rotation should be in.
  62163. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62164. * @returns The rotation matrix
  62165. */
  62166. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62168. var result = BABYLON.Matrix.Identity();
  62169. this.getRotationMatrixToRef(space, mesh, result);
  62170. return result;
  62171. };
  62172. /**
  62173. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62174. * @param space The space that the rotation should be in.
  62175. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62176. * @param result The quaternion that the rotation should be copied to.
  62177. */
  62178. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62179. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62180. if (space == BABYLON.Space.LOCAL) {
  62181. this.getLocalMatrix().getRotationMatrixToRef(result);
  62182. }
  62183. else {
  62184. var mat = Bone._tmpMats[0];
  62185. var amat = this.getAbsoluteTransform();
  62186. if (mesh) {
  62187. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62188. }
  62189. else {
  62190. mat.copyFrom(amat);
  62191. }
  62192. mat.m[0] *= this._scalingDeterminant;
  62193. mat.m[1] *= this._scalingDeterminant;
  62194. mat.m[2] *= this._scalingDeterminant;
  62195. mat.getRotationMatrixToRef(result);
  62196. }
  62197. };
  62198. /**
  62199. * Get the world position of a point that is in the local space of the bone.
  62200. * @param position The local position
  62201. * @param mesh The mesh that this bone is attached to.
  62202. * @returns The world position
  62203. */
  62204. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62205. if (mesh === void 0) { mesh = null; }
  62206. var result = BABYLON.Vector3.Zero();
  62207. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62208. return result;
  62209. };
  62210. /**
  62211. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62212. * @param position The local position
  62213. * @param mesh The mesh that this bone is attached to.
  62214. * @param result The vector3 that the world position should be copied to.
  62215. */
  62216. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62217. if (mesh === void 0) { mesh = null; }
  62218. var wm = null;
  62219. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62220. if (mesh) {
  62221. wm = mesh.getWorldMatrix();
  62222. }
  62223. this._skeleton.computeAbsoluteTransforms();
  62224. var tmat = Bone._tmpMats[0];
  62225. if (mesh && wm) {
  62226. tmat.copyFrom(this.getAbsoluteTransform());
  62227. tmat.multiplyToRef(wm, tmat);
  62228. }
  62229. else {
  62230. tmat = this.getAbsoluteTransform();
  62231. }
  62232. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62233. };
  62234. /**
  62235. * Get the local position of a point that is in world space.
  62236. * @param position The world position
  62237. * @param mesh The mesh that this bone is attached to.
  62238. * @returns The local position
  62239. */
  62240. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62241. if (mesh === void 0) { mesh = null; }
  62242. var result = BABYLON.Vector3.Zero();
  62243. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62244. return result;
  62245. };
  62246. /**
  62247. * Get the local position of a point that is in world space and copy it to the result param.
  62248. * @param position The world position
  62249. * @param mesh The mesh that this bone is attached to.
  62250. * @param result The vector3 that the local position should be copied to.
  62251. */
  62252. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62253. if (mesh === void 0) { mesh = null; }
  62254. var wm = null;
  62255. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62256. if (mesh) {
  62257. wm = mesh.getWorldMatrix();
  62258. }
  62259. this._skeleton.computeAbsoluteTransforms();
  62260. var tmat = Bone._tmpMats[0];
  62261. tmat.copyFrom(this.getAbsoluteTransform());
  62262. if (mesh && wm) {
  62263. tmat.multiplyToRef(wm, tmat);
  62264. }
  62265. tmat.invert();
  62266. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62267. };
  62268. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62269. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62270. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62271. return Bone;
  62272. }(BABYLON.Node));
  62273. BABYLON.Bone = Bone;
  62274. })(BABYLON || (BABYLON = {}));
  62275. //# sourceMappingURL=babylon.bone.js.map
  62276. var BABYLON;
  62277. (function (BABYLON) {
  62278. var BoneIKController = /** @class */ (function () {
  62279. function BoneIKController(mesh, bone, options) {
  62280. this.targetPosition = BABYLON.Vector3.Zero();
  62281. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62282. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62283. this.poleAngle = 0;
  62284. this.slerpAmount = 1;
  62285. this._bone1Quat = BABYLON.Quaternion.Identity();
  62286. this._bone1Mat = BABYLON.Matrix.Identity();
  62287. this._bone2Ang = Math.PI;
  62288. this._maxAngle = Math.PI;
  62289. this._rightHandedSystem = false;
  62290. this._bendAxis = BABYLON.Vector3.Right();
  62291. this._slerping = false;
  62292. this._adjustRoll = 0;
  62293. this._bone2 = bone;
  62294. this._bone1 = bone.getParent();
  62295. if (!this._bone1) {
  62296. return;
  62297. }
  62298. this.mesh = mesh;
  62299. var bonePos = bone.getPosition();
  62300. if (bone.getAbsoluteTransform().determinant() > 0) {
  62301. this._rightHandedSystem = true;
  62302. this._bendAxis.x = 0;
  62303. this._bendAxis.y = 0;
  62304. this._bendAxis.z = -1;
  62305. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62306. this._adjustRoll = Math.PI * .5;
  62307. this._bendAxis.z = 1;
  62308. }
  62309. }
  62310. if (this._bone1.length) {
  62311. var boneScale1 = this._bone1.getScale();
  62312. var boneScale2 = this._bone2.getScale();
  62313. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62314. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62315. }
  62316. else if (this._bone1.children[0]) {
  62317. mesh.computeWorldMatrix(true);
  62318. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62319. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62320. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62321. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62322. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62323. }
  62324. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62325. this.maxAngle = Math.PI;
  62326. if (options) {
  62327. if (options.targetMesh) {
  62328. this.targetMesh = options.targetMesh;
  62329. this.targetMesh.computeWorldMatrix(true);
  62330. }
  62331. if (options.poleTargetMesh) {
  62332. this.poleTargetMesh = options.poleTargetMesh;
  62333. this.poleTargetMesh.computeWorldMatrix(true);
  62334. }
  62335. else if (options.poleTargetBone) {
  62336. this.poleTargetBone = options.poleTargetBone;
  62337. }
  62338. else if (this._bone1.getParent()) {
  62339. this.poleTargetBone = this._bone1.getParent();
  62340. }
  62341. if (options.poleTargetLocalOffset) {
  62342. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62343. }
  62344. if (options.poleAngle) {
  62345. this.poleAngle = options.poleAngle;
  62346. }
  62347. if (options.bendAxis) {
  62348. this._bendAxis.copyFrom(options.bendAxis);
  62349. }
  62350. if (options.maxAngle) {
  62351. this.maxAngle = options.maxAngle;
  62352. }
  62353. if (options.slerpAmount) {
  62354. this.slerpAmount = options.slerpAmount;
  62355. }
  62356. }
  62357. }
  62358. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62359. get: function () {
  62360. return this._maxAngle;
  62361. },
  62362. set: function (value) {
  62363. this._setMaxAngle(value);
  62364. },
  62365. enumerable: true,
  62366. configurable: true
  62367. });
  62368. BoneIKController.prototype._setMaxAngle = function (ang) {
  62369. if (ang < 0) {
  62370. ang = 0;
  62371. }
  62372. if (ang > Math.PI || ang == undefined) {
  62373. ang = Math.PI;
  62374. }
  62375. this._maxAngle = ang;
  62376. var a = this._bone1Length;
  62377. var b = this._bone2Length;
  62378. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62379. };
  62380. BoneIKController.prototype.update = function () {
  62381. var bone1 = this._bone1;
  62382. if (!bone1) {
  62383. return;
  62384. }
  62385. var target = this.targetPosition;
  62386. var poleTarget = this.poleTargetPosition;
  62387. var mat1 = BoneIKController._tmpMats[0];
  62388. var mat2 = BoneIKController._tmpMats[1];
  62389. if (this.targetMesh) {
  62390. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62391. }
  62392. if (this.poleTargetBone) {
  62393. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62394. }
  62395. else if (this.poleTargetMesh) {
  62396. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62397. }
  62398. var bonePos = BoneIKController._tmpVecs[0];
  62399. var zaxis = BoneIKController._tmpVecs[1];
  62400. var xaxis = BoneIKController._tmpVecs[2];
  62401. var yaxis = BoneIKController._tmpVecs[3];
  62402. var upAxis = BoneIKController._tmpVecs[4];
  62403. var _tmpQuat = BoneIKController._tmpQuat;
  62404. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62405. poleTarget.subtractToRef(bonePos, upAxis);
  62406. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62407. upAxis.y = 1;
  62408. }
  62409. else {
  62410. upAxis.normalize();
  62411. }
  62412. target.subtractToRef(bonePos, yaxis);
  62413. yaxis.normalize();
  62414. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62415. zaxis.normalize();
  62416. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62417. xaxis.normalize();
  62418. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62419. var a = this._bone1Length;
  62420. var b = this._bone2Length;
  62421. var c = BABYLON.Vector3.Distance(bonePos, target);
  62422. if (this._maxReach > 0) {
  62423. c = Math.min(this._maxReach, c);
  62424. }
  62425. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62426. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62427. if (acosa > 1) {
  62428. acosa = 1;
  62429. }
  62430. if (acosb > 1) {
  62431. acosb = 1;
  62432. }
  62433. if (acosa < -1) {
  62434. acosa = -1;
  62435. }
  62436. if (acosb < -1) {
  62437. acosb = -1;
  62438. }
  62439. var angA = Math.acos(acosa);
  62440. var angB = Math.acos(acosb);
  62441. var angC = -angA - angB;
  62442. if (this._rightHandedSystem) {
  62443. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62444. mat2.multiplyToRef(mat1, mat1);
  62445. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62446. mat2.multiplyToRef(mat1, mat1);
  62447. }
  62448. else {
  62449. var _tmpVec = BoneIKController._tmpVecs[5];
  62450. _tmpVec.copyFrom(this._bendAxis);
  62451. _tmpVec.x *= -1;
  62452. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62453. mat2.multiplyToRef(mat1, mat1);
  62454. }
  62455. if (this.poleAngle) {
  62456. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62457. mat1.multiplyToRef(mat2, mat1);
  62458. }
  62459. if (this._bone1) {
  62460. if (this.slerpAmount < 1) {
  62461. if (!this._slerping) {
  62462. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62463. }
  62464. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62465. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62466. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62467. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62468. this._slerping = true;
  62469. }
  62470. else {
  62471. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62472. this._bone1Mat.copyFrom(mat1);
  62473. this._slerping = false;
  62474. }
  62475. }
  62476. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62477. this._bone2Ang = angC;
  62478. };
  62479. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62480. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62481. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62482. return BoneIKController;
  62483. }());
  62484. BABYLON.BoneIKController = BoneIKController;
  62485. })(BABYLON || (BABYLON = {}));
  62486. //# sourceMappingURL=babylon.boneIKController.js.map
  62487. var BABYLON;
  62488. (function (BABYLON) {
  62489. var BoneLookController = /** @class */ (function () {
  62490. /**
  62491. * Create a BoneLookController
  62492. * @param mesh the mesh that the bone belongs to
  62493. * @param bone the bone that will be looking to the target
  62494. * @param target the target Vector3 to look at
  62495. * @param settings optional settings:
  62496. * - maxYaw: the maximum angle the bone will yaw to
  62497. * - minYaw: the minimum angle the bone will yaw to
  62498. * - maxPitch: the maximum angle the bone will pitch to
  62499. * - minPitch: the minimum angle the bone will yaw to
  62500. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62501. * - upAxis: the up axis of the coordinate system
  62502. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62503. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62504. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62505. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62506. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62507. * - adjustRoll: used to make an adjustment to the roll of the bone
  62508. **/
  62509. function BoneLookController(mesh, bone, target, options) {
  62510. /**
  62511. * The up axis of the coordinate system that is used when the bone is rotated.
  62512. */
  62513. this.upAxis = BABYLON.Vector3.Up();
  62514. /**
  62515. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62516. */
  62517. this.upAxisSpace = BABYLON.Space.LOCAL;
  62518. /**
  62519. * Used to make an adjustment to the yaw of the bone.
  62520. */
  62521. this.adjustYaw = 0;
  62522. /**
  62523. * Used to make an adjustment to the pitch of the bone.
  62524. */
  62525. this.adjustPitch = 0;
  62526. /**
  62527. * Used to make an adjustment to the roll of the bone.
  62528. */
  62529. this.adjustRoll = 0;
  62530. /**
  62531. * 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).
  62532. */
  62533. this.slerpAmount = 1;
  62534. this._boneQuat = BABYLON.Quaternion.Identity();
  62535. this._slerping = false;
  62536. this._firstFrameSkipped = false;
  62537. this._fowardAxis = BABYLON.Vector3.Forward();
  62538. this.mesh = mesh;
  62539. this.bone = bone;
  62540. this.target = target;
  62541. if (options) {
  62542. if (options.adjustYaw) {
  62543. this.adjustYaw = options.adjustYaw;
  62544. }
  62545. if (options.adjustPitch) {
  62546. this.adjustPitch = options.adjustPitch;
  62547. }
  62548. if (options.adjustRoll) {
  62549. this.adjustRoll = options.adjustRoll;
  62550. }
  62551. if (options.maxYaw != null) {
  62552. this.maxYaw = options.maxYaw;
  62553. }
  62554. else {
  62555. this.maxYaw = Math.PI;
  62556. }
  62557. if (options.minYaw != null) {
  62558. this.minYaw = options.minYaw;
  62559. }
  62560. else {
  62561. this.minYaw = -Math.PI;
  62562. }
  62563. if (options.maxPitch != null) {
  62564. this.maxPitch = options.maxPitch;
  62565. }
  62566. else {
  62567. this.maxPitch = Math.PI;
  62568. }
  62569. if (options.minPitch != null) {
  62570. this.minPitch = options.minPitch;
  62571. }
  62572. else {
  62573. this.minPitch = -Math.PI;
  62574. }
  62575. if (options.slerpAmount != null) {
  62576. this.slerpAmount = options.slerpAmount;
  62577. }
  62578. if (options.upAxis != null) {
  62579. this.upAxis = options.upAxis;
  62580. }
  62581. if (options.upAxisSpace != null) {
  62582. this.upAxisSpace = options.upAxisSpace;
  62583. }
  62584. if (options.yawAxis != null || options.pitchAxis != null) {
  62585. var newYawAxis = BABYLON.Axis.Y;
  62586. var newPitchAxis = BABYLON.Axis.X;
  62587. if (options.yawAxis != null) {
  62588. newYawAxis = options.yawAxis.clone();
  62589. newYawAxis.normalize();
  62590. }
  62591. if (options.pitchAxis != null) {
  62592. newPitchAxis = options.pitchAxis.clone();
  62593. newPitchAxis.normalize();
  62594. }
  62595. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62596. this._transformYawPitch = BABYLON.Matrix.Identity();
  62597. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62598. this._transformYawPitchInv = this._transformYawPitch.clone();
  62599. this._transformYawPitch.invert();
  62600. }
  62601. }
  62602. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62603. this.upAxisSpace = BABYLON.Space.LOCAL;
  62604. }
  62605. }
  62606. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62607. /**
  62608. * Get/set the minimum yaw angle that the bone can look to.
  62609. */
  62610. get: function () {
  62611. return this._minYaw;
  62612. },
  62613. set: function (value) {
  62614. this._minYaw = value;
  62615. this._minYawSin = Math.sin(value);
  62616. this._minYawCos = Math.cos(value);
  62617. if (this._maxYaw != null) {
  62618. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62619. this._yawRange = this._maxYaw - this._minYaw;
  62620. }
  62621. },
  62622. enumerable: true,
  62623. configurable: true
  62624. });
  62625. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62626. /**
  62627. * Get/set the maximum yaw angle that the bone can look to.
  62628. */
  62629. get: function () {
  62630. return this._maxYaw;
  62631. },
  62632. set: function (value) {
  62633. this._maxYaw = value;
  62634. this._maxYawSin = Math.sin(value);
  62635. this._maxYawCos = Math.cos(value);
  62636. if (this._minYaw != null) {
  62637. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62638. this._yawRange = this._maxYaw - this._minYaw;
  62639. }
  62640. },
  62641. enumerable: true,
  62642. configurable: true
  62643. });
  62644. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62645. /**
  62646. * Get/set the minimum pitch angle that the bone can look to.
  62647. */
  62648. get: function () {
  62649. return this._minPitch;
  62650. },
  62651. set: function (value) {
  62652. this._minPitch = value;
  62653. this._minPitchTan = Math.tan(value);
  62654. },
  62655. enumerable: true,
  62656. configurable: true
  62657. });
  62658. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62659. /**
  62660. * Get/set the maximum pitch angle that the bone can look to.
  62661. */
  62662. get: function () {
  62663. return this._maxPitch;
  62664. },
  62665. set: function (value) {
  62666. this._maxPitch = value;
  62667. this._maxPitchTan = Math.tan(value);
  62668. },
  62669. enumerable: true,
  62670. configurable: true
  62671. });
  62672. /**
  62673. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62674. */
  62675. BoneLookController.prototype.update = function () {
  62676. //skip the first frame when slerping so that the mesh rotation is correct
  62677. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62678. this._firstFrameSkipped = true;
  62679. return;
  62680. }
  62681. var bone = this.bone;
  62682. var bonePos = BoneLookController._tmpVecs[0];
  62683. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62684. var target = this.target;
  62685. var _tmpMat1 = BoneLookController._tmpMats[0];
  62686. var _tmpMat2 = BoneLookController._tmpMats[1];
  62687. var mesh = this.mesh;
  62688. var parentBone = bone.getParent();
  62689. var upAxis = BoneLookController._tmpVecs[1];
  62690. upAxis.copyFrom(this.upAxis);
  62691. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62692. if (this._transformYawPitch) {
  62693. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62694. }
  62695. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62696. }
  62697. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62698. mesh.getDirectionToRef(upAxis, upAxis);
  62699. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62700. upAxis.normalize();
  62701. }
  62702. }
  62703. var checkYaw = false;
  62704. var checkPitch = false;
  62705. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62706. checkYaw = true;
  62707. }
  62708. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62709. checkPitch = true;
  62710. }
  62711. if (checkYaw || checkPitch) {
  62712. var spaceMat = BoneLookController._tmpMats[2];
  62713. var spaceMatInv = BoneLookController._tmpMats[3];
  62714. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62715. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62716. }
  62717. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62718. spaceMat.copyFrom(mesh.getWorldMatrix());
  62719. }
  62720. else {
  62721. var forwardAxis = BoneLookController._tmpVecs[2];
  62722. forwardAxis.copyFrom(this._fowardAxis);
  62723. if (this._transformYawPitch) {
  62724. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62725. }
  62726. if (parentBone) {
  62727. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62728. }
  62729. else {
  62730. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62731. }
  62732. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62733. rightAxis.normalize();
  62734. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62735. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62736. }
  62737. spaceMat.invertToRef(spaceMatInv);
  62738. var xzlen = null;
  62739. if (checkPitch) {
  62740. var localTarget = BoneLookController._tmpVecs[3];
  62741. target.subtractToRef(bonePos, localTarget);
  62742. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62743. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62744. var pitch = Math.atan2(localTarget.y, xzlen);
  62745. var newPitch = pitch;
  62746. if (pitch > this._maxPitch) {
  62747. localTarget.y = this._maxPitchTan * xzlen;
  62748. newPitch = this._maxPitch;
  62749. }
  62750. else if (pitch < this._minPitch) {
  62751. localTarget.y = this._minPitchTan * xzlen;
  62752. newPitch = this._minPitch;
  62753. }
  62754. if (pitch != newPitch) {
  62755. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62756. localTarget.addInPlace(bonePos);
  62757. target = localTarget;
  62758. }
  62759. }
  62760. if (checkYaw) {
  62761. var localTarget = BoneLookController._tmpVecs[4];
  62762. target.subtractToRef(bonePos, localTarget);
  62763. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62764. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62765. var newYaw = yaw;
  62766. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62767. if (xzlen == null) {
  62768. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62769. }
  62770. if (this._yawRange > Math.PI) {
  62771. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62772. localTarget.z = this._maxYawCos * xzlen;
  62773. localTarget.x = this._maxYawSin * xzlen;
  62774. newYaw = this._maxYaw;
  62775. }
  62776. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62777. localTarget.z = this._minYawCos * xzlen;
  62778. localTarget.x = this._minYawSin * xzlen;
  62779. newYaw = this._minYaw;
  62780. }
  62781. }
  62782. else {
  62783. if (yaw > this._maxYaw) {
  62784. localTarget.z = this._maxYawCos * xzlen;
  62785. localTarget.x = this._maxYawSin * xzlen;
  62786. newYaw = this._maxYaw;
  62787. }
  62788. else if (yaw < this._minYaw) {
  62789. localTarget.z = this._minYawCos * xzlen;
  62790. localTarget.x = this._minYawSin * xzlen;
  62791. newYaw = this._minYaw;
  62792. }
  62793. }
  62794. }
  62795. if (this._slerping && this._yawRange > Math.PI) {
  62796. //are we going to be crossing into the min/max region?
  62797. var boneFwd = BoneLookController._tmpVecs[8];
  62798. boneFwd.copyFrom(BABYLON.Axis.Z);
  62799. if (this._transformYawPitch) {
  62800. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62801. }
  62802. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62803. this._boneQuat.toRotationMatrix(boneRotMat);
  62804. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62805. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62806. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62807. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62808. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62809. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62810. if (angBtwTar > angBtwMidYaw) {
  62811. if (xzlen == null) {
  62812. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62813. }
  62814. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62815. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62816. if (angBtwMin < angBtwMax) {
  62817. newYaw = boneYaw + Math.PI * .75;
  62818. localTarget.z = Math.cos(newYaw) * xzlen;
  62819. localTarget.x = Math.sin(newYaw) * xzlen;
  62820. }
  62821. else {
  62822. newYaw = boneYaw - Math.PI * .75;
  62823. localTarget.z = Math.cos(newYaw) * xzlen;
  62824. localTarget.x = Math.sin(newYaw) * xzlen;
  62825. }
  62826. }
  62827. }
  62828. if (yaw != newYaw) {
  62829. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62830. localTarget.addInPlace(bonePos);
  62831. target = localTarget;
  62832. }
  62833. }
  62834. }
  62835. var zaxis = BoneLookController._tmpVecs[5];
  62836. var xaxis = BoneLookController._tmpVecs[6];
  62837. var yaxis = BoneLookController._tmpVecs[7];
  62838. var _tmpQuat = BoneLookController._tmpQuat;
  62839. target.subtractToRef(bonePos, zaxis);
  62840. zaxis.normalize();
  62841. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62842. xaxis.normalize();
  62843. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62844. yaxis.normalize();
  62845. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62846. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62847. return;
  62848. }
  62849. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62850. return;
  62851. }
  62852. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62853. return;
  62854. }
  62855. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62856. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62857. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62858. }
  62859. if (this.slerpAmount < 1) {
  62860. if (!this._slerping) {
  62861. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62862. }
  62863. if (this._transformYawPitch) {
  62864. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62865. }
  62866. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62867. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62868. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62869. this._slerping = true;
  62870. }
  62871. else {
  62872. if (this._transformYawPitch) {
  62873. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62874. }
  62875. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62876. this._slerping = false;
  62877. }
  62878. };
  62879. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62880. var angDiff = ang2 - ang1;
  62881. angDiff %= Math.PI * 2;
  62882. if (angDiff > Math.PI) {
  62883. angDiff -= Math.PI * 2;
  62884. }
  62885. else if (angDiff < -Math.PI) {
  62886. angDiff += Math.PI * 2;
  62887. }
  62888. return angDiff;
  62889. };
  62890. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62891. ang1 %= (2 * Math.PI);
  62892. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62893. ang2 %= (2 * Math.PI);
  62894. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62895. var ab = 0;
  62896. if (ang1 < ang2) {
  62897. ab = ang2 - ang1;
  62898. }
  62899. else {
  62900. ab = ang1 - ang2;
  62901. }
  62902. if (ab > Math.PI) {
  62903. ab = Math.PI * 2 - ab;
  62904. }
  62905. return ab;
  62906. };
  62907. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62908. ang %= (2 * Math.PI);
  62909. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62910. ang1 %= (2 * Math.PI);
  62911. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62912. ang2 %= (2 * Math.PI);
  62913. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62914. if (ang1 < ang2) {
  62915. if (ang > ang1 && ang < ang2) {
  62916. return true;
  62917. }
  62918. }
  62919. else {
  62920. if (ang > ang2 && ang < ang1) {
  62921. return true;
  62922. }
  62923. }
  62924. return false;
  62925. };
  62926. 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()];
  62927. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62928. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62929. return BoneLookController;
  62930. }());
  62931. BABYLON.BoneLookController = BoneLookController;
  62932. })(BABYLON || (BABYLON = {}));
  62933. //# sourceMappingURL=babylon.boneLookController.js.map
  62934. var BABYLON;
  62935. (function (BABYLON) {
  62936. var Skeleton = /** @class */ (function () {
  62937. function Skeleton(name, id, scene) {
  62938. this.name = name;
  62939. this.id = id;
  62940. this.bones = new Array();
  62941. this.needInitialSkinMatrix = false;
  62942. this._isDirty = true;
  62943. this._meshesWithPoseMatrix = new Array();
  62944. this._identity = BABYLON.Matrix.Identity();
  62945. this._ranges = {};
  62946. this._lastAbsoluteTransformsUpdateId = -1;
  62947. // Events
  62948. /**
  62949. * An event triggered before computing the skeleton's matrices
  62950. * @type {BABYLON.Observable}
  62951. */
  62952. this.onBeforeComputeObservable = new BABYLON.Observable();
  62953. this.bones = [];
  62954. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62955. scene.skeletons.push(this);
  62956. //make sure it will recalculate the matrix next time prepare is called.
  62957. this._isDirty = true;
  62958. }
  62959. // Members
  62960. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62961. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62962. return mesh._bonesTransformMatrices;
  62963. }
  62964. if (!this._transformMatrices) {
  62965. this.prepare();
  62966. }
  62967. return this._transformMatrices;
  62968. };
  62969. Skeleton.prototype.getScene = function () {
  62970. return this._scene;
  62971. };
  62972. // Methods
  62973. /**
  62974. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62975. */
  62976. Skeleton.prototype.toString = function (fullDetails) {
  62977. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62978. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62979. if (fullDetails) {
  62980. ret += ", Ranges: {";
  62981. var first = true;
  62982. for (var name_1 in this._ranges) {
  62983. if (first) {
  62984. ret += ", ";
  62985. first = false;
  62986. }
  62987. ret += name_1;
  62988. }
  62989. ret += "}";
  62990. }
  62991. return ret;
  62992. };
  62993. /**
  62994. * Get bone's index searching by name
  62995. * @param {string} name is bone's name to search for
  62996. * @return {number} Indice of the bone. Returns -1 if not found
  62997. */
  62998. Skeleton.prototype.getBoneIndexByName = function (name) {
  62999. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  63000. if (this.bones[boneIndex].name === name) {
  63001. return boneIndex;
  63002. }
  63003. }
  63004. return -1;
  63005. };
  63006. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  63007. // check name not already in use
  63008. if (!this._ranges[name]) {
  63009. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  63010. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63011. if (this.bones[i].animations[0]) {
  63012. this.bones[i].animations[0].createRange(name, from, to);
  63013. }
  63014. }
  63015. }
  63016. };
  63017. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  63018. if (deleteFrames === void 0) { deleteFrames = true; }
  63019. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63020. if (this.bones[i].animations[0]) {
  63021. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  63022. }
  63023. }
  63024. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  63025. };
  63026. Skeleton.prototype.getAnimationRange = function (name) {
  63027. return this._ranges[name];
  63028. };
  63029. /**
  63030. * Returns as an Array, all AnimationRanges defined on this skeleton
  63031. */
  63032. Skeleton.prototype.getAnimationRanges = function () {
  63033. var animationRanges = [];
  63034. var name;
  63035. var i = 0;
  63036. for (name in this._ranges) {
  63037. animationRanges[i] = this._ranges[name];
  63038. i++;
  63039. }
  63040. return animationRanges;
  63041. };
  63042. /**
  63043. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  63044. */
  63045. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  63046. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63047. if (this._ranges[name] || !source.getAnimationRange(name)) {
  63048. return false;
  63049. }
  63050. var ret = true;
  63051. var frameOffset = this._getHighestAnimationFrame() + 1;
  63052. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  63053. var boneDict = {};
  63054. var sourceBones = source.bones;
  63055. var nBones;
  63056. var i;
  63057. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  63058. boneDict[sourceBones[i].name] = sourceBones[i];
  63059. }
  63060. if (this.bones.length !== sourceBones.length) {
  63061. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  63062. ret = false;
  63063. }
  63064. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  63065. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  63066. var boneName = this.bones[i].name;
  63067. var sourceBone = boneDict[boneName];
  63068. if (sourceBone) {
  63069. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  63070. }
  63071. else {
  63072. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  63073. ret = false;
  63074. }
  63075. }
  63076. // do not call createAnimationRange(), since it also is done to bones, which was already done
  63077. var range = source.getAnimationRange(name);
  63078. if (range) {
  63079. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  63080. }
  63081. return ret;
  63082. };
  63083. Skeleton.prototype.returnToRest = function () {
  63084. for (var index = 0; index < this.bones.length; index++) {
  63085. this.bones[index].returnToRest();
  63086. }
  63087. };
  63088. Skeleton.prototype._getHighestAnimationFrame = function () {
  63089. var ret = 0;
  63090. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63091. if (this.bones[i].animations[0]) {
  63092. var highest = this.bones[i].animations[0].getHighestFrame();
  63093. if (ret < highest) {
  63094. ret = highest;
  63095. }
  63096. }
  63097. }
  63098. return ret;
  63099. };
  63100. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  63101. var range = this.getAnimationRange(name);
  63102. if (!range) {
  63103. return null;
  63104. }
  63105. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63106. };
  63107. Skeleton.prototype._markAsDirty = function () {
  63108. this._isDirty = true;
  63109. };
  63110. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63111. this._meshesWithPoseMatrix.push(mesh);
  63112. };
  63113. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63114. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63115. if (index > -1) {
  63116. this._meshesWithPoseMatrix.splice(index, 1);
  63117. }
  63118. };
  63119. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63120. this.onBeforeComputeObservable.notifyObservers(this);
  63121. for (var index = 0; index < this.bones.length; index++) {
  63122. var bone = this.bones[index];
  63123. var parentBone = bone.getParent();
  63124. if (parentBone) {
  63125. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63126. }
  63127. else {
  63128. if (initialSkinMatrix) {
  63129. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63130. }
  63131. else {
  63132. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63133. }
  63134. }
  63135. if (bone._index !== -1) {
  63136. var mappedIndex = bone._index === null ? index : bone._index;
  63137. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63138. }
  63139. }
  63140. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63141. };
  63142. Skeleton.prototype.prepare = function () {
  63143. if (!this._isDirty) {
  63144. return;
  63145. }
  63146. if (this.needInitialSkinMatrix) {
  63147. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63148. var mesh = this._meshesWithPoseMatrix[index];
  63149. var poseMatrix = mesh.getPoseMatrix();
  63150. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63151. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63152. }
  63153. if (this._synchronizedWithMesh !== mesh) {
  63154. this._synchronizedWithMesh = mesh;
  63155. // Prepare bones
  63156. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63157. var bone = this.bones[boneIndex];
  63158. if (!bone.getParent()) {
  63159. var matrix = bone.getBaseMatrix();
  63160. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63161. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63162. }
  63163. }
  63164. }
  63165. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63166. }
  63167. }
  63168. else {
  63169. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63170. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63171. }
  63172. this._computeTransformMatrices(this._transformMatrices, null);
  63173. }
  63174. this._isDirty = false;
  63175. this._scene._activeBones.addCount(this.bones.length, false);
  63176. };
  63177. Skeleton.prototype.getAnimatables = function () {
  63178. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63179. this._animatables = [];
  63180. for (var index = 0; index < this.bones.length; index++) {
  63181. this._animatables.push(this.bones[index]);
  63182. }
  63183. }
  63184. return this._animatables;
  63185. };
  63186. Skeleton.prototype.clone = function (name, id) {
  63187. var result = new Skeleton(name, id || name, this._scene);
  63188. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63189. for (var index = 0; index < this.bones.length; index++) {
  63190. var source = this.bones[index];
  63191. var parentBone = null;
  63192. var parent_1 = source.getParent();
  63193. if (parent_1) {
  63194. var parentIndex = this.bones.indexOf(parent_1);
  63195. parentBone = result.bones[parentIndex];
  63196. }
  63197. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63198. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63199. }
  63200. if (this._ranges) {
  63201. result._ranges = {};
  63202. for (var rangeName in this._ranges) {
  63203. var range = this._ranges[rangeName];
  63204. if (range) {
  63205. result._ranges[rangeName] = range.clone();
  63206. }
  63207. }
  63208. }
  63209. this._isDirty = true;
  63210. return result;
  63211. };
  63212. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63213. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63214. this.bones.forEach(function (bone) {
  63215. bone.animations.forEach(function (animation) {
  63216. animation.enableBlending = true;
  63217. animation.blendingSpeed = blendingSpeed;
  63218. });
  63219. });
  63220. };
  63221. Skeleton.prototype.dispose = function () {
  63222. this._meshesWithPoseMatrix = [];
  63223. // Animations
  63224. this.getScene().stopAnimation(this);
  63225. // Remove from scene
  63226. this.getScene().removeSkeleton(this);
  63227. };
  63228. Skeleton.prototype.serialize = function () {
  63229. var serializationObject = {};
  63230. serializationObject.name = this.name;
  63231. serializationObject.id = this.id;
  63232. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63233. serializationObject.bones = [];
  63234. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63235. for (var index = 0; index < this.bones.length; index++) {
  63236. var bone = this.bones[index];
  63237. var parent_2 = bone.getParent();
  63238. var serializedBone = {
  63239. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63240. name: bone.name,
  63241. matrix: bone.getBaseMatrix().toArray(),
  63242. rest: bone.getRestPose().toArray()
  63243. };
  63244. serializationObject.bones.push(serializedBone);
  63245. if (bone.length) {
  63246. serializedBone.length = bone.length;
  63247. }
  63248. if (bone.animations && bone.animations.length > 0) {
  63249. serializedBone.animation = bone.animations[0].serialize();
  63250. }
  63251. serializationObject.ranges = [];
  63252. for (var name in this._ranges) {
  63253. var source = this._ranges[name];
  63254. if (!source) {
  63255. continue;
  63256. }
  63257. var range = {};
  63258. range.name = name;
  63259. range.from = source.from;
  63260. range.to = source.to;
  63261. serializationObject.ranges.push(range);
  63262. }
  63263. }
  63264. return serializationObject;
  63265. };
  63266. Skeleton.Parse = function (parsedSkeleton, scene) {
  63267. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63268. if (parsedSkeleton.dimensionsAtRest) {
  63269. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63270. }
  63271. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63272. var index;
  63273. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63274. var parsedBone = parsedSkeleton.bones[index];
  63275. var parentBone = null;
  63276. if (parsedBone.parentBoneIndex > -1) {
  63277. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63278. }
  63279. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63280. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63281. if (parsedBone.length) {
  63282. bone.length = parsedBone.length;
  63283. }
  63284. if (parsedBone.animation) {
  63285. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63286. }
  63287. }
  63288. // placed after bones, so createAnimationRange can cascade down
  63289. if (parsedSkeleton.ranges) {
  63290. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63291. var data = parsedSkeleton.ranges[index];
  63292. skeleton.createAnimationRange(data.name, data.from, data.to);
  63293. }
  63294. }
  63295. return skeleton;
  63296. };
  63297. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63298. if (forceUpdate === void 0) { forceUpdate = false; }
  63299. var renderId = this._scene.getRenderId();
  63300. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63301. this.bones[0].computeAbsoluteTransforms();
  63302. this._lastAbsoluteTransformsUpdateId = renderId;
  63303. }
  63304. };
  63305. Skeleton.prototype.getPoseMatrix = function () {
  63306. var poseMatrix = null;
  63307. if (this._meshesWithPoseMatrix.length > 0) {
  63308. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63309. }
  63310. return poseMatrix;
  63311. };
  63312. Skeleton.prototype.sortBones = function () {
  63313. var bones = new Array();
  63314. var visited = new Array(this.bones.length);
  63315. for (var index = 0; index < this.bones.length; index++) {
  63316. this._sortBones(index, bones, visited);
  63317. }
  63318. this.bones = bones;
  63319. };
  63320. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63321. if (visited[index]) {
  63322. return;
  63323. }
  63324. visited[index] = true;
  63325. var bone = this.bones[index];
  63326. if (bone._index === undefined) {
  63327. bone._index = index;
  63328. }
  63329. var parentBone = bone.getParent();
  63330. if (parentBone) {
  63331. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63332. }
  63333. bones.push(bone);
  63334. };
  63335. return Skeleton;
  63336. }());
  63337. BABYLON.Skeleton = Skeleton;
  63338. })(BABYLON || (BABYLON = {}));
  63339. //# sourceMappingURL=babylon.skeleton.js.map
  63340. var BABYLON;
  63341. (function (BABYLON) {
  63342. var SphericalPolynomial = /** @class */ (function () {
  63343. function SphericalPolynomial() {
  63344. this.x = BABYLON.Vector3.Zero();
  63345. this.y = BABYLON.Vector3.Zero();
  63346. this.z = BABYLON.Vector3.Zero();
  63347. this.xx = BABYLON.Vector3.Zero();
  63348. this.yy = BABYLON.Vector3.Zero();
  63349. this.zz = BABYLON.Vector3.Zero();
  63350. this.xy = BABYLON.Vector3.Zero();
  63351. this.yz = BABYLON.Vector3.Zero();
  63352. this.zx = BABYLON.Vector3.Zero();
  63353. }
  63354. SphericalPolynomial.prototype.addAmbient = function (color) {
  63355. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63356. this.xx = this.xx.add(colorVector);
  63357. this.yy = this.yy.add(colorVector);
  63358. this.zz = this.zz.add(colorVector);
  63359. };
  63360. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63361. var result = new SphericalPolynomial();
  63362. result.x = harmonics.L11.scale(1.02333);
  63363. result.y = harmonics.L1_1.scale(1.02333);
  63364. result.z = harmonics.L10.scale(1.02333);
  63365. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63366. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63367. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63368. result.yz = harmonics.L2_1.scale(0.858086);
  63369. result.zx = harmonics.L21.scale(0.858086);
  63370. result.xy = harmonics.L2_2.scale(0.858086);
  63371. result.scale(1.0 / Math.PI);
  63372. return result;
  63373. };
  63374. SphericalPolynomial.prototype.scale = function (scale) {
  63375. this.x = this.x.scale(scale);
  63376. this.y = this.y.scale(scale);
  63377. this.z = this.z.scale(scale);
  63378. this.xx = this.xx.scale(scale);
  63379. this.yy = this.yy.scale(scale);
  63380. this.zz = this.zz.scale(scale);
  63381. this.yz = this.yz.scale(scale);
  63382. this.zx = this.zx.scale(scale);
  63383. this.xy = this.xy.scale(scale);
  63384. };
  63385. return SphericalPolynomial;
  63386. }());
  63387. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63388. var SphericalHarmonics = /** @class */ (function () {
  63389. function SphericalHarmonics() {
  63390. this.L00 = BABYLON.Vector3.Zero();
  63391. this.L1_1 = BABYLON.Vector3.Zero();
  63392. this.L10 = BABYLON.Vector3.Zero();
  63393. this.L11 = BABYLON.Vector3.Zero();
  63394. this.L2_2 = BABYLON.Vector3.Zero();
  63395. this.L2_1 = BABYLON.Vector3.Zero();
  63396. this.L20 = BABYLON.Vector3.Zero();
  63397. this.L21 = BABYLON.Vector3.Zero();
  63398. this.L22 = BABYLON.Vector3.Zero();
  63399. }
  63400. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63401. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63402. var c = colorVector.scale(deltaSolidAngle);
  63403. this.L00 = this.L00.add(c.scale(0.282095));
  63404. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63405. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63406. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63407. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63408. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63409. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63410. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63411. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63412. };
  63413. SphericalHarmonics.prototype.scale = function (scale) {
  63414. this.L00 = this.L00.scale(scale);
  63415. this.L1_1 = this.L1_1.scale(scale);
  63416. this.L10 = this.L10.scale(scale);
  63417. this.L11 = this.L11.scale(scale);
  63418. this.L2_2 = this.L2_2.scale(scale);
  63419. this.L2_1 = this.L2_1.scale(scale);
  63420. this.L20 = this.L20.scale(scale);
  63421. this.L21 = this.L21.scale(scale);
  63422. this.L22 = this.L22.scale(scale);
  63423. };
  63424. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63425. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63426. //
  63427. // E_lm = A_l * L_lm
  63428. //
  63429. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63430. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63431. // the scaling factors are given in equation 9.
  63432. // Constant (Band 0)
  63433. this.L00 = this.L00.scale(3.141593);
  63434. // Linear (Band 1)
  63435. this.L1_1 = this.L1_1.scale(2.094395);
  63436. this.L10 = this.L10.scale(2.094395);
  63437. this.L11 = this.L11.scale(2.094395);
  63438. // Quadratic (Band 2)
  63439. this.L2_2 = this.L2_2.scale(0.785398);
  63440. this.L2_1 = this.L2_1.scale(0.785398);
  63441. this.L20 = this.L20.scale(0.785398);
  63442. this.L21 = this.L21.scale(0.785398);
  63443. this.L22 = this.L22.scale(0.785398);
  63444. };
  63445. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63446. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63447. // L = (1/pi) * E * rho
  63448. //
  63449. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63450. this.scale(1.0 / Math.PI);
  63451. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63452. // (The pixel shader must apply albedo after texture fetches, etc).
  63453. };
  63454. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63455. var result = new SphericalHarmonics();
  63456. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63457. result.L1_1 = polynomial.y.scale(0.977204);
  63458. result.L10 = polynomial.z.scale(0.977204);
  63459. result.L11 = polynomial.x.scale(0.977204);
  63460. result.L2_2 = polynomial.xy.scale(1.16538);
  63461. result.L2_1 = polynomial.yz.scale(1.16538);
  63462. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63463. result.L21 = polynomial.zx.scale(1.16538);
  63464. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63465. result.scale(Math.PI);
  63466. return result;
  63467. };
  63468. return SphericalHarmonics;
  63469. }());
  63470. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63471. })(BABYLON || (BABYLON = {}));
  63472. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63473. var BABYLON;
  63474. (function (BABYLON) {
  63475. var Internals;
  63476. (function (Internals) {
  63477. var FileFaceOrientation = /** @class */ (function () {
  63478. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63479. this.name = name;
  63480. this.worldAxisForNormal = worldAxisForNormal;
  63481. this.worldAxisForFileX = worldAxisForFileX;
  63482. this.worldAxisForFileY = worldAxisForFileY;
  63483. }
  63484. return FileFaceOrientation;
  63485. }());
  63486. ;
  63487. /**
  63488. * Helper class dealing with the extraction of spherical polynomial dataArray
  63489. * from a cube map.
  63490. */
  63491. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63492. function CubeMapToSphericalPolynomialTools() {
  63493. }
  63494. /**
  63495. * Converts a texture to the according Spherical Polynomial data.
  63496. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63497. *
  63498. * @param texture The texture to extract the information from.
  63499. * @return The Spherical Polynomial data.
  63500. */
  63501. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63502. if (!texture.isCube) {
  63503. // Only supports cube Textures currently.
  63504. return null;
  63505. }
  63506. var size = texture.getSize().width;
  63507. var right = texture.readPixels(0);
  63508. var left = texture.readPixels(1);
  63509. var up;
  63510. var down;
  63511. if (texture.isRenderTarget) {
  63512. up = texture.readPixels(3);
  63513. down = texture.readPixels(2);
  63514. }
  63515. else {
  63516. up = texture.readPixels(2);
  63517. down = texture.readPixels(3);
  63518. }
  63519. var front = texture.readPixels(4);
  63520. var back = texture.readPixels(5);
  63521. var gammaSpace = texture.gammaSpace;
  63522. // Always read as RGBA.
  63523. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63524. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63525. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63526. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63527. }
  63528. var cubeInfo = {
  63529. size: size,
  63530. right: right,
  63531. left: left,
  63532. up: up,
  63533. down: down,
  63534. front: front,
  63535. back: back,
  63536. format: format,
  63537. type: type,
  63538. gammaSpace: gammaSpace,
  63539. };
  63540. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63541. };
  63542. /**
  63543. * Converts a cubemap to the according Spherical Polynomial data.
  63544. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63545. *
  63546. * @param cubeInfo The Cube map to extract the information from.
  63547. * @return The Spherical Polynomial data.
  63548. */
  63549. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63550. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63551. var totalSolidAngle = 0.0;
  63552. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63553. var du = 2.0 / cubeInfo.size;
  63554. var dv = du;
  63555. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63556. var minUV = du * 0.5 - 1.0;
  63557. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63558. var fileFace = this.FileFaces[faceIndex];
  63559. var dataArray = cubeInfo[fileFace.name];
  63560. var v = minUV;
  63561. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63562. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63563. // Because SP is still linear, so summation is fine in that basis.
  63564. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63565. for (var y = 0; y < cubeInfo.size; y++) {
  63566. var u = minUV;
  63567. for (var x = 0; x < cubeInfo.size; x++) {
  63568. // World direction (not normalised)
  63569. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63570. worldDirection.normalize();
  63571. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63572. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63573. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63574. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63575. // Handle Integer types.
  63576. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63577. r /= 255;
  63578. g /= 255;
  63579. b /= 255;
  63580. }
  63581. // Handle Gamma space textures.
  63582. if (cubeInfo.gammaSpace) {
  63583. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63584. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63585. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63586. }
  63587. var color = new BABYLON.Color3(r, g, b);
  63588. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63589. totalSolidAngle += deltaSolidAngle;
  63590. u += du;
  63591. }
  63592. v += dv;
  63593. }
  63594. }
  63595. // Solid angle for entire sphere is 4*pi
  63596. var sphereSolidAngle = 4.0 * Math.PI;
  63597. // Adjust the solid angle to allow for how many faces we processed.
  63598. var facesProcessed = 6.0;
  63599. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63600. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63601. // This is needed because the numerical integration over the cube uses a
  63602. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63603. // and also to compensate for accumulative error due to float precision in the summation.
  63604. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63605. sphericalHarmonics.scale(correctionFactor);
  63606. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63607. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63608. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63609. };
  63610. CubeMapToSphericalPolynomialTools.FileFaces = [
  63611. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63612. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63613. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63614. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63615. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63616. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63617. ];
  63618. return CubeMapToSphericalPolynomialTools;
  63619. }());
  63620. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63621. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63622. })(BABYLON || (BABYLON = {}));
  63623. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63624. var BABYLON;
  63625. (function (BABYLON) {
  63626. var Internals;
  63627. (function (Internals) {
  63628. /**
  63629. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63630. */
  63631. var PanoramaToCubeMapTools = /** @class */ (function () {
  63632. function PanoramaToCubeMapTools() {
  63633. }
  63634. /**
  63635. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63636. *
  63637. * @param float32Array The source data.
  63638. * @param inputWidth The width of the input panorama.
  63639. * @param inputhHeight The height of the input panorama.
  63640. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63641. * @return The cubemap data
  63642. */
  63643. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63644. if (!float32Array) {
  63645. throw "ConvertPanoramaToCubemap: input cannot be null";
  63646. }
  63647. if (float32Array.length != inputWidth * inputHeight * 3) {
  63648. throw "ConvertPanoramaToCubemap: input size is wrong";
  63649. }
  63650. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63651. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63652. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63653. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63654. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63655. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63656. return {
  63657. front: textureFront,
  63658. back: textureBack,
  63659. left: textureLeft,
  63660. right: textureRight,
  63661. up: textureUp,
  63662. down: textureDown,
  63663. size: size,
  63664. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63665. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63666. gammaSpace: false,
  63667. };
  63668. };
  63669. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63670. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63671. var textureArray = new Float32Array(buffer);
  63672. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63673. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63674. var dy = 1 / texSize;
  63675. var fy = 0;
  63676. for (var y = 0; y < texSize; y++) {
  63677. var xv1 = faceData[0];
  63678. var xv2 = faceData[2];
  63679. for (var x = 0; x < texSize; x++) {
  63680. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63681. v.normalize();
  63682. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63683. // 3 channels per pixels
  63684. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63685. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63686. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63687. xv1 = xv1.add(rotDX1);
  63688. xv2 = xv2.add(rotDX2);
  63689. }
  63690. fy += dy;
  63691. }
  63692. return textureArray;
  63693. };
  63694. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63695. var theta = Math.atan2(vDir.z, vDir.x);
  63696. var phi = Math.acos(vDir.y);
  63697. while (theta < -Math.PI)
  63698. theta += 2 * Math.PI;
  63699. while (theta > Math.PI)
  63700. theta -= 2 * Math.PI;
  63701. var dx = theta / Math.PI;
  63702. var dy = phi / Math.PI;
  63703. // recenter.
  63704. dx = dx * 0.5 + 0.5;
  63705. var px = Math.round(dx * inputWidth);
  63706. if (px < 0)
  63707. px = 0;
  63708. else if (px >= inputWidth)
  63709. px = inputWidth - 1;
  63710. var py = Math.round(dy * inputHeight);
  63711. if (py < 0)
  63712. py = 0;
  63713. else if (py >= inputHeight)
  63714. py = inputHeight - 1;
  63715. var inputY = (inputHeight - py - 1);
  63716. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63717. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63718. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63719. return {
  63720. r: r,
  63721. g: g,
  63722. b: b
  63723. };
  63724. };
  63725. PanoramaToCubeMapTools.FACE_FRONT = [
  63726. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63727. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63728. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63729. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63730. ];
  63731. PanoramaToCubeMapTools.FACE_BACK = [
  63732. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63733. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63734. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63735. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63736. ];
  63737. PanoramaToCubeMapTools.FACE_RIGHT = [
  63738. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63739. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63740. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63741. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63742. ];
  63743. PanoramaToCubeMapTools.FACE_LEFT = [
  63744. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63745. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63746. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63747. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63748. ];
  63749. PanoramaToCubeMapTools.FACE_DOWN = [
  63750. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63751. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63752. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63753. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63754. ];
  63755. PanoramaToCubeMapTools.FACE_UP = [
  63756. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63757. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63758. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63759. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63760. ];
  63761. return PanoramaToCubeMapTools;
  63762. }());
  63763. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63764. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63765. })(BABYLON || (BABYLON = {}));
  63766. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63767. var BABYLON;
  63768. (function (BABYLON) {
  63769. var Internals;
  63770. (function (Internals) {
  63771. ;
  63772. /**
  63773. * This groups tools to convert HDR texture to native colors array.
  63774. */
  63775. var HDRTools = /** @class */ (function () {
  63776. function HDRTools() {
  63777. }
  63778. HDRTools.Ldexp = function (mantissa, exponent) {
  63779. if (exponent > 1023) {
  63780. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63781. }
  63782. if (exponent < -1074) {
  63783. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63784. }
  63785. return mantissa * Math.pow(2, exponent);
  63786. };
  63787. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63788. if (exponent > 0) {
  63789. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63790. float32array[index + 0] = red * exponent;
  63791. float32array[index + 1] = green * exponent;
  63792. float32array[index + 2] = blue * exponent;
  63793. }
  63794. else {
  63795. float32array[index + 0] = 0;
  63796. float32array[index + 1] = 0;
  63797. float32array[index + 2] = 0;
  63798. }
  63799. };
  63800. HDRTools.readStringLine = function (uint8array, startIndex) {
  63801. var line = "";
  63802. var character = "";
  63803. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63804. character = String.fromCharCode(uint8array[i]);
  63805. if (character == "\n") {
  63806. break;
  63807. }
  63808. line += character;
  63809. }
  63810. return line;
  63811. };
  63812. /**
  63813. * Reads header information from an RGBE texture stored in a native array.
  63814. * More information on this format are available here:
  63815. * https://en.wikipedia.org/wiki/RGBE_image_format
  63816. *
  63817. * @param uint8array The binary file stored in native array.
  63818. * @return The header information.
  63819. */
  63820. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63821. var height = 0;
  63822. var width = 0;
  63823. var line = this.readStringLine(uint8array, 0);
  63824. if (line[0] != '#' || line[1] != '?') {
  63825. throw "Bad HDR Format.";
  63826. }
  63827. var endOfHeader = false;
  63828. var findFormat = false;
  63829. var lineIndex = 0;
  63830. do {
  63831. lineIndex += (line.length + 1);
  63832. line = this.readStringLine(uint8array, lineIndex);
  63833. if (line == "FORMAT=32-bit_rle_rgbe") {
  63834. findFormat = true;
  63835. }
  63836. else if (line.length == 0) {
  63837. endOfHeader = true;
  63838. }
  63839. } while (!endOfHeader);
  63840. if (!findFormat) {
  63841. throw "HDR Bad header format, unsupported FORMAT";
  63842. }
  63843. lineIndex += (line.length + 1);
  63844. line = this.readStringLine(uint8array, lineIndex);
  63845. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63846. var match = sizeRegexp.exec(line);
  63847. // TODO. Support +Y and -X if needed.
  63848. if (!match || match.length < 3) {
  63849. throw "HDR Bad header format, no size";
  63850. }
  63851. width = parseInt(match[2]);
  63852. height = parseInt(match[1]);
  63853. if (width < 8 || width > 0x7fff) {
  63854. throw "HDR Bad header format, unsupported size";
  63855. }
  63856. lineIndex += (line.length + 1);
  63857. return {
  63858. height: height,
  63859. width: width,
  63860. dataPosition: lineIndex
  63861. };
  63862. };
  63863. /**
  63864. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63865. * This RGBE texture needs to store the information as a panorama.
  63866. *
  63867. * More information on this format are available here:
  63868. * https://en.wikipedia.org/wiki/RGBE_image_format
  63869. *
  63870. * @param buffer The binary file stored in an array buffer.
  63871. * @param size The expected size of the extracted cubemap.
  63872. * @return The Cube Map information.
  63873. */
  63874. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63875. var uint8array = new Uint8Array(buffer);
  63876. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63877. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63878. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63879. return cubeMapData;
  63880. };
  63881. /**
  63882. * Returns the pixels data extracted from an RGBE texture.
  63883. * This pixels will be stored left to right up to down in the R G B order in one array.
  63884. *
  63885. * More information on this format are available here:
  63886. * https://en.wikipedia.org/wiki/RGBE_image_format
  63887. *
  63888. * @param uint8array The binary file stored in an array buffer.
  63889. * @param hdrInfo The header information of the file.
  63890. * @return The pixels data in RGB right to left up to down order.
  63891. */
  63892. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63893. // Keep for multi format supports.
  63894. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63895. };
  63896. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63897. var num_scanlines = hdrInfo.height;
  63898. var scanline_width = hdrInfo.width;
  63899. var a, b, c, d, count;
  63900. var dataIndex = hdrInfo.dataPosition;
  63901. var index = 0, endIndex = 0, i = 0;
  63902. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63903. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63904. // 3 channels of 4 bytes per pixel in float.
  63905. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63906. var resultArray = new Float32Array(resultBuffer);
  63907. // read in each successive scanline
  63908. while (num_scanlines > 0) {
  63909. a = uint8array[dataIndex++];
  63910. b = uint8array[dataIndex++];
  63911. c = uint8array[dataIndex++];
  63912. d = uint8array[dataIndex++];
  63913. if (a != 2 || b != 2 || (c & 0x80)) {
  63914. // this file is not run length encoded
  63915. throw "HDR Bad header format, not RLE";
  63916. }
  63917. if (((c << 8) | d) != scanline_width) {
  63918. throw "HDR Bad header format, wrong scan line width";
  63919. }
  63920. index = 0;
  63921. // read each of the four channels for the scanline into the buffer
  63922. for (i = 0; i < 4; i++) {
  63923. endIndex = (i + 1) * scanline_width;
  63924. while (index < endIndex) {
  63925. a = uint8array[dataIndex++];
  63926. b = uint8array[dataIndex++];
  63927. if (a > 128) {
  63928. // a run of the same value
  63929. count = a - 128;
  63930. if ((count == 0) || (count > endIndex - index)) {
  63931. throw "HDR Bad Format, bad scanline data (run)";
  63932. }
  63933. while (count-- > 0) {
  63934. scanLineArray[index++] = b;
  63935. }
  63936. }
  63937. else {
  63938. // a non-run
  63939. count = a;
  63940. if ((count == 0) || (count > endIndex - index)) {
  63941. throw "HDR Bad Format, bad scanline data (non-run)";
  63942. }
  63943. scanLineArray[index++] = b;
  63944. if (--count > 0) {
  63945. for (var j = 0; j < count; j++) {
  63946. scanLineArray[index++] = uint8array[dataIndex++];
  63947. }
  63948. }
  63949. }
  63950. }
  63951. }
  63952. // now convert data from buffer into floats
  63953. for (i = 0; i < scanline_width; i++) {
  63954. a = scanLineArray[i];
  63955. b = scanLineArray[i + scanline_width];
  63956. c = scanLineArray[i + 2 * scanline_width];
  63957. d = scanLineArray[i + 3 * scanline_width];
  63958. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63959. }
  63960. num_scanlines--;
  63961. }
  63962. return resultArray;
  63963. };
  63964. return HDRTools;
  63965. }());
  63966. Internals.HDRTools = HDRTools;
  63967. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63968. })(BABYLON || (BABYLON = {}));
  63969. //# sourceMappingURL=babylon.hdr.js.map
  63970. var BABYLON;
  63971. (function (BABYLON) {
  63972. /**
  63973. * This represents a texture coming from an HDR input.
  63974. *
  63975. * The only supported format is currently panorama picture stored in RGBE format.
  63976. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63977. */
  63978. var HDRCubeTexture = /** @class */ (function (_super) {
  63979. __extends(HDRCubeTexture, _super);
  63980. /**
  63981. * Instantiates an HDRTexture from the following parameters.
  63982. *
  63983. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63984. * @param scene The scene the texture will be used in
  63985. * @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.
  63986. * @param noMipmap Forces to not generate the mipmap if true
  63987. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63988. * @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)
  63989. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63990. */
  63991. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63992. if (noMipmap === void 0) { noMipmap = false; }
  63993. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63994. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63995. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63996. if (onLoad === void 0) { onLoad = null; }
  63997. if (onError === void 0) { onError = null; }
  63998. var _this = _super.call(this, scene) || this;
  63999. _this._useInGammaSpace = false;
  64000. _this._generateHarmonics = true;
  64001. _this._isBABYLONPreprocessed = false;
  64002. _this._onLoad = null;
  64003. _this._onError = null;
  64004. /**
  64005. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  64006. */
  64007. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64008. /**
  64009. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  64010. * This is usefull at run time to apply the good shader.
  64011. */
  64012. _this.isPMREM = false;
  64013. _this._isBlocking = true;
  64014. if (!url) {
  64015. return _this;
  64016. }
  64017. _this.name = url;
  64018. _this.url = url;
  64019. _this.hasAlpha = false;
  64020. _this.isCube = true;
  64021. _this._textureMatrix = BABYLON.Matrix.Identity();
  64022. _this._onLoad = onLoad;
  64023. _this._onError = onError;
  64024. _this.gammaSpace = false;
  64025. var caps = scene.getEngine().getCaps();
  64026. if (size) {
  64027. _this._isBABYLONPreprocessed = false;
  64028. _this._noMipmap = noMipmap;
  64029. _this._size = size;
  64030. _this._useInGammaSpace = useInGammaSpace;
  64031. _this._usePMREMGenerator = usePMREMGenerator &&
  64032. caps.textureLOD &&
  64033. caps.textureFloat &&
  64034. !_this._useInGammaSpace;
  64035. }
  64036. else {
  64037. _this._isBABYLONPreprocessed = true;
  64038. _this._noMipmap = false;
  64039. _this._useInGammaSpace = false;
  64040. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  64041. !_this._useInGammaSpace;
  64042. }
  64043. _this.isPMREM = _this._usePMREMGenerator;
  64044. _this._texture = _this._getFromCache(url, _this._noMipmap);
  64045. if (!_this._texture) {
  64046. if (!scene.useDelayedTextureLoading) {
  64047. _this.loadTexture();
  64048. }
  64049. else {
  64050. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64051. }
  64052. }
  64053. return _this;
  64054. }
  64055. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  64056. /**
  64057. * Gets wether or not the texture is blocking during loading.
  64058. */
  64059. get: function () {
  64060. return this._isBlocking;
  64061. },
  64062. /**
  64063. * Sets wether or not the texture is blocking during loading.
  64064. */
  64065. set: function (value) {
  64066. this._isBlocking = value;
  64067. },
  64068. enumerable: true,
  64069. configurable: true
  64070. });
  64071. /**
  64072. * Occurs when the file is a preprocessed .babylon.hdr file.
  64073. */
  64074. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  64075. var _this = this;
  64076. var mipLevels = 0;
  64077. var floatArrayView = null;
  64078. var scene = this.getScene();
  64079. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  64080. var mips = new Array();
  64081. if (!floatArrayView) {
  64082. return mips;
  64083. }
  64084. var startIndex = 30;
  64085. for (var level = 0; level < mipLevels; level++) {
  64086. mips.push([]);
  64087. // Fill each pixel of the mip level.
  64088. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  64089. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64090. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  64091. mips[level].push(faceData);
  64092. startIndex += faceSize;
  64093. }
  64094. }
  64095. return mips;
  64096. } : null;
  64097. var callback = function (buffer) {
  64098. var scene = _this.getScene();
  64099. if (!scene) {
  64100. return null;
  64101. }
  64102. // Create Native Array Views
  64103. var intArrayView = new Int32Array(buffer);
  64104. floatArrayView = new Float32Array(buffer);
  64105. // Fill header.
  64106. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64107. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64108. // Update Texture Information.
  64109. if (!_this._texture) {
  64110. return null;
  64111. }
  64112. _this._texture.updateSize(_this._size, _this._size);
  64113. // Fill polynomial information.
  64114. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64115. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64116. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64117. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64118. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64119. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64120. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64121. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64122. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64123. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64124. _this.sphericalPolynomial = sphericalPolynomial;
  64125. // Fill pixel data.
  64126. mipLevels = intArrayView[29]; // Number of mip levels.
  64127. var startIndex = 30;
  64128. var data = [];
  64129. var faceSize = Math.pow(_this._size, 2) * 3;
  64130. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64131. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64132. startIndex += faceSize;
  64133. }
  64134. var results = [];
  64135. var byteArray = null;
  64136. // Push each faces.
  64137. for (var k = 0; k < 6; k++) {
  64138. var dataFace = null;
  64139. // To be deprecated.
  64140. if (version === 1) {
  64141. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64142. dataFace = data[j];
  64143. }
  64144. // If special cases.
  64145. if (!mipmapGenerator && dataFace) {
  64146. if (!scene.getEngine().getCaps().textureFloat) {
  64147. // 3 channels of 1 bytes per pixel in bytes.
  64148. var byteBuffer = new ArrayBuffer(faceSize);
  64149. byteArray = new Uint8Array(byteBuffer);
  64150. }
  64151. for (var i = 0; i < _this._size * _this._size; i++) {
  64152. // Put in gamma space if requested.
  64153. if (_this._useInGammaSpace) {
  64154. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64155. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64156. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64157. }
  64158. // Convert to int texture for fallback.
  64159. if (byteArray) {
  64160. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64161. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64162. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64163. // May use luminance instead if the result is not accurate.
  64164. var max = Math.max(Math.max(r, g), b);
  64165. if (max > 255) {
  64166. var scale = 255 / max;
  64167. r *= scale;
  64168. g *= scale;
  64169. b *= scale;
  64170. }
  64171. byteArray[(i * 3) + 0] = r;
  64172. byteArray[(i * 3) + 1] = g;
  64173. byteArray[(i * 3) + 2] = b;
  64174. }
  64175. }
  64176. }
  64177. // Fill the array accordingly.
  64178. if (byteArray) {
  64179. results.push(byteArray);
  64180. }
  64181. else {
  64182. results.push(dataFace);
  64183. }
  64184. }
  64185. return results;
  64186. };
  64187. if (scene) {
  64188. 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);
  64189. }
  64190. };
  64191. /**
  64192. * Occurs when the file is raw .hdr file.
  64193. */
  64194. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64195. var _this = this;
  64196. var callback = function (buffer) {
  64197. var scene = _this.getScene();
  64198. if (!scene) {
  64199. return null;
  64200. }
  64201. // Extract the raw linear data.
  64202. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64203. // Generate harmonics if needed.
  64204. if (_this._generateHarmonics) {
  64205. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64206. _this.sphericalPolynomial = sphericalPolynomial;
  64207. }
  64208. var results = [];
  64209. var byteArray = null;
  64210. // Push each faces.
  64211. for (var j = 0; j < 6; j++) {
  64212. // Create uintarray fallback.
  64213. if (!scene.getEngine().getCaps().textureFloat) {
  64214. // 3 channels of 1 bytes per pixel in bytes.
  64215. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64216. byteArray = new Uint8Array(byteBuffer);
  64217. }
  64218. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64219. // If special cases.
  64220. if (_this._useInGammaSpace || byteArray) {
  64221. for (var i = 0; i < _this._size * _this._size; i++) {
  64222. // Put in gamma space if requested.
  64223. if (_this._useInGammaSpace) {
  64224. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64225. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64226. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64227. }
  64228. // Convert to int texture for fallback.
  64229. if (byteArray) {
  64230. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64231. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64232. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64233. // May use luminance instead if the result is not accurate.
  64234. var max = Math.max(Math.max(r, g), b);
  64235. if (max > 255) {
  64236. var scale = 255 / max;
  64237. r *= scale;
  64238. g *= scale;
  64239. b *= scale;
  64240. }
  64241. byteArray[(i * 3) + 0] = r;
  64242. byteArray[(i * 3) + 1] = g;
  64243. byteArray[(i * 3) + 2] = b;
  64244. }
  64245. }
  64246. }
  64247. if (byteArray) {
  64248. results.push(byteArray);
  64249. }
  64250. else {
  64251. results.push(dataFace);
  64252. }
  64253. }
  64254. return results;
  64255. };
  64256. var mipmapGenerator = null;
  64257. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64258. // if (!this._noMipmap &&
  64259. // this._usePMREMGenerator) {
  64260. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64261. // // Custom setup of the generator matching with the PBR shader values.
  64262. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64263. // this._size,
  64264. // this._size,
  64265. // 0,
  64266. // 3,
  64267. // this.getScene().getEngine().getCaps().textureFloat,
  64268. // 2048,
  64269. // 0.25,
  64270. // false,
  64271. // true);
  64272. // return generator.filterCubeMap();
  64273. // };
  64274. // }
  64275. var scene = this.getScene();
  64276. if (scene) {
  64277. 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);
  64278. }
  64279. };
  64280. /**
  64281. * Starts the loading process of the texture.
  64282. */
  64283. HDRCubeTexture.prototype.loadTexture = function () {
  64284. if (this._isBABYLONPreprocessed) {
  64285. this.loadBabylonTexture();
  64286. }
  64287. else {
  64288. this.loadHDRTexture();
  64289. }
  64290. };
  64291. HDRCubeTexture.prototype.clone = function () {
  64292. var scene = this.getScene();
  64293. if (!scene) {
  64294. return this;
  64295. }
  64296. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64297. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64298. // Base texture
  64299. newTexture.level = this.level;
  64300. newTexture.wrapU = this.wrapU;
  64301. newTexture.wrapV = this.wrapV;
  64302. newTexture.coordinatesIndex = this.coordinatesIndex;
  64303. newTexture.coordinatesMode = this.coordinatesMode;
  64304. return newTexture;
  64305. };
  64306. // Methods
  64307. HDRCubeTexture.prototype.delayLoad = function () {
  64308. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64309. return;
  64310. }
  64311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64312. this._texture = this._getFromCache(this.url, this._noMipmap);
  64313. if (!this._texture) {
  64314. this.loadTexture();
  64315. }
  64316. };
  64317. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64318. return this._textureMatrix;
  64319. };
  64320. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64321. this._textureMatrix = value;
  64322. };
  64323. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64324. var texture = null;
  64325. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64326. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64327. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64328. texture.name = parsedTexture.name;
  64329. texture.hasAlpha = parsedTexture.hasAlpha;
  64330. texture.level = parsedTexture.level;
  64331. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64332. texture.isBlocking = parsedTexture.isBlocking;
  64333. }
  64334. return texture;
  64335. };
  64336. HDRCubeTexture.prototype.serialize = function () {
  64337. if (!this.name) {
  64338. return null;
  64339. }
  64340. var serializationObject = {};
  64341. serializationObject.name = this.name;
  64342. serializationObject.hasAlpha = this.hasAlpha;
  64343. serializationObject.isCube = true;
  64344. serializationObject.level = this.level;
  64345. serializationObject.size = this._size;
  64346. serializationObject.coordinatesMode = this.coordinatesMode;
  64347. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64348. serializationObject.generateHarmonics = this._generateHarmonics;
  64349. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64350. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64351. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64352. serializationObject.noMipmap = this._noMipmap;
  64353. serializationObject.isBlocking = this._isBlocking;
  64354. return serializationObject;
  64355. };
  64356. /**
  64357. * Saves as a file the data contained in the texture in a binary format.
  64358. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64359. * as the spherical used in the lighting.
  64360. * @param url The HDR file url.
  64361. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64362. * @param onError Method called if any error happens during download.
  64363. * @return The packed binary data.
  64364. */
  64365. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64366. if (onError === void 0) { onError = null; }
  64367. var callback = function (buffer) {
  64368. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64369. // Returns a URL you can use as a href.
  64370. var objUrl = window.URL.createObjectURL(data);
  64371. // Simulates a link to it and click to dowload.
  64372. var a = document.createElement("a");
  64373. document.body.appendChild(a);
  64374. a.style.display = "none";
  64375. a.href = objUrl;
  64376. a.download = "envmap.babylon.hdr";
  64377. a.click();
  64378. };
  64379. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64380. };
  64381. /**
  64382. * Serializes the data contained in the texture in a binary format.
  64383. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64384. * as the spherical used in the lighting.
  64385. * @param url The HDR file url.
  64386. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64387. * @param onError Method called if any error happens during download.
  64388. * @return The packed binary data.
  64389. */
  64390. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64391. if (onError === void 0) { onError = null; }
  64392. // Needs the url tho create the texture.
  64393. if (!url) {
  64394. return;
  64395. }
  64396. // Check Power of two size.
  64397. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64398. return;
  64399. }
  64400. // Coming Back in 3.x.
  64401. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  64402. };
  64403. HDRCubeTexture._facesMapping = [
  64404. "right",
  64405. "left",
  64406. "up",
  64407. "down",
  64408. "front",
  64409. "back"
  64410. ];
  64411. return HDRCubeTexture;
  64412. }(BABYLON.BaseTexture));
  64413. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64414. })(BABYLON || (BABYLON = {}));
  64415. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64416. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64417. // Huge respect for a such great lib.
  64418. // Earcut license:
  64419. // Copyright (c) 2016, Mapbox
  64420. //
  64421. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64422. // with or without fee is hereby granted, provided that the above copyright notice
  64423. // and this permission notice appear in all copies.
  64424. //
  64425. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64426. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64427. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64428. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64429. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64430. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64431. // THIS SOFTWARE.
  64432. var Earcut;
  64433. (function (Earcut) {
  64434. /**
  64435. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64436. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64437. * @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).
  64438. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64439. */
  64440. function earcut(data, holeIndices, dim) {
  64441. dim = dim || 2;
  64442. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64443. if (!outerNode)
  64444. return triangles;
  64445. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64446. if (hasHoles)
  64447. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64448. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64449. if (data.length > 80 * dim) {
  64450. minX = maxX = data[0];
  64451. minY = maxY = data[1];
  64452. for (var i = dim; i < outerLen; i += dim) {
  64453. x = data[i];
  64454. y = data[i + 1];
  64455. if (x < minX)
  64456. minX = x;
  64457. if (y < minY)
  64458. minY = y;
  64459. if (x > maxX)
  64460. maxX = x;
  64461. if (y > maxY)
  64462. maxY = y;
  64463. }
  64464. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64465. size = Math.max(maxX - minX, maxY - minY);
  64466. }
  64467. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64468. return triangles;
  64469. }
  64470. Earcut.earcut = earcut;
  64471. var Node = /** @class */ (function () {
  64472. function Node(i, x, y) {
  64473. this.i = i;
  64474. this.x = x;
  64475. this.y = y;
  64476. this.prev = null;
  64477. this.next = null;
  64478. this.z = null;
  64479. this.prevZ = null;
  64480. this.nextZ = null;
  64481. this.steiner = false;
  64482. }
  64483. return Node;
  64484. }());
  64485. // create a circular doubly linked list from polygon points in the specified winding order
  64486. function linkedList(data, start, end, dim, clockwise) {
  64487. var i, last = null;
  64488. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64489. for (i = start; i < end; i += dim)
  64490. last = insertNode(i, data[i], data[i + 1], last);
  64491. }
  64492. else {
  64493. for (i = end - dim; i >= start; i -= dim)
  64494. last = insertNode(i, data[i], data[i + 1], last);
  64495. }
  64496. if (last && equals(last, last.next)) {
  64497. removeNode(last);
  64498. last = last.next;
  64499. }
  64500. return last;
  64501. }
  64502. // eliminate colinear or duplicate points
  64503. function filterPoints(start, end) {
  64504. if (!start)
  64505. return start;
  64506. if (!end)
  64507. end = start;
  64508. var p = start, again;
  64509. do {
  64510. again = false;
  64511. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64512. removeNode(p);
  64513. p = end = p.prev;
  64514. if (p === p.next)
  64515. return undefined;
  64516. again = true;
  64517. }
  64518. else {
  64519. p = p.next;
  64520. }
  64521. } while (again || p !== end);
  64522. return end;
  64523. }
  64524. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64525. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64526. if (!ear)
  64527. return;
  64528. // interlink polygon nodes in z-order
  64529. if (!pass && size)
  64530. indexCurve(ear, minX, minY, size);
  64531. var stop = ear, prev, next;
  64532. // iterate through ears, slicing them one by one
  64533. while (ear.prev !== ear.next) {
  64534. prev = ear.prev;
  64535. next = ear.next;
  64536. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64537. // cut off the triangle
  64538. triangles.push(prev.i / dim);
  64539. triangles.push(ear.i / dim);
  64540. triangles.push(next.i / dim);
  64541. removeNode(ear);
  64542. // skipping the next vertice leads to less sliver triangles
  64543. ear = next.next;
  64544. stop = next.next;
  64545. continue;
  64546. }
  64547. ear = next;
  64548. // if we looped through the whole remaining polygon and can't find any more ears
  64549. if (ear === stop) {
  64550. // try filtering points and slicing again
  64551. if (!pass) {
  64552. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64553. // if this didn't work, try curing all small self-intersections locally
  64554. }
  64555. else if (pass === 1) {
  64556. ear = cureLocalIntersections(ear, triangles, dim);
  64557. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64558. // as a last resort, try splitting the remaining polygon into two
  64559. }
  64560. else if (pass === 2) {
  64561. splitEarcut(ear, triangles, dim, minX, minY, size);
  64562. }
  64563. break;
  64564. }
  64565. }
  64566. }
  64567. // check whether a polygon node forms a valid ear with adjacent nodes
  64568. function isEar(ear) {
  64569. var a = ear.prev, b = ear, c = ear.next;
  64570. if (area(a, b, c) >= 0)
  64571. return false; // reflex, can't be an ear
  64572. // now make sure we don't have other points inside the potential ear
  64573. var p = ear.next.next;
  64574. while (p !== ear.prev) {
  64575. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64576. area(p.prev, p, p.next) >= 0)
  64577. return false;
  64578. p = p.next;
  64579. }
  64580. return true;
  64581. }
  64582. function isEarHashed(ear, minX, minY, size) {
  64583. var a = ear.prev, b = ear, c = ear.next;
  64584. if (area(a, b, c) >= 0)
  64585. return false; // reflex, can't be an ear
  64586. // triangle bbox; min & max are calculated like this for speed
  64587. 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);
  64588. // z-order range for the current triangle bbox;
  64589. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64590. // first look for points inside the triangle in increasing z-order
  64591. var p = ear.nextZ;
  64592. while (p && p.z <= maxZ) {
  64593. if (p !== ear.prev &&
  64594. p !== ear.next &&
  64595. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64596. area(p.prev, p, p.next) >= 0)
  64597. return false;
  64598. p = p.nextZ;
  64599. }
  64600. // then look for points in decreasing z-order
  64601. p = ear.prevZ;
  64602. while (p && p.z >= minZ) {
  64603. if (p !== ear.prev &&
  64604. p !== ear.next &&
  64605. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64606. area(p.prev, p, p.next) >= 0)
  64607. return false;
  64608. p = p.prevZ;
  64609. }
  64610. return true;
  64611. }
  64612. // go through all polygon nodes and cure small local self-intersections
  64613. function cureLocalIntersections(start, triangles, dim) {
  64614. var p = start;
  64615. do {
  64616. var a = p.prev, b = p.next.next;
  64617. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64618. triangles.push(a.i / dim);
  64619. triangles.push(p.i / dim);
  64620. triangles.push(b.i / dim);
  64621. // remove two nodes involved
  64622. removeNode(p);
  64623. removeNode(p.next);
  64624. p = start = b;
  64625. }
  64626. p = p.next;
  64627. } while (p !== start);
  64628. return p;
  64629. }
  64630. // try splitting polygon into two and triangulate them independently
  64631. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64632. // look for a valid diagonal that divides the polygon into two
  64633. var a = start;
  64634. do {
  64635. var b = a.next.next;
  64636. while (b !== a.prev) {
  64637. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64638. // split the polygon in two by the diagonal
  64639. var c = splitPolygon(a, b);
  64640. // filter colinear points around the cuts
  64641. a = filterPoints(a, a.next);
  64642. c = filterPoints(c, c.next);
  64643. // run earcut on each half
  64644. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64645. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64646. return;
  64647. }
  64648. b = b.next;
  64649. }
  64650. a = a.next;
  64651. } while (a !== start);
  64652. }
  64653. // link every hole into the outer loop, producing a single-ring polygon without holes
  64654. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64655. var queue = [], i, len, start, end, list;
  64656. for (i = 0, len = holeIndices.length; i < len; i++) {
  64657. start = holeIndices[i] * dim;
  64658. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64659. list = linkedList(data, start, end, dim, false);
  64660. if (list === list.next)
  64661. list.steiner = true;
  64662. queue.push(getLeftmost(list));
  64663. }
  64664. queue.sort(compareX);
  64665. // process holes from left to right
  64666. for (i = 0; i < queue.length; i++) {
  64667. eliminateHole(queue[i], outerNode);
  64668. outerNode = filterPoints(outerNode, outerNode.next);
  64669. }
  64670. return outerNode;
  64671. }
  64672. function compareX(a, b) {
  64673. return a.x - b.x;
  64674. }
  64675. // find a bridge between vertices that connects hole with an outer ring and and link it
  64676. function eliminateHole(hole, outerNode) {
  64677. outerNode = findHoleBridge(hole, outerNode);
  64678. if (outerNode) {
  64679. var b = splitPolygon(outerNode, hole);
  64680. filterPoints(b, b.next);
  64681. }
  64682. }
  64683. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64684. function findHoleBridge(hole, outerNode) {
  64685. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64686. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64687. // segment's endpoint with lesser x will be potential connection point
  64688. do {
  64689. if (hy <= p.y && hy >= p.next.y) {
  64690. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64691. if (x <= hx && x > qx) {
  64692. qx = x;
  64693. if (x === hx) {
  64694. if (hy === p.y)
  64695. return p;
  64696. if (hy === p.next.y)
  64697. return p.next;
  64698. }
  64699. m = p.x < p.next.x ? p : p.next;
  64700. }
  64701. }
  64702. p = p.next;
  64703. } while (p !== outerNode);
  64704. if (!m)
  64705. return null;
  64706. if (hx === qx)
  64707. return m.prev; // hole touches outer segment; pick lower endpoint
  64708. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64709. // if there are no points found, we have a valid connection;
  64710. // otherwise choose the point of the minimum angle with the ray as connection point
  64711. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64712. p = m.next;
  64713. while (p !== stop) {
  64714. if (hx >= p.x &&
  64715. p.x >= mx &&
  64716. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64717. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64718. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64719. m = p;
  64720. tanMin = tan;
  64721. }
  64722. }
  64723. p = p.next;
  64724. }
  64725. return m;
  64726. }
  64727. // interlink polygon nodes in z-order
  64728. function indexCurve(start, minX, minY, size) {
  64729. var p = start;
  64730. do {
  64731. if (p.z === null)
  64732. p.z = zOrder(p.x, p.y, minX, minY, size);
  64733. p.prevZ = p.prev;
  64734. p.nextZ = p.next;
  64735. p = p.next;
  64736. } while (p !== start);
  64737. p.prevZ.nextZ = null;
  64738. p.prevZ = null;
  64739. sortLinked(p);
  64740. }
  64741. // Simon Tatham's linked list merge sort algorithm
  64742. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64743. function sortLinked(list) {
  64744. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64745. do {
  64746. p = list;
  64747. list = null;
  64748. tail = null;
  64749. numMerges = 0;
  64750. while (p) {
  64751. numMerges++;
  64752. q = p;
  64753. pSize = 0;
  64754. for (i = 0; i < inSize; i++) {
  64755. pSize++;
  64756. q = q.nextZ;
  64757. if (!q)
  64758. break;
  64759. }
  64760. qSize = inSize;
  64761. while (pSize > 0 || (qSize > 0 && q)) {
  64762. if (pSize === 0) {
  64763. e = q;
  64764. q = q.nextZ;
  64765. qSize--;
  64766. }
  64767. else if (qSize === 0 || !q) {
  64768. e = p;
  64769. p = p.nextZ;
  64770. pSize--;
  64771. }
  64772. else if (p.z <= q.z) {
  64773. e = p;
  64774. p = p.nextZ;
  64775. pSize--;
  64776. }
  64777. else {
  64778. e = q;
  64779. q = q.nextZ;
  64780. qSize--;
  64781. }
  64782. if (tail)
  64783. tail.nextZ = e;
  64784. else
  64785. list = e;
  64786. e.prevZ = tail;
  64787. tail = e;
  64788. }
  64789. p = q;
  64790. }
  64791. tail.nextZ = null;
  64792. inSize *= 2;
  64793. } while (numMerges > 1);
  64794. return list;
  64795. }
  64796. // z-order of a point given coords and size of the data bounding box
  64797. function zOrder(x, y, minX, minY, size) {
  64798. // coords are transformed into non-negative 15-bit integer range
  64799. x = 32767 * (x - minX) / size;
  64800. y = 32767 * (y - minY) / size;
  64801. x = (x | (x << 8)) & 0x00FF00FF;
  64802. x = (x | (x << 4)) & 0x0F0F0F0F;
  64803. x = (x | (x << 2)) & 0x33333333;
  64804. x = (x | (x << 1)) & 0x55555555;
  64805. y = (y | (y << 8)) & 0x00FF00FF;
  64806. y = (y | (y << 4)) & 0x0F0F0F0F;
  64807. y = (y | (y << 2)) & 0x33333333;
  64808. y = (y | (y << 1)) & 0x55555555;
  64809. return x | (y << 1);
  64810. }
  64811. // find the leftmost node of a polygon ring
  64812. function getLeftmost(start) {
  64813. var p = start, leftmost = start;
  64814. do {
  64815. if (p.x < leftmost.x)
  64816. leftmost = p;
  64817. p = p.next;
  64818. } while (p !== start);
  64819. return leftmost;
  64820. }
  64821. // check if a point lies within a convex triangle
  64822. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64823. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64824. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64825. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64826. }
  64827. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64828. function isValidDiagonal(a, b) {
  64829. return a.next.i !== b.i &&
  64830. a.prev.i !== b.i &&
  64831. !intersectsPolygon(a, b) &&
  64832. locallyInside(a, b) &&
  64833. locallyInside(b, a) &&
  64834. middleInside(a, b);
  64835. }
  64836. // signed area of a triangle
  64837. function area(p, q, r) {
  64838. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64839. }
  64840. // check if two points are equal
  64841. function equals(p1, p2) {
  64842. return p1.x === p2.x && p1.y === p2.y;
  64843. }
  64844. // check if two segments intersect
  64845. function intersects(p1, q1, p2, q2) {
  64846. if ((equals(p1, q1) && equals(p2, q2)) ||
  64847. (equals(p1, q2) && equals(p2, q1)))
  64848. return true;
  64849. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64850. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64851. }
  64852. // check if a polygon diagonal intersects any polygon segments
  64853. function intersectsPolygon(a, b) {
  64854. var p = a;
  64855. do {
  64856. if (p.i !== a.i &&
  64857. p.next.i !== a.i &&
  64858. p.i !== b.i &&
  64859. p.next.i !== b.i &&
  64860. intersects(p, p.next, a, b))
  64861. return true;
  64862. p = p.next;
  64863. } while (p !== a);
  64864. return false;
  64865. }
  64866. // check if a polygon diagonal is locally inside the polygon
  64867. function locallyInside(a, b) {
  64868. return area(a.prev, a, a.next) < 0
  64869. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64870. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64871. }
  64872. // check if the middle point of a polygon diagonal is inside the polygon
  64873. function middleInside(a, b) {
  64874. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64875. do {
  64876. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64877. inside = !inside;
  64878. p = p.next;
  64879. } while (p !== a);
  64880. return inside;
  64881. }
  64882. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64883. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64884. function splitPolygon(a, b) {
  64885. 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;
  64886. a.next = b;
  64887. b.prev = a;
  64888. a2.next = an;
  64889. an.prev = a2;
  64890. b2.next = a2;
  64891. a2.prev = b2;
  64892. bp.next = b2;
  64893. b2.prev = bp;
  64894. return b2;
  64895. }
  64896. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64897. function insertNode(i, x, y, last) {
  64898. var p = new Node(i, x, y);
  64899. if (!last) {
  64900. p.prev = p;
  64901. p.next = p;
  64902. }
  64903. else {
  64904. p.next = last.next;
  64905. p.prev = last;
  64906. last.next.prev = p;
  64907. last.next = p;
  64908. }
  64909. return p;
  64910. }
  64911. function removeNode(p) {
  64912. p.next.prev = p.prev;
  64913. p.prev.next = p.next;
  64914. if (p.prevZ)
  64915. p.prevZ.nextZ = p.nextZ;
  64916. if (p.nextZ)
  64917. p.nextZ.prevZ = p.prevZ;
  64918. }
  64919. /**
  64920. * return a percentage difference between the polygon area and its triangulation area;
  64921. * used to verify correctness of triangulation
  64922. */
  64923. function deviation(data, holeIndices, dim, triangles) {
  64924. var hasHoles = holeIndices && holeIndices.length;
  64925. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64926. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64927. if (hasHoles) {
  64928. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64929. var start = holeIndices[i] * dim;
  64930. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64931. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64932. }
  64933. }
  64934. var trianglesArea = 0;
  64935. for (i = 0; i < triangles.length; i += 3) {
  64936. var a = triangles[i] * dim;
  64937. var b = triangles[i + 1] * dim;
  64938. var c = triangles[i + 2] * dim;
  64939. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64940. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64941. }
  64942. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64943. }
  64944. Earcut.deviation = deviation;
  64945. ;
  64946. function signedArea(data, start, end, dim) {
  64947. var sum = 0;
  64948. for (var i = start, j = end - dim; i < end; i += dim) {
  64949. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64950. j = i;
  64951. }
  64952. return sum;
  64953. }
  64954. /**
  64955. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64956. */
  64957. function flatten(data) {
  64958. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64959. for (var i = 0; i < data.length; i++) {
  64960. for (var j = 0; j < data[i].length; j++) {
  64961. for (var d = 0; d < dim; d++)
  64962. result.vertices.push(data[i][j][d]);
  64963. }
  64964. if (i > 0) {
  64965. holeIndex += data[i - 1].length;
  64966. result.holes.push(holeIndex);
  64967. }
  64968. }
  64969. return result;
  64970. }
  64971. Earcut.flatten = flatten;
  64972. ;
  64973. })(Earcut || (Earcut = {}));
  64974. //# sourceMappingURL=babylon.earcut.js.map
  64975. var BABYLON;
  64976. (function (BABYLON) {
  64977. var IndexedVector2 = /** @class */ (function (_super) {
  64978. __extends(IndexedVector2, _super);
  64979. function IndexedVector2(original, index) {
  64980. var _this = _super.call(this, original.x, original.y) || this;
  64981. _this.index = index;
  64982. return _this;
  64983. }
  64984. return IndexedVector2;
  64985. }(BABYLON.Vector2));
  64986. var PolygonPoints = /** @class */ (function () {
  64987. function PolygonPoints() {
  64988. this.elements = new Array();
  64989. }
  64990. PolygonPoints.prototype.add = function (originalPoints) {
  64991. var _this = this;
  64992. var result = new Array();
  64993. originalPoints.forEach(function (point) {
  64994. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64995. var newPoint = new IndexedVector2(point, _this.elements.length);
  64996. result.push(newPoint);
  64997. _this.elements.push(newPoint);
  64998. }
  64999. });
  65000. return result;
  65001. };
  65002. PolygonPoints.prototype.computeBounds = function () {
  65003. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65004. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65005. this.elements.forEach(function (point) {
  65006. // x
  65007. if (point.x < lmin.x) {
  65008. lmin.x = point.x;
  65009. }
  65010. else if (point.x > lmax.x) {
  65011. lmax.x = point.x;
  65012. }
  65013. // y
  65014. if (point.y < lmin.y) {
  65015. lmin.y = point.y;
  65016. }
  65017. else if (point.y > lmax.y) {
  65018. lmax.y = point.y;
  65019. }
  65020. });
  65021. return {
  65022. min: lmin,
  65023. max: lmax,
  65024. width: lmax.x - lmin.x,
  65025. height: lmax.y - lmin.y
  65026. };
  65027. };
  65028. return PolygonPoints;
  65029. }());
  65030. var Polygon = /** @class */ (function () {
  65031. function Polygon() {
  65032. }
  65033. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  65034. return [
  65035. new BABYLON.Vector2(xmin, ymin),
  65036. new BABYLON.Vector2(xmax, ymin),
  65037. new BABYLON.Vector2(xmax, ymax),
  65038. new BABYLON.Vector2(xmin, ymax)
  65039. ];
  65040. };
  65041. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  65042. if (cx === void 0) { cx = 0; }
  65043. if (cy === void 0) { cy = 0; }
  65044. if (numberOfSides === void 0) { numberOfSides = 32; }
  65045. var result = new Array();
  65046. var angle = 0;
  65047. var increment = (Math.PI * 2) / numberOfSides;
  65048. for (var i = 0; i < numberOfSides; i++) {
  65049. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  65050. angle -= increment;
  65051. }
  65052. return result;
  65053. };
  65054. Polygon.Parse = function (input) {
  65055. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  65056. var i, result = [];
  65057. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  65058. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  65059. }
  65060. return result;
  65061. };
  65062. Polygon.StartingAt = function (x, y) {
  65063. return BABYLON.Path2.StartingAt(x, y);
  65064. };
  65065. return Polygon;
  65066. }());
  65067. BABYLON.Polygon = Polygon;
  65068. var PolygonMeshBuilder = /** @class */ (function () {
  65069. function PolygonMeshBuilder(name, contours, scene) {
  65070. this._points = new PolygonPoints();
  65071. this._outlinepoints = new PolygonPoints();
  65072. this._holes = new Array();
  65073. this._epoints = new Array();
  65074. this._eholes = new Array();
  65075. this._name = name;
  65076. this._scene = scene;
  65077. var points;
  65078. if (contours instanceof BABYLON.Path2) {
  65079. points = contours.getPoints();
  65080. }
  65081. else {
  65082. points = contours;
  65083. }
  65084. this._addToepoint(points);
  65085. this._points.add(points);
  65086. this._outlinepoints.add(points);
  65087. }
  65088. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  65089. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  65090. var p = points_1[_i];
  65091. this._epoints.push(p.x, p.y);
  65092. }
  65093. };
  65094. PolygonMeshBuilder.prototype.addHole = function (hole) {
  65095. this._points.add(hole);
  65096. var holepoints = new PolygonPoints();
  65097. holepoints.add(hole);
  65098. this._holes.push(holepoints);
  65099. this._eholes.push(this._epoints.length / 2);
  65100. this._addToepoint(hole);
  65101. return this;
  65102. };
  65103. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65104. var _this = this;
  65105. if (updatable === void 0) { updatable = false; }
  65106. if (depth === void 0) { depth = 0; }
  65107. var result = new BABYLON.Mesh(this._name, this._scene);
  65108. var normals = new Array();
  65109. var positions = new Array();
  65110. var uvs = new Array();
  65111. var bounds = this._points.computeBounds();
  65112. this._points.elements.forEach(function (p) {
  65113. normals.push(0, 1.0, 0);
  65114. positions.push(p.x, 0, p.y);
  65115. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65116. });
  65117. var indices = new Array();
  65118. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65119. for (var i = 0; i < res.length; i++) {
  65120. indices.push(res[i]);
  65121. }
  65122. if (depth > 0) {
  65123. var positionscount = (positions.length / 3); //get the current pointcount
  65124. this._points.elements.forEach(function (p) {
  65125. normals.push(0, -1.0, 0);
  65126. positions.push(p.x, -depth, p.y);
  65127. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65128. });
  65129. var totalCount = indices.length;
  65130. for (var i = 0; i < totalCount; i += 3) {
  65131. var i0 = indices[i + 0];
  65132. var i1 = indices[i + 1];
  65133. var i2 = indices[i + 2];
  65134. indices.push(i2 + positionscount);
  65135. indices.push(i1 + positionscount);
  65136. indices.push(i0 + positionscount);
  65137. }
  65138. //Add the sides
  65139. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65140. this._holes.forEach(function (hole) {
  65141. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65142. });
  65143. }
  65144. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65145. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65146. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65147. result.setIndices(indices);
  65148. return result;
  65149. };
  65150. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65151. var StartIndex = positions.length / 3;
  65152. var ulength = 0;
  65153. for (var i = 0; i < points.elements.length; i++) {
  65154. var p = points.elements[i];
  65155. var p1;
  65156. if ((i + 1) > points.elements.length - 1) {
  65157. p1 = points.elements[0];
  65158. }
  65159. else {
  65160. p1 = points.elements[i + 1];
  65161. }
  65162. positions.push(p.x, 0, p.y);
  65163. positions.push(p.x, -depth, p.y);
  65164. positions.push(p1.x, 0, p1.y);
  65165. positions.push(p1.x, -depth, p1.y);
  65166. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65167. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65168. var v3 = v2.subtract(v1);
  65169. var v4 = new BABYLON.Vector3(0, 1, 0);
  65170. var vn = BABYLON.Vector3.Cross(v3, v4);
  65171. vn = vn.normalize();
  65172. uvs.push(ulength / bounds.width, 0);
  65173. uvs.push(ulength / bounds.width, 1);
  65174. ulength += v3.length();
  65175. uvs.push((ulength / bounds.width), 0);
  65176. uvs.push((ulength / bounds.width), 1);
  65177. if (!flip) {
  65178. normals.push(-vn.x, -vn.y, -vn.z);
  65179. normals.push(-vn.x, -vn.y, -vn.z);
  65180. normals.push(-vn.x, -vn.y, -vn.z);
  65181. normals.push(-vn.x, -vn.y, -vn.z);
  65182. indices.push(StartIndex);
  65183. indices.push(StartIndex + 1);
  65184. indices.push(StartIndex + 2);
  65185. indices.push(StartIndex + 1);
  65186. indices.push(StartIndex + 3);
  65187. indices.push(StartIndex + 2);
  65188. }
  65189. else {
  65190. normals.push(vn.x, vn.y, vn.z);
  65191. normals.push(vn.x, vn.y, vn.z);
  65192. normals.push(vn.x, vn.y, vn.z);
  65193. normals.push(vn.x, vn.y, vn.z);
  65194. indices.push(StartIndex);
  65195. indices.push(StartIndex + 2);
  65196. indices.push(StartIndex + 1);
  65197. indices.push(StartIndex + 1);
  65198. indices.push(StartIndex + 2);
  65199. indices.push(StartIndex + 3);
  65200. }
  65201. StartIndex += 4;
  65202. }
  65203. ;
  65204. };
  65205. return PolygonMeshBuilder;
  65206. }());
  65207. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65208. })(BABYLON || (BABYLON = {}));
  65209. //# sourceMappingURL=babylon.polygonMesh.js.map
  65210. var BABYLON;
  65211. (function (BABYLON) {
  65212. // Unique ID when we import meshes from Babylon to CSG
  65213. var currentCSGMeshId = 0;
  65214. // # class Vertex
  65215. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65216. // one to provide additional features like texture coordinates and vertex
  65217. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65218. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65219. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65220. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65221. // is not used anywhere else.
  65222. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65223. var Vertex = /** @class */ (function () {
  65224. function Vertex(pos, normal, uv) {
  65225. this.pos = pos;
  65226. this.normal = normal;
  65227. this.uv = uv;
  65228. }
  65229. Vertex.prototype.clone = function () {
  65230. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65231. };
  65232. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65233. // orientation of a polygon is flipped.
  65234. Vertex.prototype.flip = function () {
  65235. this.normal = this.normal.scale(-1);
  65236. };
  65237. // Create a new vertex between this vertex and `other` by linearly
  65238. // interpolating all properties using a parameter of `t`. Subclasses should
  65239. // override this to interpolate additional properties.
  65240. Vertex.prototype.interpolate = function (other, t) {
  65241. 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));
  65242. };
  65243. return Vertex;
  65244. }());
  65245. // # class Plane
  65246. // Represents a plane in 3D space.
  65247. var Plane = /** @class */ (function () {
  65248. function Plane(normal, w) {
  65249. this.normal = normal;
  65250. this.w = w;
  65251. }
  65252. Plane.FromPoints = function (a, b, c) {
  65253. var v0 = c.subtract(a);
  65254. var v1 = b.subtract(a);
  65255. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65256. return null;
  65257. }
  65258. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65259. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65260. };
  65261. Plane.prototype.clone = function () {
  65262. return new Plane(this.normal.clone(), this.w);
  65263. };
  65264. Plane.prototype.flip = function () {
  65265. this.normal.scaleInPlace(-1);
  65266. this.w = -this.w;
  65267. };
  65268. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65269. // fragments in the appropriate lists. Coplanar polygons go into either
  65270. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65271. // respect to this plane. Polygons in front or in back of this plane go into
  65272. // either `front` or `back`.
  65273. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65274. var COPLANAR = 0;
  65275. var FRONT = 1;
  65276. var BACK = 2;
  65277. var SPANNING = 3;
  65278. // Classify each point as well as the entire polygon into one of the above
  65279. // four classes.
  65280. var polygonType = 0;
  65281. var types = [];
  65282. var i;
  65283. var t;
  65284. for (i = 0; i < polygon.vertices.length; i++) {
  65285. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65286. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65287. polygonType |= type;
  65288. types.push(type);
  65289. }
  65290. // Put the polygon in the correct list, splitting it when necessary.
  65291. switch (polygonType) {
  65292. case COPLANAR:
  65293. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65294. break;
  65295. case FRONT:
  65296. front.push(polygon);
  65297. break;
  65298. case BACK:
  65299. back.push(polygon);
  65300. break;
  65301. case SPANNING:
  65302. var f = [], b = [];
  65303. for (i = 0; i < polygon.vertices.length; i++) {
  65304. var j = (i + 1) % polygon.vertices.length;
  65305. var ti = types[i], tj = types[j];
  65306. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65307. if (ti !== BACK)
  65308. f.push(vi);
  65309. if (ti !== FRONT)
  65310. b.push(ti !== BACK ? vi.clone() : vi);
  65311. if ((ti | tj) === SPANNING) {
  65312. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65313. var v = vi.interpolate(vj, t);
  65314. f.push(v);
  65315. b.push(v.clone());
  65316. }
  65317. }
  65318. var poly;
  65319. if (f.length >= 3) {
  65320. poly = new Polygon(f, polygon.shared);
  65321. if (poly.plane)
  65322. front.push(poly);
  65323. }
  65324. if (b.length >= 3) {
  65325. poly = new Polygon(b, polygon.shared);
  65326. if (poly.plane)
  65327. back.push(poly);
  65328. }
  65329. break;
  65330. }
  65331. };
  65332. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65333. // point is on the plane.
  65334. Plane.EPSILON = 1e-5;
  65335. return Plane;
  65336. }());
  65337. // # class Polygon
  65338. // Represents a convex polygon. The vertices used to initialize a polygon must
  65339. // be coplanar and form a convex loop.
  65340. //
  65341. // Each convex polygon has a `shared` property, which is shared between all
  65342. // polygons that are clones of each other or were split from the same polygon.
  65343. // This can be used to define per-polygon properties (such as surface color).
  65344. var Polygon = /** @class */ (function () {
  65345. function Polygon(vertices, shared) {
  65346. this.vertices = vertices;
  65347. this.shared = shared;
  65348. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65349. }
  65350. Polygon.prototype.clone = function () {
  65351. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65352. return new Polygon(vertices, this.shared);
  65353. };
  65354. Polygon.prototype.flip = function () {
  65355. this.vertices.reverse().map(function (v) { v.flip(); });
  65356. this.plane.flip();
  65357. };
  65358. return Polygon;
  65359. }());
  65360. // # class Node
  65361. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65362. // by picking a polygon to split along. That polygon (and all other coplanar
  65363. // polygons) are added directly to that node and the other polygons are added to
  65364. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65365. // no distinction between internal and leaf nodes.
  65366. var Node = /** @class */ (function () {
  65367. function Node(polygons) {
  65368. this.plane = null;
  65369. this.front = null;
  65370. this.back = null;
  65371. this.polygons = new Array();
  65372. if (polygons) {
  65373. this.build(polygons);
  65374. }
  65375. }
  65376. Node.prototype.clone = function () {
  65377. var node = new Node();
  65378. node.plane = this.plane && this.plane.clone();
  65379. node.front = this.front && this.front.clone();
  65380. node.back = this.back && this.back.clone();
  65381. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65382. return node;
  65383. };
  65384. // Convert solid space to empty space and empty space to solid space.
  65385. Node.prototype.invert = function () {
  65386. for (var i = 0; i < this.polygons.length; i++) {
  65387. this.polygons[i].flip();
  65388. }
  65389. if (this.plane) {
  65390. this.plane.flip();
  65391. }
  65392. if (this.front) {
  65393. this.front.invert();
  65394. }
  65395. if (this.back) {
  65396. this.back.invert();
  65397. }
  65398. var temp = this.front;
  65399. this.front = this.back;
  65400. this.back = temp;
  65401. };
  65402. // Recursively remove all polygons in `polygons` that are inside this BSP
  65403. // tree.
  65404. Node.prototype.clipPolygons = function (polygons) {
  65405. if (!this.plane)
  65406. return polygons.slice();
  65407. var front = new Array(), back = new Array();
  65408. for (var i = 0; i < polygons.length; i++) {
  65409. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65410. }
  65411. if (this.front) {
  65412. front = this.front.clipPolygons(front);
  65413. }
  65414. if (this.back) {
  65415. back = this.back.clipPolygons(back);
  65416. }
  65417. else {
  65418. back = [];
  65419. }
  65420. return front.concat(back);
  65421. };
  65422. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65423. // `bsp`.
  65424. Node.prototype.clipTo = function (bsp) {
  65425. this.polygons = bsp.clipPolygons(this.polygons);
  65426. if (this.front)
  65427. this.front.clipTo(bsp);
  65428. if (this.back)
  65429. this.back.clipTo(bsp);
  65430. };
  65431. // Return a list of all polygons in this BSP tree.
  65432. Node.prototype.allPolygons = function () {
  65433. var polygons = this.polygons.slice();
  65434. if (this.front)
  65435. polygons = polygons.concat(this.front.allPolygons());
  65436. if (this.back)
  65437. polygons = polygons.concat(this.back.allPolygons());
  65438. return polygons;
  65439. };
  65440. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65441. // new polygons are filtered down to the bottom of the tree and become new
  65442. // nodes there. Each set of polygons is partitioned using the first polygon
  65443. // (no heuristic is used to pick a good split).
  65444. Node.prototype.build = function (polygons) {
  65445. if (!polygons.length)
  65446. return;
  65447. if (!this.plane)
  65448. this.plane = polygons[0].plane.clone();
  65449. var front = new Array(), back = new Array();
  65450. for (var i = 0; i < polygons.length; i++) {
  65451. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65452. }
  65453. if (front.length) {
  65454. if (!this.front)
  65455. this.front = new Node();
  65456. this.front.build(front);
  65457. }
  65458. if (back.length) {
  65459. if (!this.back)
  65460. this.back = new Node();
  65461. this.back.build(back);
  65462. }
  65463. };
  65464. return Node;
  65465. }());
  65466. var CSG = /** @class */ (function () {
  65467. function CSG() {
  65468. this.polygons = new Array();
  65469. }
  65470. // Convert BABYLON.Mesh to BABYLON.CSG
  65471. CSG.FromMesh = function (mesh) {
  65472. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65473. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65474. if (mesh instanceof BABYLON.Mesh) {
  65475. mesh.computeWorldMatrix(true);
  65476. matrix = mesh.getWorldMatrix();
  65477. meshPosition = mesh.position.clone();
  65478. meshRotation = mesh.rotation.clone();
  65479. if (mesh.rotationQuaternion) {
  65480. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65481. }
  65482. meshScaling = mesh.scaling.clone();
  65483. }
  65484. else {
  65485. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65486. }
  65487. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65488. var subMeshes = mesh.subMeshes;
  65489. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65490. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65491. vertices = [];
  65492. for (var j = 0; j < 3; j++) {
  65493. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65494. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65495. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65496. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65497. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65498. vertex = new Vertex(position, normal, uv);
  65499. vertices.push(vertex);
  65500. }
  65501. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65502. // To handle the case of degenerated triangle
  65503. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65504. if (polygon.plane)
  65505. polygons.push(polygon);
  65506. }
  65507. }
  65508. var csg = CSG.FromPolygons(polygons);
  65509. csg.matrix = matrix;
  65510. csg.position = meshPosition;
  65511. csg.rotation = meshRotation;
  65512. csg.scaling = meshScaling;
  65513. csg.rotationQuaternion = meshRotationQuaternion;
  65514. currentCSGMeshId++;
  65515. return csg;
  65516. };
  65517. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65518. CSG.FromPolygons = function (polygons) {
  65519. var csg = new CSG();
  65520. csg.polygons = polygons;
  65521. return csg;
  65522. };
  65523. CSG.prototype.clone = function () {
  65524. var csg = new CSG();
  65525. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65526. csg.copyTransformAttributes(this);
  65527. return csg;
  65528. };
  65529. CSG.prototype.union = function (csg) {
  65530. var a = new Node(this.clone().polygons);
  65531. var b = new Node(csg.clone().polygons);
  65532. a.clipTo(b);
  65533. b.clipTo(a);
  65534. b.invert();
  65535. b.clipTo(a);
  65536. b.invert();
  65537. a.build(b.allPolygons());
  65538. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65539. };
  65540. CSG.prototype.unionInPlace = function (csg) {
  65541. var a = new Node(this.polygons);
  65542. var b = new Node(csg.polygons);
  65543. a.clipTo(b);
  65544. b.clipTo(a);
  65545. b.invert();
  65546. b.clipTo(a);
  65547. b.invert();
  65548. a.build(b.allPolygons());
  65549. this.polygons = a.allPolygons();
  65550. };
  65551. CSG.prototype.subtract = function (csg) {
  65552. var a = new Node(this.clone().polygons);
  65553. var b = new Node(csg.clone().polygons);
  65554. a.invert();
  65555. a.clipTo(b);
  65556. b.clipTo(a);
  65557. b.invert();
  65558. b.clipTo(a);
  65559. b.invert();
  65560. a.build(b.allPolygons());
  65561. a.invert();
  65562. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65563. };
  65564. CSG.prototype.subtractInPlace = function (csg) {
  65565. var a = new Node(this.polygons);
  65566. var b = new Node(csg.polygons);
  65567. a.invert();
  65568. a.clipTo(b);
  65569. b.clipTo(a);
  65570. b.invert();
  65571. b.clipTo(a);
  65572. b.invert();
  65573. a.build(b.allPolygons());
  65574. a.invert();
  65575. this.polygons = a.allPolygons();
  65576. };
  65577. CSG.prototype.intersect = function (csg) {
  65578. var a = new Node(this.clone().polygons);
  65579. var b = new Node(csg.clone().polygons);
  65580. a.invert();
  65581. b.clipTo(a);
  65582. b.invert();
  65583. a.clipTo(b);
  65584. b.clipTo(a);
  65585. a.build(b.allPolygons());
  65586. a.invert();
  65587. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65588. };
  65589. CSG.prototype.intersectInPlace = function (csg) {
  65590. var a = new Node(this.polygons);
  65591. var b = new Node(csg.polygons);
  65592. a.invert();
  65593. b.clipTo(a);
  65594. b.invert();
  65595. a.clipTo(b);
  65596. b.clipTo(a);
  65597. a.build(b.allPolygons());
  65598. a.invert();
  65599. this.polygons = a.allPolygons();
  65600. };
  65601. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65602. // not modified.
  65603. CSG.prototype.inverse = function () {
  65604. var csg = this.clone();
  65605. csg.inverseInPlace();
  65606. return csg;
  65607. };
  65608. CSG.prototype.inverseInPlace = function () {
  65609. this.polygons.map(function (p) { p.flip(); });
  65610. };
  65611. // This is used to keep meshes transformations so they can be restored
  65612. // when we build back a Babylon Mesh
  65613. // NB : All CSG operations are performed in world coordinates
  65614. CSG.prototype.copyTransformAttributes = function (csg) {
  65615. this.matrix = csg.matrix;
  65616. this.position = csg.position;
  65617. this.rotation = csg.rotation;
  65618. this.scaling = csg.scaling;
  65619. this.rotationQuaternion = csg.rotationQuaternion;
  65620. return this;
  65621. };
  65622. // Build Raw mesh from CSG
  65623. // Coordinates here are in world space
  65624. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65625. var matrix = this.matrix.clone();
  65626. matrix.invert();
  65627. 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;
  65628. if (keepSubMeshes) {
  65629. // Sort Polygons, since subMeshes are indices range
  65630. polygons.sort(function (a, b) {
  65631. if (a.shared.meshId === b.shared.meshId) {
  65632. return a.shared.subMeshId - b.shared.subMeshId;
  65633. }
  65634. else {
  65635. return a.shared.meshId - b.shared.meshId;
  65636. }
  65637. });
  65638. }
  65639. for (var i = 0, il = polygons.length; i < il; i++) {
  65640. polygon = polygons[i];
  65641. // Building SubMeshes
  65642. if (!subMesh_dict[polygon.shared.meshId]) {
  65643. subMesh_dict[polygon.shared.meshId] = {};
  65644. }
  65645. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65646. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65647. indexStart: +Infinity,
  65648. indexEnd: -Infinity,
  65649. materialIndex: polygon.shared.materialIndex
  65650. };
  65651. }
  65652. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65653. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65654. polygonIndices[0] = 0;
  65655. polygonIndices[1] = j - 1;
  65656. polygonIndices[2] = j;
  65657. for (var k = 0; k < 3; k++) {
  65658. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65659. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65660. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65661. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65662. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65663. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65664. // Check if 2 points can be merged
  65665. if (!(typeof vertex_idx !== 'undefined' &&
  65666. normals[vertex_idx * 3] === localNormal.x &&
  65667. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65668. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65669. uvs[vertex_idx * 2] === uv.x &&
  65670. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65671. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65672. uvs.push(uv.x, uv.y);
  65673. normals.push(normal.x, normal.y, normal.z);
  65674. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65675. }
  65676. indices.push(vertex_idx);
  65677. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65678. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65679. currentIndex++;
  65680. }
  65681. }
  65682. }
  65683. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65684. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65685. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65686. mesh.setIndices(indices, null);
  65687. if (keepSubMeshes) {
  65688. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65689. var materialIndexOffset = 0, materialMaxIndex;
  65690. mesh.subMeshes = new Array();
  65691. for (var m in subMesh_dict) {
  65692. materialMaxIndex = -1;
  65693. for (var sm in subMesh_dict[m]) {
  65694. subMesh_obj = subMesh_dict[m][sm];
  65695. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65696. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65697. }
  65698. materialIndexOffset += ++materialMaxIndex;
  65699. }
  65700. }
  65701. return mesh;
  65702. };
  65703. // Build Mesh from CSG taking material and transforms into account
  65704. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65705. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65706. mesh.material = material;
  65707. mesh.position.copyFrom(this.position);
  65708. mesh.rotation.copyFrom(this.rotation);
  65709. if (this.rotationQuaternion) {
  65710. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65711. }
  65712. mesh.scaling.copyFrom(this.scaling);
  65713. mesh.computeWorldMatrix(true);
  65714. return mesh;
  65715. };
  65716. return CSG;
  65717. }());
  65718. BABYLON.CSG = CSG;
  65719. })(BABYLON || (BABYLON = {}));
  65720. //# sourceMappingURL=babylon.csg.js.map
  65721. var BABYLON;
  65722. (function (BABYLON) {
  65723. var LensFlare = /** @class */ (function () {
  65724. function LensFlare(size, position, color, imgUrl, system) {
  65725. this.size = size;
  65726. this.position = position;
  65727. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65728. this.color = color || new BABYLON.Color3(1, 1, 1);
  65729. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65730. this._system = system;
  65731. system.lensFlares.push(this);
  65732. }
  65733. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65734. return new LensFlare(size, position, color, imgUrl, system);
  65735. };
  65736. LensFlare.prototype.dispose = function () {
  65737. if (this.texture) {
  65738. this.texture.dispose();
  65739. }
  65740. // Remove from scene
  65741. var index = this._system.lensFlares.indexOf(this);
  65742. this._system.lensFlares.splice(index, 1);
  65743. };
  65744. ;
  65745. return LensFlare;
  65746. }());
  65747. BABYLON.LensFlare = LensFlare;
  65748. })(BABYLON || (BABYLON = {}));
  65749. //# sourceMappingURL=babylon.lensFlare.js.map
  65750. var BABYLON;
  65751. (function (BABYLON) {
  65752. var LensFlareSystem = /** @class */ (function () {
  65753. function LensFlareSystem(name, emitter, scene) {
  65754. this.name = name;
  65755. this.lensFlares = new Array();
  65756. this.borderLimit = 300;
  65757. this.viewportBorder = 0;
  65758. this.layerMask = 0x0FFFFFFF;
  65759. this._vertexBuffers = {};
  65760. this._isEnabled = true;
  65761. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65762. this._emitter = emitter;
  65763. this.id = name;
  65764. scene.lensFlareSystems.push(this);
  65765. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65766. var engine = scene.getEngine();
  65767. // VBO
  65768. var vertices = [];
  65769. vertices.push(1, 1);
  65770. vertices.push(-1, 1);
  65771. vertices.push(-1, -1);
  65772. vertices.push(1, -1);
  65773. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65774. // Indices
  65775. var indices = [];
  65776. indices.push(0);
  65777. indices.push(1);
  65778. indices.push(2);
  65779. indices.push(0);
  65780. indices.push(2);
  65781. indices.push(3);
  65782. this._indexBuffer = engine.createIndexBuffer(indices);
  65783. // Effects
  65784. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65785. }
  65786. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65787. get: function () {
  65788. return this._isEnabled;
  65789. },
  65790. set: function (value) {
  65791. this._isEnabled = value;
  65792. },
  65793. enumerable: true,
  65794. configurable: true
  65795. });
  65796. LensFlareSystem.prototype.getScene = function () {
  65797. return this._scene;
  65798. };
  65799. LensFlareSystem.prototype.getEmitter = function () {
  65800. return this._emitter;
  65801. };
  65802. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65803. this._emitter = newEmitter;
  65804. };
  65805. LensFlareSystem.prototype.getEmitterPosition = function () {
  65806. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65807. };
  65808. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65809. var position = this.getEmitterPosition();
  65810. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65811. this._positionX = position.x;
  65812. this._positionY = position.y;
  65813. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65814. if (this.viewportBorder > 0) {
  65815. globalViewport.x -= this.viewportBorder;
  65816. globalViewport.y -= this.viewportBorder;
  65817. globalViewport.width += this.viewportBorder * 2;
  65818. globalViewport.height += this.viewportBorder * 2;
  65819. position.x += this.viewportBorder;
  65820. position.y += this.viewportBorder;
  65821. this._positionX += this.viewportBorder;
  65822. this._positionY += this.viewportBorder;
  65823. }
  65824. if (position.z > 0) {
  65825. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65826. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65827. return true;
  65828. }
  65829. return true;
  65830. }
  65831. return false;
  65832. };
  65833. LensFlareSystem.prototype._isVisible = function () {
  65834. if (!this._isEnabled || !this._scene.activeCamera) {
  65835. return false;
  65836. }
  65837. var emitterPosition = this.getEmitterPosition();
  65838. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65839. var distance = direction.length();
  65840. direction.normalize();
  65841. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65842. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65843. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65844. };
  65845. LensFlareSystem.prototype.render = function () {
  65846. if (!this._effect.isReady() || !this._scene.activeCamera)
  65847. return false;
  65848. var engine = this._scene.getEngine();
  65849. var viewport = this._scene.activeCamera.viewport;
  65850. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65851. // Position
  65852. if (!this.computeEffectivePosition(globalViewport)) {
  65853. return false;
  65854. }
  65855. // Visibility
  65856. if (!this._isVisible()) {
  65857. return false;
  65858. }
  65859. // Intensity
  65860. var awayX;
  65861. var awayY;
  65862. if (this._positionX < this.borderLimit + globalViewport.x) {
  65863. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65864. }
  65865. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65866. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65867. }
  65868. else {
  65869. awayX = 0;
  65870. }
  65871. if (this._positionY < this.borderLimit + globalViewport.y) {
  65872. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65873. }
  65874. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65875. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65876. }
  65877. else {
  65878. awayY = 0;
  65879. }
  65880. var away = (awayX > awayY) ? awayX : awayY;
  65881. away -= this.viewportBorder;
  65882. if (away > this.borderLimit) {
  65883. away = this.borderLimit;
  65884. }
  65885. var intensity = 1.0 - (away / this.borderLimit);
  65886. if (intensity < 0) {
  65887. return false;
  65888. }
  65889. if (intensity > 1.0) {
  65890. intensity = 1.0;
  65891. }
  65892. if (this.viewportBorder > 0) {
  65893. globalViewport.x += this.viewportBorder;
  65894. globalViewport.y += this.viewportBorder;
  65895. globalViewport.width -= this.viewportBorder * 2;
  65896. globalViewport.height -= this.viewportBorder * 2;
  65897. this._positionX -= this.viewportBorder;
  65898. this._positionY -= this.viewportBorder;
  65899. }
  65900. // Position
  65901. var centerX = globalViewport.x + globalViewport.width / 2;
  65902. var centerY = globalViewport.y + globalViewport.height / 2;
  65903. var distX = centerX - this._positionX;
  65904. var distY = centerY - this._positionY;
  65905. // Effects
  65906. engine.enableEffect(this._effect);
  65907. engine.setState(false);
  65908. engine.setDepthBuffer(false);
  65909. // VBOs
  65910. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65911. // Flares
  65912. for (var index = 0; index < this.lensFlares.length; index++) {
  65913. var flare = this.lensFlares[index];
  65914. engine.setAlphaMode(flare.alphaMode);
  65915. var x = centerX - (distX * flare.position);
  65916. var y = centerY - (distY * flare.position);
  65917. var cw = flare.size;
  65918. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65919. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65920. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65921. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65922. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65923. // Texture
  65924. this._effect.setTexture("textureSampler", flare.texture);
  65925. // Color
  65926. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65927. // Draw order
  65928. engine.draw(true, 0, 6);
  65929. }
  65930. engine.setDepthBuffer(true);
  65931. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65932. return true;
  65933. };
  65934. LensFlareSystem.prototype.dispose = function () {
  65935. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65936. if (vertexBuffer) {
  65937. vertexBuffer.dispose();
  65938. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65939. }
  65940. if (this._indexBuffer) {
  65941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65942. this._indexBuffer = null;
  65943. }
  65944. while (this.lensFlares.length) {
  65945. this.lensFlares[0].dispose();
  65946. }
  65947. // Remove from scene
  65948. var index = this._scene.lensFlareSystems.indexOf(this);
  65949. this._scene.lensFlareSystems.splice(index, 1);
  65950. };
  65951. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65952. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65953. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65954. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65955. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65956. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65957. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65958. var parsedFlare = parsedLensFlareSystem.flares[index];
  65959. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65960. }
  65961. return lensFlareSystem;
  65962. };
  65963. LensFlareSystem.prototype.serialize = function () {
  65964. var serializationObject = {};
  65965. serializationObject.id = this.id;
  65966. serializationObject.name = this.name;
  65967. serializationObject.emitterId = this.getEmitter().id;
  65968. serializationObject.borderLimit = this.borderLimit;
  65969. serializationObject.flares = [];
  65970. for (var index = 0; index < this.lensFlares.length; index++) {
  65971. var flare = this.lensFlares[index];
  65972. serializationObject.flares.push({
  65973. size: flare.size,
  65974. position: flare.position,
  65975. color: flare.color.asArray(),
  65976. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65977. });
  65978. }
  65979. return serializationObject;
  65980. };
  65981. return LensFlareSystem;
  65982. }());
  65983. BABYLON.LensFlareSystem = LensFlareSystem;
  65984. })(BABYLON || (BABYLON = {}));
  65985. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65986. var BABYLON;
  65987. (function (BABYLON) {
  65988. /**
  65989. * This is a holder class for the physics joint created by the physics plugin.
  65990. * It holds a set of functions to control the underlying joint.
  65991. */
  65992. var PhysicsJoint = /** @class */ (function () {
  65993. function PhysicsJoint(type, jointData) {
  65994. this.type = type;
  65995. this.jointData = jointData;
  65996. jointData.nativeParams = jointData.nativeParams || {};
  65997. }
  65998. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65999. get: function () {
  66000. return this._physicsJoint;
  66001. },
  66002. set: function (newJoint) {
  66003. if (this._physicsJoint) {
  66004. //remove from the wolrd
  66005. }
  66006. this._physicsJoint = newJoint;
  66007. },
  66008. enumerable: true,
  66009. configurable: true
  66010. });
  66011. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  66012. set: function (physicsPlugin) {
  66013. this._physicsPlugin = physicsPlugin;
  66014. },
  66015. enumerable: true,
  66016. configurable: true
  66017. });
  66018. /**
  66019. * Execute a function that is physics-plugin specific.
  66020. * @param {Function} func the function that will be executed.
  66021. * It accepts two parameters: the physics world and the physics joint.
  66022. */
  66023. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  66024. func(this._physicsPlugin.world, this._physicsJoint);
  66025. };
  66026. //TODO check if the native joints are the same
  66027. //Joint Types
  66028. PhysicsJoint.DistanceJoint = 0;
  66029. PhysicsJoint.HingeJoint = 1;
  66030. PhysicsJoint.BallAndSocketJoint = 2;
  66031. PhysicsJoint.WheelJoint = 3;
  66032. PhysicsJoint.SliderJoint = 4;
  66033. //OIMO
  66034. PhysicsJoint.PrismaticJoint = 5;
  66035. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  66036. PhysicsJoint.UniversalJoint = 6;
  66037. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  66038. //Cannon
  66039. //Similar to a Ball-Joint. Different in params
  66040. PhysicsJoint.PointToPointJoint = 8;
  66041. //Cannon only at the moment
  66042. PhysicsJoint.SpringJoint = 9;
  66043. PhysicsJoint.LockJoint = 10;
  66044. return PhysicsJoint;
  66045. }());
  66046. BABYLON.PhysicsJoint = PhysicsJoint;
  66047. /**
  66048. * A class representing a physics distance joint.
  66049. */
  66050. var DistanceJoint = /** @class */ (function (_super) {
  66051. __extends(DistanceJoint, _super);
  66052. function DistanceJoint(jointData) {
  66053. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  66054. }
  66055. /**
  66056. * Update the predefined distance.
  66057. */
  66058. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  66059. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  66060. };
  66061. return DistanceJoint;
  66062. }(PhysicsJoint));
  66063. BABYLON.DistanceJoint = DistanceJoint;
  66064. var MotorEnabledJoint = /** @class */ (function (_super) {
  66065. __extends(MotorEnabledJoint, _super);
  66066. function MotorEnabledJoint(type, jointData) {
  66067. return _super.call(this, type, jointData) || this;
  66068. }
  66069. /**
  66070. * Set the motor values.
  66071. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66072. * @param {number} force the force to apply
  66073. * @param {number} maxForce max force for this motor.
  66074. */
  66075. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  66076. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66077. };
  66078. /**
  66079. * Set the motor's limits.
  66080. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66081. */
  66082. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66083. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66084. };
  66085. return MotorEnabledJoint;
  66086. }(PhysicsJoint));
  66087. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  66088. /**
  66089. * This class represents a single hinge physics joint
  66090. */
  66091. var HingeJoint = /** @class */ (function (_super) {
  66092. __extends(HingeJoint, _super);
  66093. function HingeJoint(jointData) {
  66094. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  66095. }
  66096. /**
  66097. * Set the motor values.
  66098. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66099. * @param {number} force the force to apply
  66100. * @param {number} maxForce max force for this motor.
  66101. */
  66102. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66103. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66104. };
  66105. /**
  66106. * Set the motor's limits.
  66107. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66108. */
  66109. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66110. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66111. };
  66112. return HingeJoint;
  66113. }(MotorEnabledJoint));
  66114. BABYLON.HingeJoint = HingeJoint;
  66115. /**
  66116. * This class represents a dual hinge physics joint (same as wheel joint)
  66117. */
  66118. var Hinge2Joint = /** @class */ (function (_super) {
  66119. __extends(Hinge2Joint, _super);
  66120. function Hinge2Joint(jointData) {
  66121. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66122. }
  66123. /**
  66124. * Set the motor values.
  66125. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66126. * @param {number} force the force to apply
  66127. * @param {number} maxForce max force for this motor.
  66128. * @param {motorIndex} the motor's index, 0 or 1.
  66129. */
  66130. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66131. if (motorIndex === void 0) { motorIndex = 0; }
  66132. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66133. };
  66134. /**
  66135. * Set the motor limits.
  66136. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66137. * @param {number} upperLimit the upper limit
  66138. * @param {number} lowerLimit lower limit
  66139. * @param {motorIndex} the motor's index, 0 or 1.
  66140. */
  66141. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66142. if (motorIndex === void 0) { motorIndex = 0; }
  66143. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66144. };
  66145. return Hinge2Joint;
  66146. }(MotorEnabledJoint));
  66147. BABYLON.Hinge2Joint = Hinge2Joint;
  66148. })(BABYLON || (BABYLON = {}));
  66149. //# sourceMappingURL=babylon.physicsJoint.js.map
  66150. var BABYLON;
  66151. (function (BABYLON) {
  66152. var PhysicsImpostor = /** @class */ (function () {
  66153. function PhysicsImpostor(object, type, _options, _scene) {
  66154. if (_options === void 0) { _options = { mass: 0 }; }
  66155. var _this = this;
  66156. this.object = object;
  66157. this.type = type;
  66158. this._options = _options;
  66159. this._scene = _scene;
  66160. this._bodyUpdateRequired = false;
  66161. this._onBeforePhysicsStepCallbacks = new Array();
  66162. this._onAfterPhysicsStepCallbacks = new Array();
  66163. this._onPhysicsCollideCallbacks = [];
  66164. this._deltaPosition = BABYLON.Vector3.Zero();
  66165. this._isDisposed = false;
  66166. //temp variables for parent rotation calculations
  66167. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66168. this._tmpQuat = new BABYLON.Quaternion();
  66169. this._tmpQuat2 = new BABYLON.Quaternion();
  66170. /**
  66171. * this function is executed by the physics engine.
  66172. */
  66173. this.beforeStep = function () {
  66174. if (!_this._physicsEngine) {
  66175. return;
  66176. }
  66177. _this.object.translate(_this._deltaPosition, -1);
  66178. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66179. _this.object.computeWorldMatrix(false);
  66180. if (_this.object.parent && _this.object.rotationQuaternion) {
  66181. _this.getParentsRotation();
  66182. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66183. }
  66184. else {
  66185. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66186. }
  66187. if (!_this._options.disableBidirectionalTransformation) {
  66188. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66189. }
  66190. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66191. func(_this);
  66192. });
  66193. };
  66194. /**
  66195. * this function is executed by the physics engine.
  66196. */
  66197. this.afterStep = function () {
  66198. if (!_this._physicsEngine) {
  66199. return;
  66200. }
  66201. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66202. func(_this);
  66203. });
  66204. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66205. // object has now its world rotation. needs to be converted to local.
  66206. if (_this.object.parent && _this.object.rotationQuaternion) {
  66207. _this.getParentsRotation();
  66208. _this._tmpQuat.conjugateInPlace();
  66209. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66210. }
  66211. // take the position set and make it the absolute position of this object.
  66212. _this.object.setAbsolutePosition(_this.object.position);
  66213. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66214. _this.object.translate(_this._deltaPosition, 1);
  66215. };
  66216. /**
  66217. * Legacy collision detection event support
  66218. */
  66219. this.onCollideEvent = null;
  66220. //event and body object due to cannon's event-based architecture.
  66221. this.onCollide = function (e) {
  66222. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66223. return;
  66224. }
  66225. if (!_this._physicsEngine) {
  66226. return;
  66227. }
  66228. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66229. if (otherImpostor) {
  66230. // Legacy collision detection event support
  66231. if (_this.onCollideEvent) {
  66232. _this.onCollideEvent(_this, otherImpostor);
  66233. }
  66234. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66235. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66236. }).forEach(function (obj) {
  66237. obj.callback(_this, otherImpostor);
  66238. });
  66239. }
  66240. };
  66241. //sanity check!
  66242. if (!this.object) {
  66243. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66244. return;
  66245. }
  66246. //legacy support for old syntax.
  66247. if (!this._scene && object.getScene) {
  66248. this._scene = object.getScene();
  66249. }
  66250. if (!this._scene) {
  66251. return;
  66252. }
  66253. this._physicsEngine = this._scene.getPhysicsEngine();
  66254. if (!this._physicsEngine) {
  66255. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66256. }
  66257. else {
  66258. //set the object's quaternion, if not set
  66259. if (!this.object.rotationQuaternion) {
  66260. if (this.object.rotation) {
  66261. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66262. }
  66263. else {
  66264. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66265. }
  66266. }
  66267. //default options params
  66268. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66269. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66270. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66271. this._joints = [];
  66272. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66273. if (!this.object.parent || this._options.ignoreParent) {
  66274. this._init();
  66275. }
  66276. else if (this.object.parent.physicsImpostor) {
  66277. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66278. }
  66279. }
  66280. }
  66281. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66282. get: function () {
  66283. return this._isDisposed;
  66284. },
  66285. enumerable: true,
  66286. configurable: true
  66287. });
  66288. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66289. get: function () {
  66290. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66291. },
  66292. set: function (value) {
  66293. this.setMass(value);
  66294. },
  66295. enumerable: true,
  66296. configurable: true
  66297. });
  66298. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66299. get: function () {
  66300. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66301. },
  66302. set: function (value) {
  66303. if (!this._physicsEngine) {
  66304. return;
  66305. }
  66306. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66307. },
  66308. enumerable: true,
  66309. configurable: true
  66310. });
  66311. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66312. get: function () {
  66313. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66314. },
  66315. set: function (value) {
  66316. if (!this._physicsEngine) {
  66317. return;
  66318. }
  66319. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66320. },
  66321. enumerable: true,
  66322. configurable: true
  66323. });
  66324. /**
  66325. * This function will completly initialize this impostor.
  66326. * It will create a new body - but only if this mesh has no parent.
  66327. * If it has, this impostor will not be used other than to define the impostor
  66328. * of the child mesh.
  66329. */
  66330. PhysicsImpostor.prototype._init = function () {
  66331. if (!this._physicsEngine) {
  66332. return;
  66333. }
  66334. this._physicsEngine.removeImpostor(this);
  66335. this.physicsBody = null;
  66336. this._parent = this._parent || this._getPhysicsParent();
  66337. if (!this.parent || this._options.ignoreParent) {
  66338. this._physicsEngine.addImpostor(this);
  66339. }
  66340. };
  66341. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66342. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66343. var parentMesh = this.object.parent;
  66344. return parentMesh.physicsImpostor;
  66345. }
  66346. return null;
  66347. };
  66348. /**
  66349. * Should a new body be generated.
  66350. */
  66351. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66352. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66353. };
  66354. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66355. this.forceUpdate();
  66356. };
  66357. /**
  66358. * Force a regeneration of this or the parent's impostor's body.
  66359. * Use under cautious - This will remove all joints already implemented.
  66360. */
  66361. PhysicsImpostor.prototype.forceUpdate = function () {
  66362. this._init();
  66363. if (this.parent && !this._options.ignoreParent) {
  66364. this.parent.forceUpdate();
  66365. }
  66366. };
  66367. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66368. /*public get mesh(): AbstractMesh {
  66369. return this._mesh;
  66370. }*/
  66371. /**
  66372. * Gets the body that holds this impostor. Either its own, or its parent.
  66373. */
  66374. get: function () {
  66375. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66376. },
  66377. /**
  66378. * Set the physics body. Used mainly by the physics engine/plugin
  66379. */
  66380. set: function (physicsBody) {
  66381. if (this._physicsBody && this._physicsEngine) {
  66382. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66383. }
  66384. this._physicsBody = physicsBody;
  66385. this.resetUpdateFlags();
  66386. },
  66387. enumerable: true,
  66388. configurable: true
  66389. });
  66390. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66391. get: function () {
  66392. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66393. },
  66394. set: function (value) {
  66395. this._parent = value;
  66396. },
  66397. enumerable: true,
  66398. configurable: true
  66399. });
  66400. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66401. this._bodyUpdateRequired = false;
  66402. };
  66403. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66404. if (this.object.getBoundingInfo) {
  66405. var q = this.object.rotationQuaternion;
  66406. //reset rotation
  66407. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66408. //calculate the world matrix with no rotation
  66409. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66410. var boundingInfo = this.object.getBoundingInfo();
  66411. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66412. //bring back the rotation
  66413. this.object.rotationQuaternion = q;
  66414. //calculate the world matrix with the new rotation
  66415. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66416. return size;
  66417. }
  66418. else {
  66419. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66420. }
  66421. };
  66422. PhysicsImpostor.prototype.getObjectCenter = function () {
  66423. if (this.object.getBoundingInfo) {
  66424. var boundingInfo = this.object.getBoundingInfo();
  66425. return boundingInfo.boundingBox.centerWorld;
  66426. }
  66427. else {
  66428. return this.object.position;
  66429. }
  66430. };
  66431. /**
  66432. * Get a specific parametes from the options parameter.
  66433. */
  66434. PhysicsImpostor.prototype.getParam = function (paramName) {
  66435. return this._options[paramName];
  66436. };
  66437. /**
  66438. * Sets a specific parameter in the options given to the physics plugin
  66439. */
  66440. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66441. this._options[paramName] = value;
  66442. this._bodyUpdateRequired = true;
  66443. };
  66444. /**
  66445. * Specifically change the body's mass option. Won't recreate the physics body object
  66446. */
  66447. PhysicsImpostor.prototype.setMass = function (mass) {
  66448. if (this.getParam("mass") !== mass) {
  66449. this.setParam("mass", mass);
  66450. }
  66451. if (this._physicsEngine) {
  66452. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66453. }
  66454. };
  66455. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66456. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66457. };
  66458. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66459. if (this._physicsEngine) {
  66460. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66461. }
  66462. };
  66463. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66464. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66465. };
  66466. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66467. if (this._physicsEngine) {
  66468. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66469. }
  66470. };
  66471. /**
  66472. * Execute a function with the physics plugin native code.
  66473. * Provide a function the will have two variables - the world object and the physics body object.
  66474. */
  66475. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66476. if (this._physicsEngine) {
  66477. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66478. }
  66479. };
  66480. /**
  66481. * Register a function that will be executed before the physics world is stepping forward.
  66482. */
  66483. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66484. this._onBeforePhysicsStepCallbacks.push(func);
  66485. };
  66486. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66487. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66488. if (index > -1) {
  66489. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66490. }
  66491. else {
  66492. BABYLON.Tools.Warn("Function to remove was not found");
  66493. }
  66494. };
  66495. /**
  66496. * Register a function that will be executed after the physics step
  66497. */
  66498. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66499. this._onAfterPhysicsStepCallbacks.push(func);
  66500. };
  66501. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66502. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66503. if (index > -1) {
  66504. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66505. }
  66506. else {
  66507. BABYLON.Tools.Warn("Function to remove was not found");
  66508. }
  66509. };
  66510. /**
  66511. * register a function that will be executed when this impostor collides against a different body.
  66512. */
  66513. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66514. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66515. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66516. };
  66517. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66518. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66519. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66520. if (index > -1) {
  66521. this._onPhysicsCollideCallbacks.splice(index, 1);
  66522. }
  66523. else {
  66524. BABYLON.Tools.Warn("Function to remove was not found");
  66525. }
  66526. };
  66527. PhysicsImpostor.prototype.getParentsRotation = function () {
  66528. var parent = this.object.parent;
  66529. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66530. while (parent) {
  66531. if (parent.rotationQuaternion) {
  66532. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66533. }
  66534. else {
  66535. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66536. }
  66537. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66538. parent = parent.parent;
  66539. }
  66540. return this._tmpQuat;
  66541. };
  66542. /**
  66543. * Apply a force
  66544. */
  66545. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66546. if (this._physicsEngine) {
  66547. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66548. }
  66549. return this;
  66550. };
  66551. /**
  66552. * Apply an impulse
  66553. */
  66554. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66555. if (this._physicsEngine) {
  66556. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66557. }
  66558. return this;
  66559. };
  66560. /**
  66561. * A help function to create a joint.
  66562. */
  66563. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66564. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66565. this.addJoint(otherImpostor, joint);
  66566. return this;
  66567. };
  66568. /**
  66569. * Add a joint to this impostor with a different impostor.
  66570. */
  66571. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66572. this._joints.push({
  66573. otherImpostor: otherImpostor,
  66574. joint: joint
  66575. });
  66576. if (this._physicsEngine) {
  66577. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66578. }
  66579. return this;
  66580. };
  66581. /**
  66582. * Will keep this body still, in a sleep mode.
  66583. */
  66584. PhysicsImpostor.prototype.sleep = function () {
  66585. if (this._physicsEngine) {
  66586. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66587. }
  66588. return this;
  66589. };
  66590. /**
  66591. * Wake the body up.
  66592. */
  66593. PhysicsImpostor.prototype.wakeUp = function () {
  66594. if (this._physicsEngine) {
  66595. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66596. }
  66597. return this;
  66598. };
  66599. PhysicsImpostor.prototype.clone = function (newObject) {
  66600. if (!newObject)
  66601. return null;
  66602. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66603. };
  66604. PhysicsImpostor.prototype.dispose = function () {
  66605. var _this = this;
  66606. //no dispose if no physics engine is available.
  66607. if (!this._physicsEngine) {
  66608. return;
  66609. }
  66610. this._joints.forEach(function (j) {
  66611. if (_this._physicsEngine) {
  66612. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66613. }
  66614. });
  66615. //dispose the physics body
  66616. this._physicsEngine.removeImpostor(this);
  66617. if (this.parent) {
  66618. this.parent.forceUpdate();
  66619. }
  66620. else {
  66621. /*this._object.getChildMeshes().forEach(function(mesh) {
  66622. if (mesh.physicsImpostor) {
  66623. if (disposeChildren) {
  66624. mesh.physicsImpostor.dispose();
  66625. mesh.physicsImpostor = null;
  66626. }
  66627. }
  66628. })*/
  66629. }
  66630. this._isDisposed = true;
  66631. };
  66632. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66633. this._deltaPosition.copyFrom(position);
  66634. };
  66635. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66636. if (!this._deltaRotation) {
  66637. this._deltaRotation = new BABYLON.Quaternion();
  66638. }
  66639. this._deltaRotation.copyFrom(rotation);
  66640. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66641. };
  66642. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66643. if (this._physicsEngine) {
  66644. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66645. }
  66646. return this;
  66647. };
  66648. PhysicsImpostor.prototype.getRadius = function () {
  66649. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66650. };
  66651. /**
  66652. * Sync a bone with this impostor
  66653. * @param bone The bone to sync to the impostor.
  66654. * @param boneMesh The mesh that the bone is influencing.
  66655. * @param jointPivot The pivot of the joint / bone in local space.
  66656. * @param distToJoint Optional distance from the impostor to the joint.
  66657. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66658. */
  66659. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66660. var tempVec = PhysicsImpostor._tmpVecs[0];
  66661. var mesh = this.object;
  66662. if (mesh.rotationQuaternion) {
  66663. if (adjustRotation) {
  66664. var tempQuat = PhysicsImpostor._tmpQuat;
  66665. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66666. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66667. }
  66668. else {
  66669. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66670. }
  66671. }
  66672. tempVec.x = 0;
  66673. tempVec.y = 0;
  66674. tempVec.z = 0;
  66675. if (jointPivot) {
  66676. tempVec.x = jointPivot.x;
  66677. tempVec.y = jointPivot.y;
  66678. tempVec.z = jointPivot.z;
  66679. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66680. if (distToJoint === undefined || distToJoint === null) {
  66681. distToJoint = jointPivot.length();
  66682. }
  66683. tempVec.x *= distToJoint;
  66684. tempVec.y *= distToJoint;
  66685. tempVec.z *= distToJoint;
  66686. }
  66687. if (bone.getParent()) {
  66688. tempVec.addInPlace(mesh.getAbsolutePosition());
  66689. bone.setAbsolutePosition(tempVec, boneMesh);
  66690. }
  66691. else {
  66692. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66693. boneMesh.position.x -= tempVec.x;
  66694. boneMesh.position.y -= tempVec.y;
  66695. boneMesh.position.z -= tempVec.z;
  66696. }
  66697. };
  66698. /**
  66699. * Sync impostor to a bone
  66700. * @param bone The bone that the impostor will be synced to.
  66701. * @param boneMesh The mesh that the bone is influencing.
  66702. * @param jointPivot The pivot of the joint / bone in local space.
  66703. * @param distToJoint Optional distance from the impostor to the joint.
  66704. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66705. * @param boneAxis Optional vector3 axis the bone is aligned with
  66706. */
  66707. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66708. var mesh = this.object;
  66709. if (mesh.rotationQuaternion) {
  66710. if (adjustRotation) {
  66711. var tempQuat = PhysicsImpostor._tmpQuat;
  66712. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66713. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66714. }
  66715. else {
  66716. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66717. }
  66718. }
  66719. var pos = PhysicsImpostor._tmpVecs[0];
  66720. var boneDir = PhysicsImpostor._tmpVecs[1];
  66721. if (!boneAxis) {
  66722. boneAxis = PhysicsImpostor._tmpVecs[2];
  66723. boneAxis.x = 0;
  66724. boneAxis.y = 1;
  66725. boneAxis.z = 0;
  66726. }
  66727. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66728. bone.getAbsolutePositionToRef(boneMesh, pos);
  66729. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66730. distToJoint = jointPivot.length();
  66731. }
  66732. if (distToJoint !== undefined && distToJoint !== null) {
  66733. pos.x += boneDir.x * distToJoint;
  66734. pos.y += boneDir.y * distToJoint;
  66735. pos.z += boneDir.z * distToJoint;
  66736. }
  66737. mesh.setAbsolutePosition(pos);
  66738. };
  66739. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66740. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66741. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66742. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66743. //Impostor types
  66744. PhysicsImpostor.NoImpostor = 0;
  66745. PhysicsImpostor.SphereImpostor = 1;
  66746. PhysicsImpostor.BoxImpostor = 2;
  66747. PhysicsImpostor.PlaneImpostor = 3;
  66748. PhysicsImpostor.MeshImpostor = 4;
  66749. PhysicsImpostor.CylinderImpostor = 7;
  66750. PhysicsImpostor.ParticleImpostor = 8;
  66751. PhysicsImpostor.HeightmapImpostor = 9;
  66752. return PhysicsImpostor;
  66753. }());
  66754. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66755. })(BABYLON || (BABYLON = {}));
  66756. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66757. var BABYLON;
  66758. (function (BABYLON) {
  66759. var PhysicsEngine = /** @class */ (function () {
  66760. function PhysicsEngine(gravity, _physicsPlugin) {
  66761. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66762. this._physicsPlugin = _physicsPlugin;
  66763. //new methods and parameters
  66764. this._impostors = [];
  66765. this._joints = [];
  66766. if (!this._physicsPlugin.isSupported()) {
  66767. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66768. + "Please make sure it is included.");
  66769. }
  66770. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66771. this.setGravity(gravity);
  66772. this.setTimeStep();
  66773. }
  66774. PhysicsEngine.prototype.setGravity = function (gravity) {
  66775. this.gravity = gravity;
  66776. this._physicsPlugin.setGravity(this.gravity);
  66777. };
  66778. /**
  66779. * Set the time step of the physics engine.
  66780. * default is 1/60.
  66781. * To slow it down, enter 1/600 for example.
  66782. * To speed it up, 1/30
  66783. * @param {number} newTimeStep the new timestep to apply to this world.
  66784. */
  66785. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66786. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66787. this._physicsPlugin.setTimeStep(newTimeStep);
  66788. };
  66789. /**
  66790. * Get the time step of the physics engine.
  66791. */
  66792. PhysicsEngine.prototype.getTimeStep = function () {
  66793. return this._physicsPlugin.getTimeStep();
  66794. };
  66795. PhysicsEngine.prototype.dispose = function () {
  66796. this._impostors.forEach(function (impostor) {
  66797. impostor.dispose();
  66798. });
  66799. this._physicsPlugin.dispose();
  66800. };
  66801. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66802. return this._physicsPlugin.name;
  66803. };
  66804. /**
  66805. * Adding a new impostor for the impostor tracking.
  66806. * This will be done by the impostor itself.
  66807. * @param {PhysicsImpostor} impostor the impostor to add
  66808. */
  66809. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66810. impostor.uniqueId = this._impostors.push(impostor);
  66811. //if no parent, generate the body
  66812. if (!impostor.parent) {
  66813. this._physicsPlugin.generatePhysicsBody(impostor);
  66814. }
  66815. };
  66816. /**
  66817. * Remove an impostor from the engine.
  66818. * This impostor and its mesh will not longer be updated by the physics engine.
  66819. * @param {PhysicsImpostor} impostor the impostor to remove
  66820. */
  66821. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66822. var index = this._impostors.indexOf(impostor);
  66823. if (index > -1) {
  66824. var removed = this._impostors.splice(index, 1);
  66825. //Is it needed?
  66826. if (removed.length) {
  66827. //this will also remove it from the world.
  66828. removed[0].physicsBody = null;
  66829. }
  66830. }
  66831. };
  66832. /**
  66833. * Add a joint to the physics engine
  66834. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66835. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66836. * @param {PhysicsJoint} the joint that will connect both impostors.
  66837. */
  66838. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66839. var impostorJoint = {
  66840. mainImpostor: mainImpostor,
  66841. connectedImpostor: connectedImpostor,
  66842. joint: joint
  66843. };
  66844. joint.physicsPlugin = this._physicsPlugin;
  66845. this._joints.push(impostorJoint);
  66846. this._physicsPlugin.generateJoint(impostorJoint);
  66847. };
  66848. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66849. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66850. return (impostorJoint.connectedImpostor === connectedImpostor
  66851. && impostorJoint.joint === joint
  66852. && impostorJoint.mainImpostor === mainImpostor);
  66853. });
  66854. if (matchingJoints.length) {
  66855. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66856. //TODO remove it from the list as well
  66857. }
  66858. };
  66859. /**
  66860. * Called by the scene. no need to call it.
  66861. */
  66862. PhysicsEngine.prototype._step = function (delta) {
  66863. var _this = this;
  66864. //check if any mesh has no body / requires an update
  66865. this._impostors.forEach(function (impostor) {
  66866. if (impostor.isBodyInitRequired()) {
  66867. _this._physicsPlugin.generatePhysicsBody(impostor);
  66868. }
  66869. });
  66870. if (delta > 0.1) {
  66871. delta = 0.1;
  66872. }
  66873. else if (delta <= 0) {
  66874. delta = 1.0 / 60.0;
  66875. }
  66876. this._physicsPlugin.executeStep(delta, this._impostors);
  66877. };
  66878. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66879. return this._physicsPlugin;
  66880. };
  66881. PhysicsEngine.prototype.getImpostors = function () {
  66882. return this._impostors;
  66883. };
  66884. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66885. for (var i = 0; i < this._impostors.length; ++i) {
  66886. if (this._impostors[i].object === object) {
  66887. return this._impostors[i];
  66888. }
  66889. }
  66890. return null;
  66891. };
  66892. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66893. for (var i = 0; i < this._impostors.length; ++i) {
  66894. if (this._impostors[i].physicsBody === body) {
  66895. return this._impostors[i];
  66896. }
  66897. }
  66898. return null;
  66899. };
  66900. // Statics
  66901. PhysicsEngine.Epsilon = 0.001;
  66902. return PhysicsEngine;
  66903. }());
  66904. BABYLON.PhysicsEngine = PhysicsEngine;
  66905. })(BABYLON || (BABYLON = {}));
  66906. //# sourceMappingURL=babylon.physicsEngine.js.map
  66907. var BABYLON;
  66908. (function (BABYLON) {
  66909. /**
  66910. * The strenght of the force in correspondence to the distance of the affected object
  66911. */
  66912. var PhysicsRadialImpulseFallof;
  66913. (function (PhysicsRadialImpulseFallof) {
  66914. PhysicsRadialImpulseFallof[PhysicsRadialImpulseFallof["Constant"] = 0] = "Constant";
  66915. PhysicsRadialImpulseFallof[PhysicsRadialImpulseFallof["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  66916. })(PhysicsRadialImpulseFallof = BABYLON.PhysicsRadialImpulseFallof || (BABYLON.PhysicsRadialImpulseFallof = {}));
  66917. /**
  66918. * The strenght of the force in correspondence to the distance of the affected object
  66919. */
  66920. var PhysicsUpdraftMode;
  66921. (function (PhysicsUpdraftMode) {
  66922. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  66923. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  66924. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  66925. var PhysicsHelper = /** @class */ (function () {
  66926. function PhysicsHelper(scene) {
  66927. this._scene = scene;
  66928. this._physicsEngine = this._scene.getPhysicsEngine();
  66929. if (!this._physicsEngine) {
  66930. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  66931. }
  66932. }
  66933. /**
  66934. * @param {Vector3} origin the origin of the explosion
  66935. * @param {number} radius the explosion radius
  66936. * @param {number} strength the explosion strength
  66937. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear. Defaults to Constant
  66938. */
  66939. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  66940. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66941. if (!this._physicsEngine) {
  66942. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  66943. return null;
  66944. }
  66945. var impostors = this._physicsEngine.getImpostors();
  66946. if (impostors.length === 0) {
  66947. return null;
  66948. }
  66949. var event = new PhysicsRadialExplosionEvent(this._scene);
  66950. impostors.forEach(function (impostor) {
  66951. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66952. if (!impostorForceAndContactPoint) {
  66953. return;
  66954. }
  66955. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66956. });
  66957. event.dispose(false);
  66958. return event;
  66959. };
  66960. /**
  66961. * @param {Vector3} origin the origin of the explosion
  66962. * @param {number} radius the explosion radius
  66963. * @param {number} strength the explosion strength
  66964. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear. Defaults to Constant
  66965. */
  66966. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  66967. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66968. if (!this._physicsEngine) {
  66969. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66970. return null;
  66971. }
  66972. var impostors = this._physicsEngine.getImpostors();
  66973. if (impostors.length === 0) {
  66974. return null;
  66975. }
  66976. var event = new PhysicsRadialExplosionEvent(this._scene);
  66977. impostors.forEach(function (impostor) {
  66978. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66979. if (!impostorForceAndContactPoint) {
  66980. return;
  66981. }
  66982. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66983. });
  66984. event.dispose(false);
  66985. return event;
  66986. };
  66987. /**
  66988. * @param {Vector3} origin the origin of the explosion
  66989. * @param {number} radius the explosion radius
  66990. * @param {number} strength the explosion strength
  66991. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear. Defaults to Constant
  66992. */
  66993. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  66994. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66995. if (!this._physicsEngine) {
  66996. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66997. return null;
  66998. }
  66999. var impostors = this._physicsEngine.getImpostors();
  67000. if (impostors.length === 0) {
  67001. return null;
  67002. }
  67003. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  67004. event.dispose(false);
  67005. return event;
  67006. };
  67007. /**
  67008. * @param {Vector3} origin the origin of the updraft
  67009. * @param {number} radius the radius of the updraft
  67010. * @param {number} strength the strength of the updraft
  67011. * @param {number} height the height of the updraft
  67012. */
  67013. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  67014. if (!this._physicsEngine) {
  67015. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67016. return null;
  67017. }
  67018. if (this._physicsEngine.getImpostors().length === 0) {
  67019. return null;
  67020. }
  67021. var event = new PhysicsUpdraftEvent(this._physicsEngine, this._scene, origin, radius, strength, height, updraftMode);
  67022. event.dispose(false);
  67023. return event;
  67024. };
  67025. return PhysicsHelper;
  67026. }());
  67027. BABYLON.PhysicsHelper = PhysicsHelper;
  67028. /***** Radial explosion *****/
  67029. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  67030. function PhysicsRadialExplosionEvent(scene) {
  67031. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  67032. this._rays = [];
  67033. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  67034. this._scene = scene;
  67035. }
  67036. /**
  67037. * Returns the data related to the radial explosion event (sphere & rays).
  67038. * @returns {PhysicsRadialExplosionEventData}
  67039. */
  67040. PhysicsRadialExplosionEvent.prototype.getData = function () {
  67041. this._dataFetched = true;
  67042. return {
  67043. sphere: this._sphere,
  67044. rays: this._rays,
  67045. };
  67046. };
  67047. /**
  67048. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  67049. * @param impostor
  67050. * @param {Vector3} origin the origin of the explosion
  67051. * @param {number} radius the explosion radius
  67052. * @param {number} strength the explosion strength
  67053. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear
  67054. * @returns {Nullable<PhysicsForceAndContactPoint>}
  67055. */
  67056. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  67057. if (impostor.mass === 0) {
  67058. return null;
  67059. }
  67060. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  67061. return null;
  67062. }
  67063. var impostorObject = impostor.object;
  67064. var impostorObjectCenter = impostor.getObjectCenter();
  67065. var direction = impostorObjectCenter.subtract(origin);
  67066. var ray = new BABYLON.Ray(origin, direction, radius);
  67067. this._rays.push(ray);
  67068. var hit = ray.intersectsMesh(impostorObject);
  67069. var contactPoint = hit.pickedPoint;
  67070. if (!contactPoint) {
  67071. return null;
  67072. }
  67073. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  67074. if (distanceFromOrigin > radius) {
  67075. return null;
  67076. }
  67077. var multiplier = falloff === PhysicsRadialImpulseFallof.Constant
  67078. ? strength
  67079. : strength * (1 - (distanceFromOrigin / radius));
  67080. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67081. return { force: force, contactPoint: contactPoint };
  67082. };
  67083. /**
  67084. * Disposes the sphere.
  67085. * @param {bolean} force
  67086. */
  67087. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  67088. var _this = this;
  67089. if (force === void 0) { force = true; }
  67090. if (force) {
  67091. this._sphere.dispose();
  67092. }
  67093. else {
  67094. setTimeout(function () {
  67095. if (!_this._dataFetched) {
  67096. _this._sphere.dispose();
  67097. }
  67098. }, 0);
  67099. }
  67100. };
  67101. /*** Helpers ***/
  67102. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67103. if (!this._sphere) {
  67104. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67105. this._sphere.isVisible = false;
  67106. }
  67107. };
  67108. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67109. var impostorObject = impostor.object;
  67110. this._prepareSphere();
  67111. this._sphere.position = origin;
  67112. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67113. this._sphere._updateBoundingInfo();
  67114. this._sphere.computeWorldMatrix(true);
  67115. return this._sphere.intersectsMesh(impostorObject, true);
  67116. };
  67117. return PhysicsRadialExplosionEvent;
  67118. }());
  67119. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67120. /***** Gravitational Field *****/
  67121. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67122. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67123. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  67124. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67125. this._physicsHelper = physicsHelper;
  67126. this._scene = scene;
  67127. this._origin = origin;
  67128. this._radius = radius;
  67129. this._strength = strength;
  67130. this._falloff = falloff;
  67131. this._tickCallback = this._tick.bind(this);
  67132. }
  67133. /**
  67134. * Returns the data related to the gravitational field event (sphere).
  67135. * @returns {PhysicsGravitationalFieldEventData}
  67136. */
  67137. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67138. this._dataFetched = true;
  67139. return {
  67140. sphere: this._sphere,
  67141. };
  67142. };
  67143. /**
  67144. * Enables the gravitational field.
  67145. */
  67146. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67147. this._tickCallback.call(this);
  67148. this._scene.registerBeforeRender(this._tickCallback);
  67149. };
  67150. /**
  67151. * Disables the gravitational field.
  67152. */
  67153. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67154. this._scene.unregisterBeforeRender(this._tickCallback);
  67155. };
  67156. /**
  67157. * Disposes the sphere.
  67158. * @param {bolean} force
  67159. */
  67160. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67161. var _this = this;
  67162. if (force === void 0) { force = true; }
  67163. if (force) {
  67164. this._sphere.dispose();
  67165. }
  67166. else {
  67167. setTimeout(function () {
  67168. if (!_this._dataFetched) {
  67169. _this._sphere.dispose();
  67170. }
  67171. }, 0);
  67172. }
  67173. };
  67174. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67175. // Since the params won't change, we fetch the event only once
  67176. if (this._sphere) {
  67177. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67178. }
  67179. else {
  67180. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67181. if (radialExplosionEvent) {
  67182. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67183. }
  67184. }
  67185. };
  67186. return PhysicsGravitationalFieldEvent;
  67187. }());
  67188. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67189. /***** Updraft *****/
  67190. var PhysicsUpdraftEvent = /** @class */ (function () {
  67191. function PhysicsUpdraftEvent(physicsEngine, scene, origin, radius, strength, height, updraftMode) {
  67192. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67193. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67194. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67195. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67196. this._physicsEngine = physicsEngine;
  67197. this._scene = scene;
  67198. this._origin = origin;
  67199. this._radius = radius;
  67200. this._strength = strength;
  67201. this._height = height;
  67202. this._updraftMode = updraftMode;
  67203. // TODO: for this._cylinderPosition & this._originTop, take rotation into account
  67204. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67205. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67206. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67207. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67208. }
  67209. this._tickCallback = this._tick.bind(this);
  67210. }
  67211. /**
  67212. * Returns the data related to the updraft event (cylinder).
  67213. * @returns {PhysicsGravitationalFieldEventData}
  67214. */
  67215. PhysicsUpdraftEvent.prototype.getData = function () {
  67216. this._dataFetched = true;
  67217. return {
  67218. cylinder: this._cylinder,
  67219. };
  67220. };
  67221. /**
  67222. * Enables the updraft.
  67223. */
  67224. PhysicsUpdraftEvent.prototype.enable = function () {
  67225. this._tickCallback.call(this);
  67226. this._scene.registerBeforeRender(this._tickCallback);
  67227. };
  67228. /**
  67229. * Disables the cortex.
  67230. */
  67231. PhysicsUpdraftEvent.prototype.disable = function () {
  67232. this._scene.unregisterBeforeRender(this._tickCallback);
  67233. };
  67234. /**
  67235. * Disposes the sphere.
  67236. * @param {bolean} force
  67237. */
  67238. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67239. var _this = this;
  67240. if (force === void 0) { force = true; }
  67241. if (force) {
  67242. this._cylinder.dispose();
  67243. }
  67244. else {
  67245. setTimeout(function () {
  67246. if (!_this._dataFetched) {
  67247. _this._cylinder.dispose();
  67248. }
  67249. }, 0);
  67250. }
  67251. };
  67252. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67253. if (impostor.mass === 0) {
  67254. return null;
  67255. }
  67256. if (!this._intersectsWithCylinder(impostor)) {
  67257. return null;
  67258. }
  67259. var impostorObjectCenter = impostor.getObjectCenter();
  67260. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67261. var direction = this._originDirection;
  67262. }
  67263. else {
  67264. var direction = impostorObjectCenter.subtract(this._originTop);
  67265. }
  67266. var multiplier = this._strength * -1;
  67267. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67268. return { force: force, contactPoint: impostorObjectCenter };
  67269. };
  67270. PhysicsUpdraftEvent.prototype._tick = function () {
  67271. var _this = this;
  67272. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67273. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67274. if (!impostorForceAndContactPoint) {
  67275. return;
  67276. }
  67277. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67278. });
  67279. };
  67280. /*** Helpers ***/
  67281. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67282. if (!this._cylinder) {
  67283. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67284. height: this._height,
  67285. diameter: this._radius * 2,
  67286. }, this._scene);
  67287. this._cylinder.isVisible = false;
  67288. }
  67289. };
  67290. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67291. var impostorObject = impostor.object;
  67292. this._prepareCylinder();
  67293. this._cylinder.position = this._cylinderPosition;
  67294. return this._cylinder.intersectsMesh(impostorObject, true);
  67295. };
  67296. return PhysicsUpdraftEvent;
  67297. }());
  67298. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67299. })(BABYLON || (BABYLON = {}));
  67300. //# sourceMappingURL=babylon.physicsHelper.js.map
  67301. var BABYLON;
  67302. (function (BABYLON) {
  67303. var CannonJSPlugin = /** @class */ (function () {
  67304. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  67305. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  67306. if (iterations === void 0) { iterations = 10; }
  67307. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  67308. this.name = "CannonJSPlugin";
  67309. this._physicsMaterials = new Array();
  67310. this._fixedTimeStep = 1 / 60;
  67311. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  67312. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(15) : undefined);
  67313. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  67314. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  67315. this._tmpPosition = BABYLON.Vector3.Zero();
  67316. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  67317. this._tmpUnityRotation = new BABYLON.Quaternion();
  67318. if (!this.isSupported()) {
  67319. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  67320. return;
  67321. }
  67322. this.world = new this.BJSCANNON.World();
  67323. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  67324. this.world.solver.iterations = iterations;
  67325. }
  67326. CannonJSPlugin.prototype.setGravity = function (gravity) {
  67327. this.world.gravity.copy(gravity);
  67328. };
  67329. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  67330. this._fixedTimeStep = timeStep;
  67331. };
  67332. CannonJSPlugin.prototype.getTimeStep = function () {
  67333. return this._fixedTimeStep;
  67334. };
  67335. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  67336. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  67337. };
  67338. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67339. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67340. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67341. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  67342. };
  67343. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67344. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67345. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67346. impostor.physicsBody.applyForce(impulse, worldPoint);
  67347. };
  67348. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67349. //parent-child relationship. Does this impostor has a parent impostor?
  67350. if (impostor.parent) {
  67351. if (impostor.physicsBody) {
  67352. this.removePhysicsBody(impostor);
  67353. //TODO is that needed?
  67354. impostor.forceUpdate();
  67355. }
  67356. return;
  67357. }
  67358. //should a new body be created for this impostor?
  67359. if (impostor.isBodyInitRequired()) {
  67360. var shape = this._createShape(impostor);
  67361. //unregister events, if body is being changed
  67362. var oldBody = impostor.physicsBody;
  67363. if (oldBody) {
  67364. this.removePhysicsBody(impostor);
  67365. }
  67366. //create the body and material
  67367. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  67368. var bodyCreationObject = {
  67369. mass: impostor.getParam("mass"),
  67370. material: material
  67371. };
  67372. // A simple extend, in case native options were used.
  67373. var nativeOptions = impostor.getParam("nativeOptions");
  67374. for (var key in nativeOptions) {
  67375. if (nativeOptions.hasOwnProperty(key)) {
  67376. bodyCreationObject[key] = nativeOptions[key];
  67377. }
  67378. }
  67379. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  67380. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  67381. this.world.addEventListener("preStep", impostor.beforeStep);
  67382. this.world.addEventListener("postStep", impostor.afterStep);
  67383. impostor.physicsBody.addShape(shape);
  67384. this.world.add(impostor.physicsBody);
  67385. //try to keep the body moving in the right direction by taking old properties.
  67386. //Should be tested!
  67387. if (oldBody) {
  67388. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  67389. impostor.physicsBody[param].copy(oldBody[param]);
  67390. });
  67391. }
  67392. this._processChildMeshes(impostor);
  67393. }
  67394. //now update the body's transformation
  67395. this._updatePhysicsBodyTransformation(impostor);
  67396. };
  67397. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  67398. var _this = this;
  67399. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  67400. var currentRotation = mainImpostor.object.rotationQuaternion;
  67401. if (meshChildren.length) {
  67402. var processMesh = function (localPosition, mesh) {
  67403. if (!currentRotation || !mesh.rotationQuaternion) {
  67404. return;
  67405. }
  67406. var childImpostor = mesh.getPhysicsImpostor();
  67407. if (childImpostor) {
  67408. var parent = childImpostor.parent;
  67409. if (parent !== mainImpostor) {
  67410. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  67411. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  67412. if (childImpostor.physicsBody) {
  67413. _this.removePhysicsBody(childImpostor);
  67414. childImpostor.physicsBody = null;
  67415. }
  67416. childImpostor.parent = mainImpostor;
  67417. childImpostor.resetUpdateFlags();
  67418. 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));
  67419. //Add the mass of the children.
  67420. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  67421. }
  67422. }
  67423. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  67424. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  67425. };
  67426. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  67427. }
  67428. };
  67429. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67430. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  67431. this.world.removeEventListener("preStep", impostor.beforeStep);
  67432. this.world.removeEventListener("postStep", impostor.afterStep);
  67433. this.world.remove(impostor.physicsBody);
  67434. };
  67435. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67436. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67437. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67438. if (!mainBody || !connectedBody) {
  67439. return;
  67440. }
  67441. var constraint;
  67442. var jointData = impostorJoint.joint.jointData;
  67443. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  67444. var constraintData = {
  67445. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  67446. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  67447. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  67448. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  67449. maxForce: jointData.nativeParams.maxForce,
  67450. collideConnected: !!jointData.collision
  67451. };
  67452. switch (impostorJoint.joint.type) {
  67453. case BABYLON.PhysicsJoint.HingeJoint:
  67454. case BABYLON.PhysicsJoint.Hinge2Joint:
  67455. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  67456. break;
  67457. case BABYLON.PhysicsJoint.DistanceJoint:
  67458. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  67459. break;
  67460. case BABYLON.PhysicsJoint.SpringJoint:
  67461. var springData = jointData;
  67462. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  67463. restLength: springData.length,
  67464. stiffness: springData.stiffness,
  67465. damping: springData.damping,
  67466. localAnchorA: constraintData.pivotA,
  67467. localAnchorB: constraintData.pivotB
  67468. });
  67469. break;
  67470. case BABYLON.PhysicsJoint.LockJoint:
  67471. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  67472. break;
  67473. case BABYLON.PhysicsJoint.PointToPointJoint:
  67474. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67475. default:
  67476. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  67477. break;
  67478. }
  67479. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  67480. constraint.collideConnected = !!jointData.collision;
  67481. impostorJoint.joint.physicsJoint = constraint;
  67482. //don't add spring as constraint, as it is not one.
  67483. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  67484. this.world.addConstraint(constraint);
  67485. }
  67486. else {
  67487. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  67488. constraint.applyForce();
  67489. });
  67490. }
  67491. };
  67492. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67493. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  67494. };
  67495. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  67496. var index;
  67497. var mat;
  67498. for (index = 0; index < this._physicsMaterials.length; index++) {
  67499. mat = this._physicsMaterials[index];
  67500. if (mat.friction === friction && mat.restitution === restitution) {
  67501. return mat;
  67502. }
  67503. }
  67504. var currentMat = new this.BJSCANNON.Material(name);
  67505. currentMat.friction = friction;
  67506. currentMat.restitution = restitution;
  67507. this._physicsMaterials.push(currentMat);
  67508. return currentMat;
  67509. };
  67510. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  67511. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  67512. };
  67513. CannonJSPlugin.prototype._createShape = function (impostor) {
  67514. var object = impostor.object;
  67515. var returnValue;
  67516. var extendSize = impostor.getObjectExtendSize();
  67517. switch (impostor.type) {
  67518. case BABYLON.PhysicsImpostor.SphereImpostor:
  67519. var radiusX = extendSize.x;
  67520. var radiusY = extendSize.y;
  67521. var radiusZ = extendSize.z;
  67522. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  67523. break;
  67524. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  67525. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67526. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  67527. break;
  67528. case BABYLON.PhysicsImpostor.BoxImpostor:
  67529. var box = extendSize.scale(0.5);
  67530. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  67531. break;
  67532. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67533. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  67534. returnValue = new this.BJSCANNON.Plane();
  67535. break;
  67536. case BABYLON.PhysicsImpostor.MeshImpostor:
  67537. // should transform the vertex data to world coordinates!!
  67538. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  67539. var rawFaces = object.getIndices ? object.getIndices() : [];
  67540. if (!rawVerts)
  67541. return;
  67542. // get only scale! so the object could transform correctly.
  67543. var oldPosition = object.position.clone();
  67544. var oldRotation = object.rotation && object.rotation.clone();
  67545. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  67546. object.position.copyFromFloats(0, 0, 0);
  67547. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67548. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67549. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67550. var transform = object.computeWorldMatrix(true);
  67551. // convert rawVerts to object space
  67552. var temp = new Array();
  67553. var index;
  67554. for (index = 0; index < rawVerts.length; index += 3) {
  67555. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  67556. }
  67557. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  67558. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  67559. //now set back the transformation!
  67560. object.position.copyFrom(oldPosition);
  67561. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  67562. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  67563. break;
  67564. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  67565. var oldPosition2 = object.position.clone();
  67566. var oldRotation2 = object.rotation && object.rotation.clone();
  67567. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  67568. object.position.copyFromFloats(0, 0, 0);
  67569. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67570. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67571. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67572. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  67573. returnValue = this._createHeightmap(object);
  67574. object.position.copyFrom(oldPosition2);
  67575. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  67576. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  67577. object.computeWorldMatrix(true);
  67578. break;
  67579. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67580. returnValue = new this.BJSCANNON.Particle();
  67581. break;
  67582. }
  67583. return returnValue;
  67584. };
  67585. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  67586. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  67587. var transform = object.computeWorldMatrix(true);
  67588. // convert rawVerts to object space
  67589. var temp = new Array();
  67590. var index;
  67591. for (index = 0; index < pos.length; index += 3) {
  67592. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  67593. }
  67594. pos = temp;
  67595. var matrix = new Array();
  67596. //For now pointDepth will not be used and will be automatically calculated.
  67597. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  67598. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  67599. var boundingInfo = object.getBoundingInfo();
  67600. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  67601. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  67602. var elementSize = dim * 2 / arraySize;
  67603. for (var i = 0; i < pos.length; i = i + 3) {
  67604. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  67605. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  67606. var y = -pos[i + 2] + minY;
  67607. if (!matrix[x]) {
  67608. matrix[x] = [];
  67609. }
  67610. if (!matrix[x][z]) {
  67611. matrix[x][z] = y;
  67612. }
  67613. matrix[x][z] = Math.max(y, matrix[x][z]);
  67614. }
  67615. for (var x = 0; x <= arraySize; ++x) {
  67616. if (!matrix[x]) {
  67617. var loc = 1;
  67618. while (!matrix[(x + loc) % arraySize]) {
  67619. loc++;
  67620. }
  67621. matrix[x] = matrix[(x + loc) % arraySize].slice();
  67622. //console.log("missing x", x);
  67623. }
  67624. for (var z = 0; z <= arraySize; ++z) {
  67625. if (!matrix[x][z]) {
  67626. var loc = 1;
  67627. var newValue;
  67628. while (newValue === undefined) {
  67629. newValue = matrix[x][(z + loc++) % arraySize];
  67630. }
  67631. matrix[x][z] = newValue;
  67632. }
  67633. }
  67634. }
  67635. var shape = new this.BJSCANNON.Heightfield(matrix, {
  67636. elementSize: elementSize
  67637. });
  67638. //For future reference, needed for body transformation
  67639. shape.minY = minY;
  67640. return shape;
  67641. };
  67642. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  67643. var object = impostor.object;
  67644. //make sure it is updated...
  67645. object.computeWorldMatrix && object.computeWorldMatrix(true);
  67646. // The delta between the mesh position and the mesh bounding box center
  67647. var bInfo = object.getBoundingInfo();
  67648. if (!bInfo)
  67649. return;
  67650. var center = impostor.getObjectCenter();
  67651. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  67652. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  67653. this._tmpPosition.copyFrom(center);
  67654. var quaternion = object.rotationQuaternion;
  67655. if (!quaternion) {
  67656. return;
  67657. }
  67658. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  67659. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  67660. //-90 DEG in X, precalculated
  67661. quaternion = quaternion.multiply(this._minus90X);
  67662. //Invert! (Precalculated, 90 deg in X)
  67663. //No need to clone. this will never change.
  67664. impostor.setDeltaRotation(this._plus90X);
  67665. }
  67666. //If it is a heightfield, if should be centered.
  67667. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  67668. var mesh = object;
  67669. var boundingInfo = mesh.getBoundingInfo();
  67670. //calculate the correct body position:
  67671. var rotationQuaternion = mesh.rotationQuaternion;
  67672. mesh.rotationQuaternion = this._tmpUnityRotation;
  67673. mesh.computeWorldMatrix(true);
  67674. //get original center with no rotation
  67675. var c = center.clone();
  67676. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  67677. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  67678. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  67679. mesh.setPivotMatrix(p);
  67680. mesh.computeWorldMatrix(true);
  67681. //calculate the translation
  67682. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  67683. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  67684. //add it inverted to the delta
  67685. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  67686. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  67687. //rotation is back
  67688. mesh.rotationQuaternion = rotationQuaternion;
  67689. mesh.setPivotMatrix(oldPivot);
  67690. mesh.computeWorldMatrix(true);
  67691. }
  67692. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  67693. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  67694. //this._tmpPosition.copyFrom(object.position);
  67695. }
  67696. impostor.setDeltaPosition(this._tmpDeltaPosition);
  67697. //Now update the impostor object
  67698. impostor.physicsBody.position.copy(this._tmpPosition);
  67699. impostor.physicsBody.quaternion.copy(quaternion);
  67700. };
  67701. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67702. impostor.object.position.copyFrom(impostor.physicsBody.position);
  67703. if (impostor.object.rotationQuaternion) {
  67704. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  67705. }
  67706. };
  67707. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67708. impostor.physicsBody.position.copy(newPosition);
  67709. impostor.physicsBody.quaternion.copy(newRotation);
  67710. };
  67711. CannonJSPlugin.prototype.isSupported = function () {
  67712. return this.BJSCANNON !== undefined;
  67713. };
  67714. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67715. impostor.physicsBody.velocity.copy(velocity);
  67716. };
  67717. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67718. impostor.physicsBody.angularVelocity.copy(velocity);
  67719. };
  67720. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67721. var v = impostor.physicsBody.velocity;
  67722. if (!v) {
  67723. return null;
  67724. }
  67725. return new BABYLON.Vector3(v.x, v.y, v.z);
  67726. };
  67727. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67728. var v = impostor.physicsBody.angularVelocity;
  67729. if (!v) {
  67730. return null;
  67731. }
  67732. return new BABYLON.Vector3(v.x, v.y, v.z);
  67733. };
  67734. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67735. impostor.physicsBody.mass = mass;
  67736. impostor.physicsBody.updateMassProperties();
  67737. };
  67738. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  67739. return impostor.physicsBody.mass;
  67740. };
  67741. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  67742. return impostor.physicsBody.material.friction;
  67743. };
  67744. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67745. impostor.physicsBody.material.friction = friction;
  67746. };
  67747. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67748. return impostor.physicsBody.material.restitution;
  67749. };
  67750. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67751. impostor.physicsBody.material.restitution = restitution;
  67752. };
  67753. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  67754. impostor.physicsBody.sleep();
  67755. };
  67756. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  67757. impostor.physicsBody.wakeUp();
  67758. };
  67759. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67760. joint.physicsJoint.distance = maxDistance;
  67761. };
  67762. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67763. // if (!motorIndex) {
  67764. // joint.physicsJoint.enableMotor();
  67765. // }
  67766. // }
  67767. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67768. // if (!motorIndex) {
  67769. // joint.physicsJoint.disableMotor();
  67770. // }
  67771. // }
  67772. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67773. if (!motorIndex) {
  67774. joint.physicsJoint.enableMotor();
  67775. joint.physicsJoint.setMotorSpeed(speed);
  67776. if (maxForce) {
  67777. this.setLimit(joint, maxForce);
  67778. }
  67779. }
  67780. };
  67781. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  67782. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  67783. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  67784. };
  67785. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67786. var body = impostor.physicsBody;
  67787. mesh.position.x = body.position.x;
  67788. mesh.position.y = body.position.y;
  67789. mesh.position.z = body.position.z;
  67790. if (mesh.rotationQuaternion) {
  67791. mesh.rotationQuaternion.x = body.quaternion.x;
  67792. mesh.rotationQuaternion.y = body.quaternion.y;
  67793. mesh.rotationQuaternion.z = body.quaternion.z;
  67794. mesh.rotationQuaternion.w = body.quaternion.w;
  67795. }
  67796. };
  67797. CannonJSPlugin.prototype.getRadius = function (impostor) {
  67798. var shape = impostor.physicsBody.shapes[0];
  67799. return shape.boundingSphereRadius;
  67800. };
  67801. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67802. var shape = impostor.physicsBody.shapes[0];
  67803. result.x = shape.halfExtents.x * 2;
  67804. result.y = shape.halfExtents.y * 2;
  67805. result.z = shape.halfExtents.z * 2;
  67806. };
  67807. CannonJSPlugin.prototype.dispose = function () {
  67808. };
  67809. return CannonJSPlugin;
  67810. }());
  67811. BABYLON.CannonJSPlugin = CannonJSPlugin;
  67812. })(BABYLON || (BABYLON = {}));
  67813. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  67814. var BABYLON;
  67815. (function (BABYLON) {
  67816. var OimoJSPlugin = /** @class */ (function () {
  67817. function OimoJSPlugin(iterations) {
  67818. this.name = "OimoJSPlugin";
  67819. this._tmpImpostorsArray = [];
  67820. this._tmpPositionVector = BABYLON.Vector3.Zero();
  67821. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(16) : undefined);
  67822. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  67823. this.world.worldscale(1);
  67824. this.world.clear();
  67825. //making sure no stats are calculated
  67826. this.world.isNoStat = true;
  67827. }
  67828. OimoJSPlugin.prototype.setGravity = function (gravity) {
  67829. this.world.gravity.copy(gravity);
  67830. };
  67831. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  67832. this.world.timeStep = timeStep;
  67833. };
  67834. OimoJSPlugin.prototype.getTimeStep = function () {
  67835. return this.world.timeStep;
  67836. };
  67837. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  67838. var _this = this;
  67839. impostors.forEach(function (impostor) {
  67840. impostor.beforeStep();
  67841. });
  67842. this.world.step();
  67843. impostors.forEach(function (impostor) {
  67844. impostor.afterStep();
  67845. //update the ordered impostors array
  67846. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  67847. });
  67848. //check for collisions
  67849. var contact = this.world.contacts;
  67850. while (contact !== null) {
  67851. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  67852. contact = contact.next;
  67853. continue;
  67854. }
  67855. //is this body colliding with any other? get the impostor
  67856. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  67857. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  67858. if (!mainImpostor || !collidingImpostor) {
  67859. contact = contact.next;
  67860. continue;
  67861. }
  67862. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  67863. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  67864. contact = contact.next;
  67865. }
  67866. };
  67867. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67868. var mass = impostor.physicsBody.massInfo.mass;
  67869. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  67870. };
  67871. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67872. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  67873. this.applyImpulse(impostor, force, contactPoint);
  67874. };
  67875. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67876. var _this = this;
  67877. //parent-child relationship. Does this impostor has a parent impostor?
  67878. if (impostor.parent) {
  67879. if (impostor.physicsBody) {
  67880. this.removePhysicsBody(impostor);
  67881. //TODO is that needed?
  67882. impostor.forceUpdate();
  67883. }
  67884. return;
  67885. }
  67886. if (impostor.isBodyInitRequired()) {
  67887. var bodyConfig = {
  67888. name: impostor.uniqueId,
  67889. //Oimo must have mass, also for static objects.
  67890. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  67891. size: [],
  67892. type: [],
  67893. pos: [],
  67894. rot: [],
  67895. move: impostor.getParam("mass") !== 0,
  67896. //Supporting older versions of Oimo
  67897. world: this.world
  67898. };
  67899. var impostors = [impostor];
  67900. var addToArray = function (parent) {
  67901. if (!parent.getChildMeshes)
  67902. return;
  67903. parent.getChildMeshes().forEach(function (m) {
  67904. if (m.physicsImpostor) {
  67905. impostors.push(m.physicsImpostor);
  67906. //m.physicsImpostor._init();
  67907. }
  67908. });
  67909. };
  67910. addToArray(impostor.object);
  67911. var checkWithEpsilon_1 = function (value) {
  67912. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  67913. };
  67914. impostors.forEach(function (i) {
  67915. if (!impostor.object.rotationQuaternion) {
  67916. return;
  67917. }
  67918. //get the correct bounding box
  67919. var oldQuaternion = i.object.rotationQuaternion;
  67920. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  67921. x: impostor.object.rotationQuaternion.x,
  67922. y: impostor.object.rotationQuaternion.y,
  67923. z: impostor.object.rotationQuaternion.z,
  67924. s: impostor.object.rotationQuaternion.w
  67925. });
  67926. var extendSize = i.getObjectExtendSize();
  67927. if (i === impostor) {
  67928. var center = impostor.getObjectCenter();
  67929. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  67930. //Can also use Array.prototype.push.apply
  67931. bodyConfig.pos.push(center.x);
  67932. bodyConfig.pos.push(center.y);
  67933. bodyConfig.pos.push(center.z);
  67934. //tmp solution
  67935. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67936. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67937. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67938. }
  67939. else {
  67940. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  67941. bodyConfig.pos.push(localPosition.x);
  67942. bodyConfig.pos.push(localPosition.y);
  67943. bodyConfig.pos.push(localPosition.z);
  67944. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  67945. bodyConfig.rot.push(0);
  67946. bodyConfig.rot.push(0);
  67947. bodyConfig.rot.push(0);
  67948. }
  67949. // register mesh
  67950. switch (i.type) {
  67951. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67952. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  67953. case BABYLON.PhysicsImpostor.SphereImpostor:
  67954. var radiusX = extendSize.x;
  67955. var radiusY = extendSize.y;
  67956. var radiusZ = extendSize.z;
  67957. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  67958. bodyConfig.type.push('sphere');
  67959. //due to the way oimo works with compounds, add 3 times
  67960. bodyConfig.size.push(size);
  67961. bodyConfig.size.push(size);
  67962. bodyConfig.size.push(size);
  67963. break;
  67964. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67965. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  67966. var sizeY = checkWithEpsilon_1(extendSize.y);
  67967. bodyConfig.type.push('cylinder');
  67968. bodyConfig.size.push(sizeX);
  67969. bodyConfig.size.push(sizeY);
  67970. //due to the way oimo works with compounds, add one more value.
  67971. bodyConfig.size.push(sizeY);
  67972. break;
  67973. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67974. case BABYLON.PhysicsImpostor.BoxImpostor:
  67975. default:
  67976. var sizeX = checkWithEpsilon_1(extendSize.x);
  67977. var sizeY = checkWithEpsilon_1(extendSize.y);
  67978. var sizeZ = checkWithEpsilon_1(extendSize.z);
  67979. bodyConfig.type.push('box');
  67980. bodyConfig.size.push(sizeX);
  67981. bodyConfig.size.push(sizeY);
  67982. bodyConfig.size.push(sizeZ);
  67983. break;
  67984. }
  67985. //actually not needed, but hey...
  67986. i.object.rotationQuaternion = oldQuaternion;
  67987. });
  67988. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  67989. }
  67990. else {
  67991. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  67992. }
  67993. impostor.setDeltaPosition(this._tmpPositionVector);
  67994. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  67995. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  67996. };
  67997. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67998. //impostor.physicsBody.dispose();
  67999. //Same as : (older oimo versions)
  68000. this.world.removeRigidBody(impostor.physicsBody);
  68001. };
  68002. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68003. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68004. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68005. if (!mainBody || !connectedBody) {
  68006. return;
  68007. }
  68008. var jointData = impostorJoint.joint.jointData;
  68009. var options = jointData.nativeParams || {};
  68010. var type;
  68011. var nativeJointData = {
  68012. body1: mainBody,
  68013. body2: connectedBody,
  68014. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  68015. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  68016. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  68017. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  68018. min: options.min,
  68019. max: options.max,
  68020. collision: options.collision || jointData.collision,
  68021. spring: options.spring,
  68022. //supporting older version of Oimo
  68023. world: this.world
  68024. };
  68025. switch (impostorJoint.joint.type) {
  68026. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68027. type = "jointBall";
  68028. break;
  68029. case BABYLON.PhysicsJoint.SpringJoint:
  68030. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  68031. var springData = jointData;
  68032. nativeJointData.min = springData.length || nativeJointData.min;
  68033. //Max should also be set, just make sure it is at least min
  68034. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  68035. case BABYLON.PhysicsJoint.DistanceJoint:
  68036. type = "jointDistance";
  68037. nativeJointData.max = jointData.maxDistance;
  68038. break;
  68039. case BABYLON.PhysicsJoint.PrismaticJoint:
  68040. type = "jointPrisme";
  68041. break;
  68042. case BABYLON.PhysicsJoint.SliderJoint:
  68043. type = "jointSlide";
  68044. break;
  68045. case BABYLON.PhysicsJoint.WheelJoint:
  68046. type = "jointWheel";
  68047. break;
  68048. case BABYLON.PhysicsJoint.HingeJoint:
  68049. default:
  68050. type = "jointHinge";
  68051. break;
  68052. }
  68053. nativeJointData.type = type;
  68054. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  68055. };
  68056. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68057. //Bug in Oimo prevents us from disposing a joint in the playground
  68058. //joint.joint.physicsJoint.dispose();
  68059. //So we will bruteforce it!
  68060. try {
  68061. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  68062. }
  68063. catch (e) {
  68064. BABYLON.Tools.Warn(e);
  68065. }
  68066. };
  68067. OimoJSPlugin.prototype.isSupported = function () {
  68068. return this.BJSOIMO !== undefined;
  68069. };
  68070. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68071. if (!impostor.physicsBody.sleeping) {
  68072. //TODO check that
  68073. if (impostor.physicsBody.shapes.next) {
  68074. var parentShape = this._getLastShape(impostor.physicsBody);
  68075. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  68076. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  68077. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  68078. }
  68079. else {
  68080. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  68081. }
  68082. if (impostor.object.rotationQuaternion) {
  68083. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  68084. impostor.object.rotationQuaternion.normalize();
  68085. }
  68086. }
  68087. };
  68088. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68089. var body = impostor.physicsBody;
  68090. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  68091. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  68092. body.syncShapes();
  68093. body.awake();
  68094. };
  68095. OimoJSPlugin.prototype._getLastShape = function (body) {
  68096. var lastShape = body.shapes;
  68097. while (lastShape.next) {
  68098. lastShape = lastShape.next;
  68099. }
  68100. return lastShape;
  68101. };
  68102. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68103. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68104. };
  68105. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68106. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68107. };
  68108. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68109. var v = impostor.physicsBody.linearVelocity;
  68110. if (!v) {
  68111. return null;
  68112. }
  68113. return new BABYLON.Vector3(v.x, v.y, v.z);
  68114. };
  68115. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68116. var v = impostor.physicsBody.angularVelocity;
  68117. if (!v) {
  68118. return null;
  68119. }
  68120. return new BABYLON.Vector3(v.x, v.y, v.z);
  68121. };
  68122. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68123. var staticBody = mass === 0;
  68124. //this will actually set the body's density and not its mass.
  68125. //But this is how oimo treats the mass variable.
  68126. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68127. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68128. };
  68129. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68130. return impostor.physicsBody.shapes.density;
  68131. };
  68132. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68133. return impostor.physicsBody.shapes.friction;
  68134. };
  68135. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68136. impostor.physicsBody.shapes.friction = friction;
  68137. };
  68138. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68139. return impostor.physicsBody.shapes.restitution;
  68140. };
  68141. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68142. impostor.physicsBody.shapes.restitution = restitution;
  68143. };
  68144. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68145. impostor.physicsBody.sleep();
  68146. };
  68147. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68148. impostor.physicsBody.awake();
  68149. };
  68150. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68151. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68152. if (minDistance !== void 0) {
  68153. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68154. }
  68155. };
  68156. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68157. //TODO separate rotational and transational motors.
  68158. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68159. if (motor) {
  68160. motor.setMotor(speed, maxForce);
  68161. }
  68162. };
  68163. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68164. //TODO separate rotational and transational motors.
  68165. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68166. if (motor) {
  68167. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68168. }
  68169. };
  68170. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68171. var body = impostor.physicsBody;
  68172. mesh.position.x = body.position.x;
  68173. mesh.position.y = body.position.y;
  68174. mesh.position.z = body.position.z;
  68175. if (mesh.rotationQuaternion) {
  68176. mesh.rotationQuaternion.x = body.orientation.x;
  68177. mesh.rotationQuaternion.y = body.orientation.y;
  68178. mesh.rotationQuaternion.z = body.orientation.z;
  68179. mesh.rotationQuaternion.w = body.orientation.s;
  68180. }
  68181. };
  68182. OimoJSPlugin.prototype.getRadius = function (impostor) {
  68183. return impostor.physicsBody.shapes.radius;
  68184. };
  68185. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68186. var shape = impostor.physicsBody.shapes;
  68187. result.x = shape.halfWidth * 2;
  68188. result.y = shape.halfHeight * 2;
  68189. result.z = shape.halfDepth * 2;
  68190. };
  68191. OimoJSPlugin.prototype.dispose = function () {
  68192. this.world.clear();
  68193. };
  68194. return OimoJSPlugin;
  68195. }());
  68196. BABYLON.OimoJSPlugin = OimoJSPlugin;
  68197. })(BABYLON || (BABYLON = {}));
  68198. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  68199. var BABYLON;
  68200. (function (BABYLON) {
  68201. var Internals;
  68202. (function (Internals) {
  68203. /*
  68204. * Based on jsTGALoader - Javascript loader for TGA file
  68205. * By Vincent Thibault
  68206. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  68207. */
  68208. var TGATools = /** @class */ (function () {
  68209. function TGATools() {
  68210. }
  68211. TGATools.GetTGAHeader = function (data) {
  68212. var offset = 0;
  68213. var header = {
  68214. id_length: data[offset++],
  68215. colormap_type: data[offset++],
  68216. image_type: data[offset++],
  68217. colormap_index: data[offset++] | data[offset++] << 8,
  68218. colormap_length: data[offset++] | data[offset++] << 8,
  68219. colormap_size: data[offset++],
  68220. origin: [
  68221. data[offset++] | data[offset++] << 8,
  68222. data[offset++] | data[offset++] << 8
  68223. ],
  68224. width: data[offset++] | data[offset++] << 8,
  68225. height: data[offset++] | data[offset++] << 8,
  68226. pixel_size: data[offset++],
  68227. flags: data[offset++]
  68228. };
  68229. return header;
  68230. };
  68231. TGATools.UploadContent = function (gl, data) {
  68232. // Not enough data to contain header ?
  68233. if (data.length < 19) {
  68234. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  68235. return;
  68236. }
  68237. // Read Header
  68238. var offset = 18;
  68239. var header = TGATools.GetTGAHeader(data);
  68240. // Assume it's a valid Targa file.
  68241. if (header.id_length + offset > data.length) {
  68242. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  68243. return;
  68244. }
  68245. // Skip not needed data
  68246. offset += header.id_length;
  68247. var use_rle = false;
  68248. var use_pal = false;
  68249. var use_grey = false;
  68250. // Get some informations.
  68251. switch (header.image_type) {
  68252. case TGATools._TYPE_RLE_INDEXED:
  68253. use_rle = true;
  68254. case TGATools._TYPE_INDEXED:
  68255. use_pal = true;
  68256. break;
  68257. case TGATools._TYPE_RLE_RGB:
  68258. use_rle = true;
  68259. case TGATools._TYPE_RGB:
  68260. // use_rgb = true;
  68261. break;
  68262. case TGATools._TYPE_RLE_GREY:
  68263. use_rle = true;
  68264. case TGATools._TYPE_GREY:
  68265. use_grey = true;
  68266. break;
  68267. }
  68268. var pixel_data;
  68269. // var numAlphaBits = header.flags & 0xf;
  68270. var pixel_size = header.pixel_size >> 3;
  68271. var pixel_total = header.width * header.height * pixel_size;
  68272. // Read palettes
  68273. var palettes;
  68274. if (use_pal) {
  68275. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  68276. }
  68277. // Read LRE
  68278. if (use_rle) {
  68279. pixel_data = new Uint8Array(pixel_total);
  68280. var c, count, i;
  68281. var localOffset = 0;
  68282. var pixels = new Uint8Array(pixel_size);
  68283. while (offset < pixel_total && localOffset < pixel_total) {
  68284. c = data[offset++];
  68285. count = (c & 0x7f) + 1;
  68286. // RLE pixels
  68287. if (c & 0x80) {
  68288. // Bind pixel tmp array
  68289. for (i = 0; i < pixel_size; ++i) {
  68290. pixels[i] = data[offset++];
  68291. }
  68292. // Copy pixel array
  68293. for (i = 0; i < count; ++i) {
  68294. pixel_data.set(pixels, localOffset + i * pixel_size);
  68295. }
  68296. localOffset += pixel_size * count;
  68297. }
  68298. else {
  68299. count *= pixel_size;
  68300. for (i = 0; i < count; ++i) {
  68301. pixel_data[localOffset + i] = data[offset++];
  68302. }
  68303. localOffset += count;
  68304. }
  68305. }
  68306. }
  68307. else {
  68308. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  68309. }
  68310. // Load to texture
  68311. var x_start, y_start, x_step, y_step, y_end, x_end;
  68312. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  68313. default:
  68314. case TGATools._ORIGIN_UL:
  68315. x_start = 0;
  68316. x_step = 1;
  68317. x_end = header.width;
  68318. y_start = 0;
  68319. y_step = 1;
  68320. y_end = header.height;
  68321. break;
  68322. case TGATools._ORIGIN_BL:
  68323. x_start = 0;
  68324. x_step = 1;
  68325. x_end = header.width;
  68326. y_start = header.height - 1;
  68327. y_step = -1;
  68328. y_end = -1;
  68329. break;
  68330. case TGATools._ORIGIN_UR:
  68331. x_start = header.width - 1;
  68332. x_step = -1;
  68333. x_end = -1;
  68334. y_start = 0;
  68335. y_step = 1;
  68336. y_end = header.height;
  68337. break;
  68338. case TGATools._ORIGIN_BR:
  68339. x_start = header.width - 1;
  68340. x_step = -1;
  68341. x_end = -1;
  68342. y_start = header.height - 1;
  68343. y_step = -1;
  68344. y_end = -1;
  68345. break;
  68346. }
  68347. // Load the specify method
  68348. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  68349. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  68350. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68351. };
  68352. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68353. var image = pixel_data, colormap = palettes;
  68354. var width = header.width, height = header.height;
  68355. var color, i = 0, x, y;
  68356. var imageData = new Uint8Array(width * height * 4);
  68357. for (y = y_start; y !== y_end; y += y_step) {
  68358. for (x = x_start; x !== x_end; x += x_step, i++) {
  68359. color = image[i];
  68360. imageData[(x + width * y) * 4 + 3] = 255;
  68361. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  68362. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  68363. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  68364. }
  68365. }
  68366. return imageData;
  68367. };
  68368. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68369. var image = pixel_data;
  68370. var width = header.width, height = header.height;
  68371. var color, i = 0, x, y;
  68372. var imageData = new Uint8Array(width * height * 4);
  68373. for (y = y_start; y !== y_end; y += y_step) {
  68374. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68375. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  68376. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  68377. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  68378. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  68379. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  68380. }
  68381. }
  68382. return imageData;
  68383. };
  68384. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68385. var image = pixel_data;
  68386. var width = header.width, height = header.height;
  68387. var i = 0, x, y;
  68388. var imageData = new Uint8Array(width * height * 4);
  68389. for (y = y_start; y !== y_end; y += y_step) {
  68390. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  68391. imageData[(x + width * y) * 4 + 3] = 255;
  68392. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68393. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68394. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68395. }
  68396. }
  68397. return imageData;
  68398. };
  68399. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68400. var image = pixel_data;
  68401. var width = header.width, height = header.height;
  68402. var i = 0, x, y;
  68403. var imageData = new Uint8Array(width * height * 4);
  68404. for (y = y_start; y !== y_end; y += y_step) {
  68405. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  68406. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68407. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68408. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68409. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  68410. }
  68411. }
  68412. return imageData;
  68413. };
  68414. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68415. var image = pixel_data;
  68416. var width = header.width, height = header.height;
  68417. var color, i = 0, x, y;
  68418. var imageData = new Uint8Array(width * height * 4);
  68419. for (y = y_start; y !== y_end; y += y_step) {
  68420. for (x = x_start; x !== x_end; x += x_step, i++) {
  68421. color = image[i];
  68422. imageData[(x + width * y) * 4 + 0] = color;
  68423. imageData[(x + width * y) * 4 + 1] = color;
  68424. imageData[(x + width * y) * 4 + 2] = color;
  68425. imageData[(x + width * y) * 4 + 3] = 255;
  68426. }
  68427. }
  68428. return imageData;
  68429. };
  68430. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68431. var image = pixel_data;
  68432. var width = header.width, height = header.height;
  68433. var i = 0, x, y;
  68434. var imageData = new Uint8Array(width * height * 4);
  68435. for (y = y_start; y !== y_end; y += y_step) {
  68436. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68437. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  68438. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  68439. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68440. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  68441. }
  68442. }
  68443. return imageData;
  68444. };
  68445. //private static _TYPE_NO_DATA = 0;
  68446. TGATools._TYPE_INDEXED = 1;
  68447. TGATools._TYPE_RGB = 2;
  68448. TGATools._TYPE_GREY = 3;
  68449. TGATools._TYPE_RLE_INDEXED = 9;
  68450. TGATools._TYPE_RLE_RGB = 10;
  68451. TGATools._TYPE_RLE_GREY = 11;
  68452. TGATools._ORIGIN_MASK = 0x30;
  68453. TGATools._ORIGIN_SHIFT = 0x04;
  68454. TGATools._ORIGIN_BL = 0x00;
  68455. TGATools._ORIGIN_BR = 0x01;
  68456. TGATools._ORIGIN_UL = 0x02;
  68457. TGATools._ORIGIN_UR = 0x03;
  68458. return TGATools;
  68459. }());
  68460. Internals.TGATools = TGATools;
  68461. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68462. })(BABYLON || (BABYLON = {}));
  68463. //# sourceMappingURL=babylon.tga.js.map
  68464. var BABYLON;
  68465. (function (BABYLON) {
  68466. var Internals;
  68467. (function (Internals) {
  68468. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  68469. // All values and structures referenced from:
  68470. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  68471. var DDS_MAGIC = 0x20534444;
  68472. var
  68473. //DDSD_CAPS = 0x1,
  68474. //DDSD_HEIGHT = 0x2,
  68475. //DDSD_WIDTH = 0x4,
  68476. //DDSD_PITCH = 0x8,
  68477. //DDSD_PIXELFORMAT = 0x1000,
  68478. DDSD_MIPMAPCOUNT = 0x20000;
  68479. //DDSD_LINEARSIZE = 0x80000,
  68480. //DDSD_DEPTH = 0x800000;
  68481. // var DDSCAPS_COMPLEX = 0x8,
  68482. // DDSCAPS_MIPMAP = 0x400000,
  68483. // DDSCAPS_TEXTURE = 0x1000;
  68484. var DDSCAPS2_CUBEMAP = 0x200;
  68485. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  68486. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  68487. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  68488. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  68489. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  68490. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  68491. // DDSCAPS2_VOLUME = 0x200000;
  68492. var
  68493. //DDPF_ALPHAPIXELS = 0x1,
  68494. //DDPF_ALPHA = 0x2,
  68495. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  68496. //DDPF_YUV = 0x200,
  68497. DDPF_LUMINANCE = 0x20000;
  68498. function FourCCToInt32(value) {
  68499. return value.charCodeAt(0) +
  68500. (value.charCodeAt(1) << 8) +
  68501. (value.charCodeAt(2) << 16) +
  68502. (value.charCodeAt(3) << 24);
  68503. }
  68504. function Int32ToFourCC(value) {
  68505. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  68506. }
  68507. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  68508. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  68509. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  68510. var FOURCC_DX10 = FourCCToInt32("DX10");
  68511. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  68512. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  68513. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  68514. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  68515. var headerLengthInt = 31; // The header length in 32 bit ints
  68516. // Offsets into the header array
  68517. var off_magic = 0;
  68518. var off_size = 1;
  68519. var off_flags = 2;
  68520. var off_height = 3;
  68521. var off_width = 4;
  68522. var off_mipmapCount = 7;
  68523. var off_pfFlags = 20;
  68524. var off_pfFourCC = 21;
  68525. var off_RGBbpp = 22;
  68526. // var off_RMask = 23;
  68527. // var off_GMask = 24;
  68528. // var off_BMask = 25;
  68529. // var off_AMask = 26;
  68530. // var off_caps1 = 27;
  68531. var off_caps2 = 28;
  68532. // var off_caps3 = 29;
  68533. // var off_caps4 = 30;
  68534. var off_dxgiFormat = 32;
  68535. ;
  68536. var DDSTools = /** @class */ (function () {
  68537. function DDSTools() {
  68538. }
  68539. DDSTools.GetDDSInfo = function (arrayBuffer) {
  68540. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68541. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  68542. var mipmapCount = 1;
  68543. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  68544. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68545. }
  68546. var fourCC = header[off_pfFourCC];
  68547. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  68548. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68549. switch (fourCC) {
  68550. case FOURCC_D3DFMT_R16G16B16A16F:
  68551. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68552. break;
  68553. case FOURCC_D3DFMT_R32G32B32A32F:
  68554. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68555. break;
  68556. case FOURCC_DX10:
  68557. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  68558. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68559. break;
  68560. }
  68561. }
  68562. return {
  68563. width: header[off_width],
  68564. height: header[off_height],
  68565. mipmapCount: mipmapCount,
  68566. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  68567. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  68568. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  68569. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  68570. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  68571. dxgiFormat: dxgiFormat,
  68572. textureType: textureType
  68573. };
  68574. };
  68575. DDSTools._ToHalfFloat = function (value) {
  68576. if (!DDSTools._FloatView) {
  68577. DDSTools._FloatView = new Float32Array(1);
  68578. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  68579. }
  68580. DDSTools._FloatView[0] = value;
  68581. var x = DDSTools._Int32View[0];
  68582. var bits = (x >> 16) & 0x8000; /* Get the sign */
  68583. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  68584. var e = (x >> 23) & 0xff; /* Using int is faster here */
  68585. /* If zero, or denormal, or exponent underflows too much for a denormal
  68586. * half, return signed zero. */
  68587. if (e < 103) {
  68588. return bits;
  68589. }
  68590. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  68591. if (e > 142) {
  68592. bits |= 0x7c00;
  68593. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  68594. * not Inf, so make sure we set one mantissa bit too. */
  68595. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  68596. return bits;
  68597. }
  68598. /* If exponent underflows but not too much, return a denormal */
  68599. if (e < 113) {
  68600. m |= 0x0800;
  68601. /* Extra rounding may overflow and set mantissa to 0 and exponent
  68602. * to 1, which is OK. */
  68603. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  68604. return bits;
  68605. }
  68606. bits |= ((e - 112) << 10) | (m >> 1);
  68607. bits += m & 1;
  68608. return bits;
  68609. };
  68610. DDSTools._FromHalfFloat = function (value) {
  68611. var s = (value & 0x8000) >> 15;
  68612. var e = (value & 0x7C00) >> 10;
  68613. var f = value & 0x03FF;
  68614. if (e === 0) {
  68615. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  68616. }
  68617. else if (e == 0x1F) {
  68618. return f ? NaN : ((s ? -1 : 1) * Infinity);
  68619. }
  68620. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  68621. };
  68622. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68623. var destArray = new Float32Array(dataLength);
  68624. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68625. var index = 0;
  68626. for (var y = 0; y < height; y++) {
  68627. for (var x = 0; x < width; x++) {
  68628. var srcPos = (x + y * width) * 4;
  68629. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  68630. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  68631. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  68632. if (DDSTools.StoreLODInAlphaChannel) {
  68633. destArray[index + 3] = lod;
  68634. }
  68635. else {
  68636. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  68637. }
  68638. index += 4;
  68639. }
  68640. }
  68641. return destArray;
  68642. };
  68643. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68644. if (DDSTools.StoreLODInAlphaChannel) {
  68645. var destArray = new Uint16Array(dataLength);
  68646. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68647. var index = 0;
  68648. for (var y = 0; y < height; y++) {
  68649. for (var x = 0; x < width; x++) {
  68650. var srcPos = (x + y * width) * 4;
  68651. destArray[index] = srcData[srcPos];
  68652. destArray[index + 1] = srcData[srcPos + 1];
  68653. destArray[index + 2] = srcData[srcPos + 2];
  68654. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  68655. index += 4;
  68656. }
  68657. }
  68658. return destArray;
  68659. }
  68660. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  68661. };
  68662. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68663. if (DDSTools.StoreLODInAlphaChannel) {
  68664. var destArray = new Float32Array(dataLength);
  68665. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68666. var index = 0;
  68667. for (var y = 0; y < height; y++) {
  68668. for (var x = 0; x < width; x++) {
  68669. var srcPos = (x + y * width) * 4;
  68670. destArray[index] = srcData[srcPos];
  68671. destArray[index + 1] = srcData[srcPos + 1];
  68672. destArray[index + 2] = srcData[srcPos + 2];
  68673. destArray[index + 3] = lod;
  68674. index += 4;
  68675. }
  68676. }
  68677. return destArray;
  68678. }
  68679. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  68680. };
  68681. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68682. var destArray = new Uint8Array(dataLength);
  68683. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68684. var index = 0;
  68685. for (var y = 0; y < height; y++) {
  68686. for (var x = 0; x < width; x++) {
  68687. var srcPos = (x + y * width) * 4;
  68688. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  68689. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  68690. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  68691. if (DDSTools.StoreLODInAlphaChannel) {
  68692. destArray[index + 3] = lod;
  68693. }
  68694. else {
  68695. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  68696. }
  68697. index += 4;
  68698. }
  68699. }
  68700. return destArray;
  68701. };
  68702. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68703. var destArray = new Uint8Array(dataLength);
  68704. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68705. var index = 0;
  68706. for (var y = 0; y < height; y++) {
  68707. for (var x = 0; x < width; x++) {
  68708. var srcPos = (x + y * width) * 4;
  68709. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  68710. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  68711. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  68712. if (DDSTools.StoreLODInAlphaChannel) {
  68713. destArray[index + 3] = lod;
  68714. }
  68715. else {
  68716. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  68717. }
  68718. index += 4;
  68719. }
  68720. }
  68721. return destArray;
  68722. };
  68723. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68724. var byteArray = new Uint8Array(dataLength);
  68725. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68726. var index = 0;
  68727. for (var y = 0; y < height; y++) {
  68728. for (var x = 0; x < width; x++) {
  68729. var srcPos = (x + y * width) * 4;
  68730. byteArray[index] = srcData[srcPos + 2];
  68731. byteArray[index + 1] = srcData[srcPos + 1];
  68732. byteArray[index + 2] = srcData[srcPos];
  68733. byteArray[index + 3] = srcData[srcPos + 3];
  68734. index += 4;
  68735. }
  68736. }
  68737. return byteArray;
  68738. };
  68739. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68740. var byteArray = new Uint8Array(dataLength);
  68741. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68742. var index = 0;
  68743. for (var y = 0; y < height; y++) {
  68744. for (var x = 0; x < width; x++) {
  68745. var srcPos = (x + y * width) * 3;
  68746. byteArray[index] = srcData[srcPos + 2];
  68747. byteArray[index + 1] = srcData[srcPos + 1];
  68748. byteArray[index + 2] = srcData[srcPos];
  68749. index += 3;
  68750. }
  68751. }
  68752. return byteArray;
  68753. };
  68754. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68755. var byteArray = new Uint8Array(dataLength);
  68756. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68757. var index = 0;
  68758. for (var y = 0; y < height; y++) {
  68759. for (var x = 0; x < width; x++) {
  68760. var srcPos = (x + y * width);
  68761. byteArray[index] = srcData[srcPos];
  68762. index++;
  68763. }
  68764. }
  68765. return byteArray;
  68766. };
  68767. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  68768. if (lodIndex === void 0) { lodIndex = -1; }
  68769. var ext = engine.getCaps().s3tc;
  68770. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68771. var fourCC, width, height, dataLength = 0, dataOffset;
  68772. var byteArray, mipmapCount, mip;
  68773. var internalFormat = 0;
  68774. var format = 0;
  68775. var blockBytes = 1;
  68776. if (header[off_magic] !== DDS_MAGIC) {
  68777. BABYLON.Tools.Error("Invalid magic number in DDS header");
  68778. return;
  68779. }
  68780. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  68781. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  68782. return;
  68783. }
  68784. if (info.isCompressed && !ext) {
  68785. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  68786. return;
  68787. }
  68788. var bpp = header[off_RGBbpp];
  68789. dataOffset = header[off_size] + 4;
  68790. var computeFormats = false;
  68791. if (info.isFourCC) {
  68792. fourCC = header[off_pfFourCC];
  68793. switch (fourCC) {
  68794. case FOURCC_DXT1:
  68795. blockBytes = 8;
  68796. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  68797. break;
  68798. case FOURCC_DXT3:
  68799. blockBytes = 16;
  68800. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  68801. break;
  68802. case FOURCC_DXT5:
  68803. blockBytes = 16;
  68804. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  68805. break;
  68806. case FOURCC_D3DFMT_R16G16B16A16F:
  68807. computeFormats = true;
  68808. break;
  68809. case FOURCC_D3DFMT_R32G32B32A32F:
  68810. computeFormats = true;
  68811. break;
  68812. case FOURCC_DX10:
  68813. // There is an additionnal header so dataOffset need to be changed
  68814. dataOffset += 5 * 4; // 5 uints
  68815. var supported = false;
  68816. switch (info.dxgiFormat) {
  68817. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  68818. computeFormats = true;
  68819. supported = true;
  68820. break;
  68821. case DXGI_FORMAT_B8G8R8X8_UNORM:
  68822. info.isRGB = true;
  68823. info.isFourCC = false;
  68824. bpp = 32;
  68825. supported = true;
  68826. break;
  68827. }
  68828. if (supported) {
  68829. break;
  68830. }
  68831. default:
  68832. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  68833. return;
  68834. }
  68835. }
  68836. if (computeFormats) {
  68837. format = engine._getWebGLTextureType(info.textureType);
  68838. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68839. }
  68840. mipmapCount = 1;
  68841. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  68842. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68843. }
  68844. for (var face = 0; face < faces; face++) {
  68845. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  68846. width = header[off_width];
  68847. height = header[off_height];
  68848. for (mip = 0; mip < mipmapCount; ++mip) {
  68849. if (lodIndex === -1 || lodIndex === mip) {
  68850. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  68851. var i = (lodIndex === -1) ? mip : 0;
  68852. if (!info.isCompressed && info.isFourCC) {
  68853. dataLength = width * height * 4;
  68854. var floatArray = null;
  68855. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  68856. if (bpp === 128) {
  68857. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68858. }
  68859. else if (bpp === 64) {
  68860. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68861. }
  68862. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68863. format = engine._getWebGLTextureType(info.textureType);
  68864. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68865. }
  68866. else {
  68867. if (bpp === 128) {
  68868. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68869. }
  68870. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  68871. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68872. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68873. format = engine._getWebGLTextureType(info.textureType);
  68874. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68875. }
  68876. else {
  68877. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68878. }
  68879. }
  68880. if (floatArray) {
  68881. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  68882. }
  68883. }
  68884. else if (info.isRGB) {
  68885. if (bpp === 24) {
  68886. dataLength = width * height * 3;
  68887. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68888. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  68889. }
  68890. else {
  68891. dataLength = width * height * 4;
  68892. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68893. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  68894. }
  68895. }
  68896. else if (info.isLuminance) {
  68897. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  68898. var unpaddedRowSize = width;
  68899. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  68900. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  68901. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68902. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  68903. }
  68904. else {
  68905. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  68906. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  68907. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  68908. }
  68909. }
  68910. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  68911. width *= 0.5;
  68912. height *= 0.5;
  68913. width = Math.max(1.0, width);
  68914. height = Math.max(1.0, height);
  68915. }
  68916. if (currentFace !== undefined) {
  68917. // Loading a single face
  68918. break;
  68919. }
  68920. }
  68921. };
  68922. DDSTools.StoreLODInAlphaChannel = false;
  68923. return DDSTools;
  68924. }());
  68925. Internals.DDSTools = DDSTools;
  68926. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68927. })(BABYLON || (BABYLON = {}));
  68928. //# sourceMappingURL=babylon.dds.js.map
  68929. var BABYLON;
  68930. (function (BABYLON) {
  68931. var Internals;
  68932. (function (Internals) {
  68933. /**
  68934. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  68935. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  68936. */
  68937. var KhronosTextureContainer = /** @class */ (function () {
  68938. /**
  68939. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  68940. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  68941. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  68942. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  68943. */
  68944. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  68945. this.arrayBuffer = arrayBuffer;
  68946. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  68947. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  68948. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  68949. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  68950. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  68951. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  68952. BABYLON.Tools.Error("texture missing KTX identifier");
  68953. return;
  68954. }
  68955. // load the reset of the header in native 32 bit int
  68956. var header = new Int32Array(this.arrayBuffer, 12, 13);
  68957. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  68958. var oppositeEndianess = header[0] === 0x01020304;
  68959. // read all the header elements in order they exist in the file, without modification (sans endainness)
  68960. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  68961. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  68962. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  68963. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  68964. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  68965. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  68966. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  68967. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  68968. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  68969. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  68970. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  68971. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  68972. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  68973. if (this.glType !== 0) {
  68974. BABYLON.Tools.Error("only compressed formats currently supported");
  68975. return;
  68976. }
  68977. else {
  68978. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  68979. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  68980. }
  68981. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  68982. BABYLON.Tools.Error("only 2D textures currently supported");
  68983. return;
  68984. }
  68985. if (this.numberOfArrayElements !== 0) {
  68986. BABYLON.Tools.Error("texture arrays not currently supported");
  68987. return;
  68988. }
  68989. if (this.numberOfFaces !== facesExpected) {
  68990. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  68991. return;
  68992. }
  68993. // we now have a completely validated file, so could use existence of loadType as success
  68994. // would need to make this more elaborate & adjust checks above to support more than one load type
  68995. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  68996. }
  68997. // not as fast hardware based, but will probably never need to use
  68998. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  68999. return ((val & 0xFF) << 24)
  69000. | ((val & 0xFF00) << 8)
  69001. | ((val >> 8) & 0xFF00)
  69002. | ((val >> 24) & 0xFF);
  69003. };
  69004. /**
  69005. * It is assumed that the texture has already been created & is currently bound
  69006. */
  69007. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  69008. switch (this.loadType) {
  69009. case KhronosTextureContainer.COMPRESSED_2D:
  69010. this._upload2DCompressedLevels(gl, loadMipmaps);
  69011. break;
  69012. case KhronosTextureContainer.TEX_2D:
  69013. case KhronosTextureContainer.COMPRESSED_3D:
  69014. case KhronosTextureContainer.TEX_3D:
  69015. }
  69016. };
  69017. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  69018. // initialize width & height for level 1
  69019. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  69020. var width = this.pixelWidth;
  69021. var height = this.pixelHeight;
  69022. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  69023. for (var level = 0; level < mipmapCount; level++) {
  69024. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  69025. for (var face = 0; face < this.numberOfFaces; face++) {
  69026. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  69027. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  69028. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  69029. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  69030. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  69031. }
  69032. width = Math.max(1.0, width * 0.5);
  69033. height = Math.max(1.0, height * 0.5);
  69034. }
  69035. };
  69036. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  69037. // load types
  69038. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  69039. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  69040. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  69041. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  69042. return KhronosTextureContainer;
  69043. }());
  69044. Internals.KhronosTextureContainer = KhronosTextureContainer;
  69045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69046. })(BABYLON || (BABYLON = {}));
  69047. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  69048. var BABYLON;
  69049. (function (BABYLON) {
  69050. var Debug;
  69051. (function (Debug) {
  69052. /**
  69053. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  69054. */
  69055. var SkeletonViewer = /** @class */ (function () {
  69056. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  69057. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  69058. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  69059. this.skeleton = skeleton;
  69060. this.mesh = mesh;
  69061. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  69062. this.renderingGroupId = renderingGroupId;
  69063. this.color = BABYLON.Color3.White();
  69064. this._debugLines = new Array();
  69065. this._isEnabled = false;
  69066. this._scene = scene;
  69067. this.update();
  69068. this._renderFunction = this.update.bind(this);
  69069. }
  69070. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  69071. get: function () {
  69072. return this._isEnabled;
  69073. },
  69074. set: function (value) {
  69075. if (this._isEnabled === value) {
  69076. return;
  69077. }
  69078. this._isEnabled = value;
  69079. if (value) {
  69080. this._scene.registerBeforeRender(this._renderFunction);
  69081. }
  69082. else {
  69083. this._scene.unregisterBeforeRender(this._renderFunction);
  69084. }
  69085. },
  69086. enumerable: true,
  69087. configurable: true
  69088. });
  69089. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  69090. if (x === void 0) { x = 0; }
  69091. if (y === void 0) { y = 0; }
  69092. if (z === void 0) { z = 0; }
  69093. var tmat = BABYLON.Tmp.Matrix[0];
  69094. var parentBone = bone.getParent();
  69095. tmat.copyFrom(bone.getLocalMatrix());
  69096. if (x !== 0 || y !== 0 || z !== 0) {
  69097. var tmat2 = BABYLON.Tmp.Matrix[1];
  69098. BABYLON.Matrix.IdentityToRef(tmat2);
  69099. tmat2.m[12] = x;
  69100. tmat2.m[13] = y;
  69101. tmat2.m[14] = z;
  69102. tmat2.multiplyToRef(tmat, tmat);
  69103. }
  69104. if (parentBone) {
  69105. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69106. }
  69107. tmat.multiplyToRef(meshMat, tmat);
  69108. position.x = tmat.m[12];
  69109. position.y = tmat.m[13];
  69110. position.z = tmat.m[14];
  69111. };
  69112. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69113. var len = bones.length;
  69114. var meshPos = this.mesh.position;
  69115. for (var i = 0; i < len; i++) {
  69116. var bone = bones[i];
  69117. var points = this._debugLines[i];
  69118. if (!points) {
  69119. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69120. this._debugLines[i] = points;
  69121. }
  69122. this._getBonePosition(points[0], bone, meshMat);
  69123. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69124. points[0].subtractInPlace(meshPos);
  69125. points[1].subtractInPlace(meshPos);
  69126. }
  69127. };
  69128. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69129. var len = bones.length;
  69130. var boneNum = 0;
  69131. var meshPos = this.mesh.position;
  69132. for (var i = len - 1; i >= 0; i--) {
  69133. var childBone = bones[i];
  69134. var parentBone = childBone.getParent();
  69135. if (!parentBone) {
  69136. continue;
  69137. }
  69138. var points = this._debugLines[boneNum];
  69139. if (!points) {
  69140. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69141. this._debugLines[boneNum] = points;
  69142. }
  69143. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69144. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69145. points[0].subtractInPlace(meshPos);
  69146. points[1].subtractInPlace(meshPos);
  69147. boneNum++;
  69148. }
  69149. };
  69150. SkeletonViewer.prototype.update = function () {
  69151. if (this.autoUpdateBonesMatrices) {
  69152. this.skeleton.computeAbsoluteTransforms();
  69153. }
  69154. if (this.skeleton.bones[0].length === undefined) {
  69155. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69156. }
  69157. else {
  69158. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69159. }
  69160. if (!this._debugMesh) {
  69161. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69162. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69163. }
  69164. else {
  69165. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69166. }
  69167. this._debugMesh.position.copyFrom(this.mesh.position);
  69168. this._debugMesh.color = this.color;
  69169. };
  69170. SkeletonViewer.prototype.dispose = function () {
  69171. if (this._debugMesh) {
  69172. this.isEnabled = false;
  69173. this._debugMesh.dispose();
  69174. this._debugMesh = null;
  69175. }
  69176. };
  69177. return SkeletonViewer;
  69178. }());
  69179. Debug.SkeletonViewer = SkeletonViewer;
  69180. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69181. })(BABYLON || (BABYLON = {}));
  69182. //# sourceMappingURL=babylon.skeletonViewer.js.map
  69183. var BABYLON;
  69184. (function (BABYLON) {
  69185. var Debug;
  69186. (function (Debug) {
  69187. var AxesViewer = /** @class */ (function () {
  69188. function AxesViewer(scene, scaleLines) {
  69189. if (scaleLines === void 0) { scaleLines = 1; }
  69190. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69191. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69192. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69193. this.scaleLines = 1;
  69194. this.scaleLines = scaleLines;
  69195. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  69196. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  69197. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  69198. this._xmesh.renderingGroupId = 2;
  69199. this._ymesh.renderingGroupId = 2;
  69200. this._zmesh.renderingGroupId = 2;
  69201. this._xmesh.material.checkReadyOnlyOnce = true;
  69202. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  69203. this._ymesh.material.checkReadyOnlyOnce = true;
  69204. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  69205. this._zmesh.material.checkReadyOnlyOnce = true;
  69206. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  69207. this.scene = scene;
  69208. }
  69209. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  69210. var scaleLines = this.scaleLines;
  69211. if (this._xmesh) {
  69212. this._xmesh.position.copyFrom(position);
  69213. }
  69214. if (this._ymesh) {
  69215. this._ymesh.position.copyFrom(position);
  69216. }
  69217. if (this._zmesh) {
  69218. this._zmesh.position.copyFrom(position);
  69219. }
  69220. var point2 = this._xline[1];
  69221. point2.x = xaxis.x * scaleLines;
  69222. point2.y = xaxis.y * scaleLines;
  69223. point2.z = xaxis.z * scaleLines;
  69224. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  69225. point2 = this._yline[1];
  69226. point2.x = yaxis.x * scaleLines;
  69227. point2.y = yaxis.y * scaleLines;
  69228. point2.z = yaxis.z * scaleLines;
  69229. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  69230. point2 = this._zline[1];
  69231. point2.x = zaxis.x * scaleLines;
  69232. point2.y = zaxis.y * scaleLines;
  69233. point2.z = zaxis.z * scaleLines;
  69234. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  69235. };
  69236. AxesViewer.prototype.dispose = function () {
  69237. if (this._xmesh) {
  69238. this._xmesh.dispose();
  69239. }
  69240. if (this._ymesh) {
  69241. this._ymesh.dispose();
  69242. }
  69243. if (this._zmesh) {
  69244. this._zmesh.dispose();
  69245. }
  69246. this._xmesh = null;
  69247. this._ymesh = null;
  69248. this._zmesh = null;
  69249. this.scene = null;
  69250. };
  69251. return AxesViewer;
  69252. }());
  69253. Debug.AxesViewer = AxesViewer;
  69254. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69255. })(BABYLON || (BABYLON = {}));
  69256. //# sourceMappingURL=babylon.axesViewer.js.map
  69257. var BABYLON;
  69258. (function (BABYLON) {
  69259. var Debug;
  69260. (function (Debug) {
  69261. var BoneAxesViewer = /** @class */ (function (_super) {
  69262. __extends(BoneAxesViewer, _super);
  69263. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  69264. if (scaleLines === void 0) { scaleLines = 1; }
  69265. var _this = _super.call(this, scene, scaleLines) || this;
  69266. _this.pos = BABYLON.Vector3.Zero();
  69267. _this.xaxis = BABYLON.Vector3.Zero();
  69268. _this.yaxis = BABYLON.Vector3.Zero();
  69269. _this.zaxis = BABYLON.Vector3.Zero();
  69270. _this.mesh = mesh;
  69271. _this.bone = bone;
  69272. return _this;
  69273. }
  69274. BoneAxesViewer.prototype.update = function () {
  69275. if (!this.mesh || !this.bone) {
  69276. return;
  69277. }
  69278. var bone = this.bone;
  69279. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  69280. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  69281. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  69282. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  69283. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  69284. };
  69285. BoneAxesViewer.prototype.dispose = function () {
  69286. if (this.mesh) {
  69287. this.mesh = null;
  69288. this.bone = null;
  69289. _super.prototype.dispose.call(this);
  69290. }
  69291. };
  69292. return BoneAxesViewer;
  69293. }(Debug.AxesViewer));
  69294. Debug.BoneAxesViewer = BoneAxesViewer;
  69295. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69296. })(BABYLON || (BABYLON = {}));
  69297. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  69298. var BABYLON;
  69299. (function (BABYLON) {
  69300. var RayHelper = /** @class */ (function () {
  69301. function RayHelper(ray) {
  69302. this.ray = ray;
  69303. }
  69304. RayHelper.CreateAndShow = function (ray, scene, color) {
  69305. var helper = new RayHelper(ray);
  69306. helper.show(scene, color);
  69307. return helper;
  69308. };
  69309. RayHelper.prototype.show = function (scene, color) {
  69310. if (!this._renderFunction && this.ray) {
  69311. var ray = this.ray;
  69312. this._renderFunction = this._render.bind(this);
  69313. this._scene = scene;
  69314. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  69315. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  69316. if (this._renderFunction) {
  69317. this._scene.registerBeforeRender(this._renderFunction);
  69318. }
  69319. }
  69320. if (color && this._renderLine) {
  69321. this._renderLine.color.copyFrom(color);
  69322. }
  69323. };
  69324. RayHelper.prototype.hide = function () {
  69325. if (this._renderFunction && this._scene) {
  69326. this._scene.unregisterBeforeRender(this._renderFunction);
  69327. this._scene = null;
  69328. this._renderFunction = null;
  69329. if (this._renderLine) {
  69330. this._renderLine.dispose();
  69331. this._renderLine = null;
  69332. }
  69333. this._renderPoints = [];
  69334. }
  69335. };
  69336. RayHelper.prototype._render = function () {
  69337. var ray = this.ray;
  69338. if (!ray) {
  69339. return;
  69340. }
  69341. var point = this._renderPoints[1];
  69342. var len = Math.min(ray.length, 1000000);
  69343. point.copyFrom(ray.direction);
  69344. point.scaleInPlace(len);
  69345. point.addInPlace(ray.origin);
  69346. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  69347. };
  69348. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  69349. this._attachedToMesh = mesh;
  69350. var ray = this.ray;
  69351. if (!ray) {
  69352. return;
  69353. }
  69354. if (!ray.direction) {
  69355. ray.direction = BABYLON.Vector3.Zero();
  69356. }
  69357. if (!ray.origin) {
  69358. ray.origin = BABYLON.Vector3.Zero();
  69359. }
  69360. if (length) {
  69361. ray.length = length;
  69362. }
  69363. if (!meshSpaceOrigin) {
  69364. meshSpaceOrigin = BABYLON.Vector3.Zero();
  69365. }
  69366. if (!meshSpaceDirection) {
  69367. // -1 so that this will work with Mesh.lookAt
  69368. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  69369. }
  69370. if (!this._meshSpaceDirection) {
  69371. this._meshSpaceDirection = meshSpaceDirection.clone();
  69372. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  69373. }
  69374. else {
  69375. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  69376. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  69377. }
  69378. if (!this._updateToMeshFunction) {
  69379. this._updateToMeshFunction = this._updateToMesh.bind(this);
  69380. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  69381. }
  69382. this._updateToMesh();
  69383. };
  69384. RayHelper.prototype.detachFromMesh = function () {
  69385. if (this._attachedToMesh) {
  69386. if (this._updateToMeshFunction) {
  69387. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  69388. }
  69389. this._attachedToMesh = null;
  69390. this._updateToMeshFunction = null;
  69391. }
  69392. };
  69393. RayHelper.prototype._updateToMesh = function () {
  69394. var ray = this.ray;
  69395. if (!this._attachedToMesh || !ray) {
  69396. return;
  69397. }
  69398. if (this._attachedToMesh._isDisposed) {
  69399. this.detachFromMesh();
  69400. return;
  69401. }
  69402. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  69403. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  69404. };
  69405. RayHelper.prototype.dispose = function () {
  69406. this.hide();
  69407. this.detachFromMesh();
  69408. this.ray = null;
  69409. };
  69410. return RayHelper;
  69411. }());
  69412. BABYLON.RayHelper = RayHelper;
  69413. })(BABYLON || (BABYLON = {}));
  69414. //# sourceMappingURL=babylon.rayHelper.js.map
  69415. var BABYLON;
  69416. (function (BABYLON) {
  69417. // load the inspector using require, if not present in the global namespace.
  69418. var DebugLayer = /** @class */ (function () {
  69419. function DebugLayer(scene) {
  69420. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69421. this._scene = scene;
  69422. // load inspector using require, if it doesn't exist on the global namespace.
  69423. }
  69424. /** Creates the inspector window. */
  69425. DebugLayer.prototype._createInspector = function (config) {
  69426. if (config === void 0) { config = {}; }
  69427. var popup = config.popup || false;
  69428. var initialTab = config.initialTab || 0;
  69429. var parentElement = config.parentElement || null;
  69430. if (!this._inspector) {
  69431. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69432. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  69433. } // else nothing to do,; instance is already existing
  69434. };
  69435. DebugLayer.prototype.isVisible = function () {
  69436. if (!this._inspector) {
  69437. return false;
  69438. }
  69439. return true;
  69440. };
  69441. DebugLayer.prototype.hide = function () {
  69442. if (this._inspector) {
  69443. try {
  69444. this._inspector.dispose();
  69445. }
  69446. catch (e) {
  69447. // If the inspector has been removed directly from the inspector tool
  69448. }
  69449. this._inspector = null;
  69450. }
  69451. };
  69452. DebugLayer.prototype.show = function (config) {
  69453. if (config === void 0) { config = {}; }
  69454. if (typeof this.BJSINSPECTOR == 'undefined') {
  69455. // Load inspector and add it to the DOM
  69456. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  69457. }
  69458. else {
  69459. // Otherwise creates the inspector
  69460. this._createInspector(config);
  69461. }
  69462. };
  69463. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  69464. return DebugLayer;
  69465. }());
  69466. BABYLON.DebugLayer = DebugLayer;
  69467. })(BABYLON || (BABYLON = {}));
  69468. //# sourceMappingURL=babylon.debugLayer.js.map
  69469. var BABYLON;
  69470. (function (BABYLON) {
  69471. var Debug;
  69472. (function (Debug) {
  69473. var PhysicsViewer = /** @class */ (function () {
  69474. function PhysicsViewer(scene) {
  69475. this._impostors = [];
  69476. this._meshes = [];
  69477. this._numMeshes = 0;
  69478. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69479. var physicEngine = this._scene.getPhysicsEngine();
  69480. if (physicEngine) {
  69481. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  69482. }
  69483. }
  69484. PhysicsViewer.prototype._updateDebugMeshes = function () {
  69485. var plugin = this._physicsEnginePlugin;
  69486. for (var i = 0; i < this._numMeshes; i++) {
  69487. var impostor = this._impostors[i];
  69488. if (!impostor) {
  69489. continue;
  69490. }
  69491. if (impostor.isDisposed) {
  69492. this.hideImpostor(this._impostors[i--]);
  69493. }
  69494. else {
  69495. var mesh = this._meshes[i];
  69496. if (mesh && plugin) {
  69497. plugin.syncMeshWithImpostor(mesh, impostor);
  69498. }
  69499. }
  69500. }
  69501. };
  69502. PhysicsViewer.prototype.showImpostor = function (impostor) {
  69503. if (!this._scene) {
  69504. return;
  69505. }
  69506. for (var i = 0; i < this._numMeshes; i++) {
  69507. if (this._impostors[i] == impostor) {
  69508. return;
  69509. }
  69510. }
  69511. var debugMesh = this._getDebugMesh(impostor, this._scene);
  69512. if (debugMesh) {
  69513. this._impostors[this._numMeshes] = impostor;
  69514. this._meshes[this._numMeshes] = debugMesh;
  69515. if (this._numMeshes === 0) {
  69516. this._renderFunction = this._updateDebugMeshes.bind(this);
  69517. this._scene.registerBeforeRender(this._renderFunction);
  69518. }
  69519. this._numMeshes++;
  69520. }
  69521. };
  69522. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  69523. if (!impostor || !this._scene) {
  69524. return;
  69525. }
  69526. var removed = false;
  69527. for (var i = 0; i < this._numMeshes; i++) {
  69528. if (this._impostors[i] == impostor) {
  69529. var mesh = this._meshes[i];
  69530. if (!mesh) {
  69531. continue;
  69532. }
  69533. this._scene.removeMesh(mesh);
  69534. mesh.dispose();
  69535. this._numMeshes--;
  69536. if (this._numMeshes > 0) {
  69537. this._meshes[i] = this._meshes[this._numMeshes];
  69538. this._impostors[i] = this._impostors[this._numMeshes];
  69539. this._meshes[this._numMeshes] = null;
  69540. this._impostors[this._numMeshes] = null;
  69541. }
  69542. else {
  69543. this._meshes[0] = null;
  69544. this._impostors[0] = null;
  69545. }
  69546. removed = true;
  69547. break;
  69548. }
  69549. }
  69550. if (removed && this._numMeshes === 0) {
  69551. this._scene.unregisterBeforeRender(this._renderFunction);
  69552. }
  69553. };
  69554. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  69555. if (!this._debugMaterial) {
  69556. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  69557. this._debugMaterial.wireframe = true;
  69558. }
  69559. return this._debugMaterial;
  69560. };
  69561. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  69562. if (!this._debugBoxMesh) {
  69563. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  69564. this._debugBoxMesh.renderingGroupId = 1;
  69565. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69566. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  69567. scene.removeMesh(this._debugBoxMesh);
  69568. }
  69569. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  69570. };
  69571. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  69572. if (!this._debugSphereMesh) {
  69573. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  69574. this._debugSphereMesh.renderingGroupId = 1;
  69575. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69576. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  69577. scene.removeMesh(this._debugSphereMesh);
  69578. }
  69579. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  69580. };
  69581. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  69582. var mesh = null;
  69583. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  69584. mesh = this._getDebugBoxMesh(scene);
  69585. impostor.getBoxSizeToRef(mesh.scaling);
  69586. }
  69587. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  69588. mesh = this._getDebugSphereMesh(scene);
  69589. var radius = impostor.getRadius();
  69590. mesh.scaling.x = radius * 2;
  69591. mesh.scaling.y = radius * 2;
  69592. mesh.scaling.z = radius * 2;
  69593. }
  69594. return mesh;
  69595. };
  69596. PhysicsViewer.prototype.dispose = function () {
  69597. for (var i = 0; i < this._numMeshes; i++) {
  69598. this.hideImpostor(this._impostors[i]);
  69599. }
  69600. if (this._debugBoxMesh) {
  69601. this._debugBoxMesh.dispose();
  69602. }
  69603. if (this._debugSphereMesh) {
  69604. this._debugSphereMesh.dispose();
  69605. }
  69606. if (this._debugMaterial) {
  69607. this._debugMaterial.dispose();
  69608. }
  69609. this._impostors.length = 0;
  69610. this._scene = null;
  69611. this._physicsEnginePlugin = null;
  69612. };
  69613. return PhysicsViewer;
  69614. }());
  69615. Debug.PhysicsViewer = PhysicsViewer;
  69616. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69617. })(BABYLON || (BABYLON = {}));
  69618. //# sourceMappingURL=babylon.physicsViewer.js.map
  69619. var BABYLON;
  69620. (function (BABYLON) {
  69621. var BoundingBoxRenderer = /** @class */ (function () {
  69622. function BoundingBoxRenderer(scene) {
  69623. this.frontColor = new BABYLON.Color3(1, 1, 1);
  69624. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  69625. this.showBackLines = true;
  69626. this.renderList = new BABYLON.SmartArray(32);
  69627. this._vertexBuffers = {};
  69628. this._scene = scene;
  69629. }
  69630. BoundingBoxRenderer.prototype._prepareRessources = function () {
  69631. if (this._colorShader) {
  69632. return;
  69633. }
  69634. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  69635. attributes: [BABYLON.VertexBuffer.PositionKind],
  69636. uniforms: ["world", "viewProjection", "color"]
  69637. });
  69638. var engine = this._scene.getEngine();
  69639. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  69640. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  69641. this._createIndexBuffer();
  69642. };
  69643. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  69644. var engine = this._scene.getEngine();
  69645. 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]);
  69646. };
  69647. BoundingBoxRenderer.prototype._rebuild = function () {
  69648. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69649. if (vb) {
  69650. vb._rebuild();
  69651. }
  69652. this._createIndexBuffer();
  69653. };
  69654. BoundingBoxRenderer.prototype.reset = function () {
  69655. this.renderList.reset();
  69656. };
  69657. BoundingBoxRenderer.prototype.render = function () {
  69658. if (this.renderList.length === 0) {
  69659. return;
  69660. }
  69661. this._prepareRessources();
  69662. if (!this._colorShader.isReady()) {
  69663. return;
  69664. }
  69665. var engine = this._scene.getEngine();
  69666. engine.setDepthWrite(false);
  69667. this._colorShader._preBind();
  69668. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  69669. var boundingBox = this.renderList.data[boundingBoxIndex];
  69670. var min = boundingBox.minimum;
  69671. var max = boundingBox.maximum;
  69672. var diff = max.subtract(min);
  69673. var median = min.add(diff.scale(0.5));
  69674. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69675. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69676. .multiply(boundingBox.getWorldMatrix());
  69677. // VBOs
  69678. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69679. if (this.showBackLines) {
  69680. // Back
  69681. engine.setDepthFunctionToGreaterOrEqual();
  69682. this._scene.resetCachedMaterial();
  69683. this._colorShader.setColor4("color", this.backColor.toColor4());
  69684. this._colorShader.bind(worldMatrix);
  69685. // Draw order
  69686. engine.draw(false, 0, 24);
  69687. }
  69688. // Front
  69689. engine.setDepthFunctionToLess();
  69690. this._scene.resetCachedMaterial();
  69691. this._colorShader.setColor4("color", this.frontColor.toColor4());
  69692. this._colorShader.bind(worldMatrix);
  69693. // Draw order
  69694. engine.draw(false, 0, 24);
  69695. }
  69696. this._colorShader.unbind();
  69697. engine.setDepthFunctionToLessOrEqual();
  69698. engine.setDepthWrite(true);
  69699. };
  69700. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  69701. this._prepareRessources();
  69702. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  69703. return;
  69704. }
  69705. var engine = this._scene.getEngine();
  69706. engine.setDepthWrite(false);
  69707. engine.setColorWrite(false);
  69708. this._colorShader._preBind();
  69709. var boundingBox = mesh._boundingInfo.boundingBox;
  69710. var min = boundingBox.minimum;
  69711. var max = boundingBox.maximum;
  69712. var diff = max.subtract(min);
  69713. var median = min.add(diff.scale(0.5));
  69714. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69715. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69716. .multiply(boundingBox.getWorldMatrix());
  69717. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69718. engine.setDepthFunctionToLess();
  69719. this._scene.resetCachedMaterial();
  69720. this._colorShader.bind(worldMatrix);
  69721. engine.draw(false, 0, 24);
  69722. this._colorShader.unbind();
  69723. engine.setDepthFunctionToLessOrEqual();
  69724. engine.setDepthWrite(true);
  69725. engine.setColorWrite(true);
  69726. };
  69727. BoundingBoxRenderer.prototype.dispose = function () {
  69728. if (!this._colorShader) {
  69729. return;
  69730. }
  69731. this.renderList.dispose();
  69732. this._colorShader.dispose();
  69733. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69734. if (buffer) {
  69735. buffer.dispose();
  69736. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69737. }
  69738. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69739. };
  69740. return BoundingBoxRenderer;
  69741. }());
  69742. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  69743. })(BABYLON || (BABYLON = {}));
  69744. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  69745. var BABYLON;
  69746. (function (BABYLON) {
  69747. var MorphTarget = /** @class */ (function () {
  69748. function MorphTarget(name, influence) {
  69749. if (influence === void 0) { influence = 0; }
  69750. this.name = name;
  69751. this.animations = new Array();
  69752. this._positions = null;
  69753. this._normals = null;
  69754. this._tangents = null;
  69755. this.onInfluenceChanged = new BABYLON.Observable();
  69756. this.influence = influence;
  69757. }
  69758. Object.defineProperty(MorphTarget.prototype, "influence", {
  69759. get: function () {
  69760. return this._influence;
  69761. },
  69762. set: function (influence) {
  69763. if (this._influence === influence) {
  69764. return;
  69765. }
  69766. var previous = this._influence;
  69767. this._influence = influence;
  69768. if (this.onInfluenceChanged.hasObservers) {
  69769. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  69770. }
  69771. },
  69772. enumerable: true,
  69773. configurable: true
  69774. });
  69775. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  69776. get: function () {
  69777. return !!this._positions;
  69778. },
  69779. enumerable: true,
  69780. configurable: true
  69781. });
  69782. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  69783. get: function () {
  69784. return !!this._normals;
  69785. },
  69786. enumerable: true,
  69787. configurable: true
  69788. });
  69789. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  69790. get: function () {
  69791. return !!this._tangents;
  69792. },
  69793. enumerable: true,
  69794. configurable: true
  69795. });
  69796. MorphTarget.prototype.setPositions = function (data) {
  69797. this._positions = data;
  69798. };
  69799. MorphTarget.prototype.getPositions = function () {
  69800. return this._positions;
  69801. };
  69802. MorphTarget.prototype.setNormals = function (data) {
  69803. this._normals = data;
  69804. };
  69805. MorphTarget.prototype.getNormals = function () {
  69806. return this._normals;
  69807. };
  69808. MorphTarget.prototype.setTangents = function (data) {
  69809. this._tangents = data;
  69810. };
  69811. MorphTarget.prototype.getTangents = function () {
  69812. return this._tangents;
  69813. };
  69814. /**
  69815. * Serializes the current target into a Serialization object.
  69816. * Returns the serialized object.
  69817. */
  69818. MorphTarget.prototype.serialize = function () {
  69819. var serializationObject = {};
  69820. serializationObject.name = this.name;
  69821. serializationObject.influence = this.influence;
  69822. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  69823. if (this.hasNormals) {
  69824. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  69825. }
  69826. if (this.hasTangents) {
  69827. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  69828. }
  69829. // Animations
  69830. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  69831. return serializationObject;
  69832. };
  69833. // Statics
  69834. MorphTarget.Parse = function (serializationObject) {
  69835. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  69836. result.setPositions(serializationObject.positions);
  69837. if (serializationObject.normals) {
  69838. result.setNormals(serializationObject.normals);
  69839. }
  69840. if (serializationObject.tangents) {
  69841. result.setTangents(serializationObject.tangents);
  69842. }
  69843. // Animations
  69844. if (serializationObject.animations) {
  69845. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  69846. var parsedAnimation = serializationObject.animations[animationIndex];
  69847. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69848. }
  69849. }
  69850. return result;
  69851. };
  69852. MorphTarget.FromMesh = function (mesh, name, influence) {
  69853. if (!name) {
  69854. name = mesh.name;
  69855. }
  69856. var result = new MorphTarget(name, influence);
  69857. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69859. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  69860. }
  69861. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  69862. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  69863. }
  69864. return result;
  69865. };
  69866. return MorphTarget;
  69867. }());
  69868. BABYLON.MorphTarget = MorphTarget;
  69869. })(BABYLON || (BABYLON = {}));
  69870. //# sourceMappingURL=babylon.morphTarget.js.map
  69871. var BABYLON;
  69872. (function (BABYLON) {
  69873. var MorphTargetManager = /** @class */ (function () {
  69874. function MorphTargetManager(scene) {
  69875. if (scene === void 0) { scene = null; }
  69876. this._targets = new Array();
  69877. this._targetObservable = new Array();
  69878. this._activeTargets = new BABYLON.SmartArray(16);
  69879. this._supportsNormals = false;
  69880. this._supportsTangents = false;
  69881. this._vertexCount = 0;
  69882. this._uniqueId = 0;
  69883. this._tempInfluences = new Array();
  69884. if (!scene) {
  69885. scene = BABYLON.Engine.LastCreatedScene;
  69886. }
  69887. this._scene = scene;
  69888. if (this._scene) {
  69889. this._scene.morphTargetManagers.push(this);
  69890. this._uniqueId = this._scene.getUniqueId();
  69891. }
  69892. }
  69893. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  69894. get: function () {
  69895. return this._uniqueId;
  69896. },
  69897. enumerable: true,
  69898. configurable: true
  69899. });
  69900. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  69901. get: function () {
  69902. return this._vertexCount;
  69903. },
  69904. enumerable: true,
  69905. configurable: true
  69906. });
  69907. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  69908. get: function () {
  69909. return this._supportsNormals;
  69910. },
  69911. enumerable: true,
  69912. configurable: true
  69913. });
  69914. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  69915. get: function () {
  69916. return this._supportsTangents;
  69917. },
  69918. enumerable: true,
  69919. configurable: true
  69920. });
  69921. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  69922. get: function () {
  69923. return this._targets.length;
  69924. },
  69925. enumerable: true,
  69926. configurable: true
  69927. });
  69928. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  69929. get: function () {
  69930. return this._activeTargets.length;
  69931. },
  69932. enumerable: true,
  69933. configurable: true
  69934. });
  69935. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  69936. get: function () {
  69937. return this._influences;
  69938. },
  69939. enumerable: true,
  69940. configurable: true
  69941. });
  69942. MorphTargetManager.prototype.getActiveTarget = function (index) {
  69943. return this._activeTargets.data[index];
  69944. };
  69945. MorphTargetManager.prototype.getTarget = function (index) {
  69946. return this._targets[index];
  69947. };
  69948. MorphTargetManager.prototype.addTarget = function (target) {
  69949. var _this = this;
  69950. this._targets.push(target);
  69951. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  69952. _this._syncActiveTargets(needUpdate);
  69953. }));
  69954. this._syncActiveTargets(true);
  69955. };
  69956. MorphTargetManager.prototype.removeTarget = function (target) {
  69957. var index = this._targets.indexOf(target);
  69958. if (index >= 0) {
  69959. this._targets.splice(index, 1);
  69960. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  69961. this._syncActiveTargets(true);
  69962. }
  69963. };
  69964. /**
  69965. * Serializes the current manager into a Serialization object.
  69966. * Returns the serialized object.
  69967. */
  69968. MorphTargetManager.prototype.serialize = function () {
  69969. var serializationObject = {};
  69970. serializationObject.id = this.uniqueId;
  69971. serializationObject.targets = [];
  69972. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69973. var target = _a[_i];
  69974. serializationObject.targets.push(target.serialize());
  69975. }
  69976. return serializationObject;
  69977. };
  69978. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  69979. var influenceCount = 0;
  69980. this._activeTargets.reset();
  69981. this._supportsNormals = true;
  69982. this._supportsTangents = true;
  69983. this._vertexCount = 0;
  69984. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69985. var target = _a[_i];
  69986. if (target.influence > 0) {
  69987. this._activeTargets.push(target);
  69988. this._tempInfluences[influenceCount++] = target.influence;
  69989. this._supportsNormals = this._supportsNormals && target.hasNormals;
  69990. this._supportsTangents = this._supportsTangents && target.hasTangents;
  69991. var positions = target.getPositions();
  69992. if (!positions) {
  69993. BABYLON.Tools.Error("Invalid target. Target must positions.");
  69994. return;
  69995. }
  69996. var vertexCount = positions.length / 3;
  69997. if (this._vertexCount === 0) {
  69998. this._vertexCount = vertexCount;
  69999. }
  70000. else if (this._vertexCount !== vertexCount) {
  70001. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  70002. return;
  70003. }
  70004. }
  70005. }
  70006. if (!this._influences || this._influences.length !== influenceCount) {
  70007. this._influences = new Float32Array(influenceCount);
  70008. }
  70009. for (var index = 0; index < influenceCount; index++) {
  70010. this._influences[index] = this._tempInfluences[index];
  70011. }
  70012. if (needUpdate && this._scene) {
  70013. // Flag meshes as dirty to resync with the active targets
  70014. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  70015. var mesh = _c[_b];
  70016. if (mesh.morphTargetManager === this) {
  70017. mesh._syncGeometryWithMorphTargetManager();
  70018. }
  70019. }
  70020. }
  70021. };
  70022. // Statics
  70023. MorphTargetManager.Parse = function (serializationObject, scene) {
  70024. var result = new MorphTargetManager(scene);
  70025. result._uniqueId = serializationObject.id;
  70026. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  70027. var targetData = _a[_i];
  70028. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  70029. }
  70030. return result;
  70031. };
  70032. return MorphTargetManager;
  70033. }());
  70034. BABYLON.MorphTargetManager = MorphTargetManager;
  70035. })(BABYLON || (BABYLON = {}));
  70036. //# sourceMappingURL=babylon.morphTargetManager.js.map
  70037. var BABYLON;
  70038. (function (BABYLON) {
  70039. var Octree = /** @class */ (function () {
  70040. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  70041. if (maxDepth === void 0) { maxDepth = 2; }
  70042. this.maxDepth = maxDepth;
  70043. this.dynamicContent = new Array();
  70044. this._maxBlockCapacity = maxBlockCapacity || 64;
  70045. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  70046. this._creationFunc = creationFunc;
  70047. }
  70048. // Methods
  70049. Octree.prototype.update = function (worldMin, worldMax, entries) {
  70050. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  70051. };
  70052. Octree.prototype.addMesh = function (entry) {
  70053. for (var index = 0; index < this.blocks.length; index++) {
  70054. var block = this.blocks[index];
  70055. block.addEntry(entry);
  70056. }
  70057. };
  70058. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  70059. this._selectionContent.reset();
  70060. for (var index = 0; index < this.blocks.length; index++) {
  70061. var block = this.blocks[index];
  70062. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  70063. }
  70064. if (allowDuplicate) {
  70065. this._selectionContent.concat(this.dynamicContent);
  70066. }
  70067. else {
  70068. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70069. }
  70070. return this._selectionContent;
  70071. };
  70072. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  70073. this._selectionContent.reset();
  70074. for (var index = 0; index < this.blocks.length; index++) {
  70075. var block = this.blocks[index];
  70076. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  70077. }
  70078. if (allowDuplicate) {
  70079. this._selectionContent.concat(this.dynamicContent);
  70080. }
  70081. else {
  70082. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70083. }
  70084. return this._selectionContent;
  70085. };
  70086. Octree.prototype.intersectsRay = function (ray) {
  70087. this._selectionContent.reset();
  70088. for (var index = 0; index < this.blocks.length; index++) {
  70089. var block = this.blocks[index];
  70090. block.intersectsRay(ray, this._selectionContent);
  70091. }
  70092. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70093. return this._selectionContent;
  70094. };
  70095. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  70096. target.blocks = new Array();
  70097. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  70098. // Segmenting space
  70099. for (var x = 0; x < 2; x++) {
  70100. for (var y = 0; y < 2; y++) {
  70101. for (var z = 0; z < 2; z++) {
  70102. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70103. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70104. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70105. block.addEntries(entries);
  70106. target.blocks.push(block);
  70107. }
  70108. }
  70109. }
  70110. };
  70111. Octree.CreationFuncForMeshes = function (entry, block) {
  70112. var boundingInfo = entry.getBoundingInfo();
  70113. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70114. block.entries.push(entry);
  70115. }
  70116. };
  70117. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70118. var boundingInfo = entry.getBoundingInfo();
  70119. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70120. block.entries.push(entry);
  70121. }
  70122. };
  70123. return Octree;
  70124. }());
  70125. BABYLON.Octree = Octree;
  70126. })(BABYLON || (BABYLON = {}));
  70127. //# sourceMappingURL=babylon.octree.js.map
  70128. var BABYLON;
  70129. (function (BABYLON) {
  70130. var OctreeBlock = /** @class */ (function () {
  70131. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70132. this.entries = new Array();
  70133. this._boundingVectors = new Array();
  70134. this._capacity = capacity;
  70135. this._depth = depth;
  70136. this._maxDepth = maxDepth;
  70137. this._creationFunc = creationFunc;
  70138. this._minPoint = minPoint;
  70139. this._maxPoint = maxPoint;
  70140. this._boundingVectors.push(minPoint.clone());
  70141. this._boundingVectors.push(maxPoint.clone());
  70142. this._boundingVectors.push(minPoint.clone());
  70143. this._boundingVectors[2].x = maxPoint.x;
  70144. this._boundingVectors.push(minPoint.clone());
  70145. this._boundingVectors[3].y = maxPoint.y;
  70146. this._boundingVectors.push(minPoint.clone());
  70147. this._boundingVectors[4].z = maxPoint.z;
  70148. this._boundingVectors.push(maxPoint.clone());
  70149. this._boundingVectors[5].z = minPoint.z;
  70150. this._boundingVectors.push(maxPoint.clone());
  70151. this._boundingVectors[6].x = minPoint.x;
  70152. this._boundingVectors.push(maxPoint.clone());
  70153. this._boundingVectors[7].y = minPoint.y;
  70154. }
  70155. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70156. // Property
  70157. get: function () {
  70158. return this._capacity;
  70159. },
  70160. enumerable: true,
  70161. configurable: true
  70162. });
  70163. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70164. get: function () {
  70165. return this._minPoint;
  70166. },
  70167. enumerable: true,
  70168. configurable: true
  70169. });
  70170. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70171. get: function () {
  70172. return this._maxPoint;
  70173. },
  70174. enumerable: true,
  70175. configurable: true
  70176. });
  70177. // Methods
  70178. OctreeBlock.prototype.addEntry = function (entry) {
  70179. if (this.blocks) {
  70180. for (var index = 0; index < this.blocks.length; index++) {
  70181. var block = this.blocks[index];
  70182. block.addEntry(entry);
  70183. }
  70184. return;
  70185. }
  70186. this._creationFunc(entry, this);
  70187. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  70188. this.createInnerBlocks();
  70189. }
  70190. };
  70191. OctreeBlock.prototype.addEntries = function (entries) {
  70192. for (var index = 0; index < entries.length; index++) {
  70193. var mesh = entries[index];
  70194. this.addEntry(mesh);
  70195. }
  70196. };
  70197. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  70198. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  70199. if (this.blocks) {
  70200. for (var index = 0; index < this.blocks.length; index++) {
  70201. var block = this.blocks[index];
  70202. block.select(frustumPlanes, selection, allowDuplicate);
  70203. }
  70204. return;
  70205. }
  70206. if (allowDuplicate) {
  70207. selection.concat(this.entries);
  70208. }
  70209. else {
  70210. selection.concatWithNoDuplicate(this.entries);
  70211. }
  70212. }
  70213. };
  70214. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  70215. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  70216. if (this.blocks) {
  70217. for (var index = 0; index < this.blocks.length; index++) {
  70218. var block = this.blocks[index];
  70219. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  70220. }
  70221. return;
  70222. }
  70223. if (allowDuplicate) {
  70224. selection.concat(this.entries);
  70225. }
  70226. else {
  70227. selection.concatWithNoDuplicate(this.entries);
  70228. }
  70229. }
  70230. };
  70231. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  70232. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  70233. if (this.blocks) {
  70234. for (var index = 0; index < this.blocks.length; index++) {
  70235. var block = this.blocks[index];
  70236. block.intersectsRay(ray, selection);
  70237. }
  70238. return;
  70239. }
  70240. selection.concatWithNoDuplicate(this.entries);
  70241. }
  70242. };
  70243. OctreeBlock.prototype.createInnerBlocks = function () {
  70244. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  70245. };
  70246. return OctreeBlock;
  70247. }());
  70248. BABYLON.OctreeBlock = OctreeBlock;
  70249. })(BABYLON || (BABYLON = {}));
  70250. //# sourceMappingURL=babylon.octreeBlock.js.map
  70251. var BABYLON;
  70252. (function (BABYLON) {
  70253. var SIMDVector3 = /** @class */ (function () {
  70254. function SIMDVector3() {
  70255. }
  70256. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  70257. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  70258. };
  70259. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  70260. var m = transformation.m;
  70261. var m0 = SIMD.Float32x4.load(m, 0);
  70262. var m1 = SIMD.Float32x4.load(m, 4);
  70263. var m2 = SIMD.Float32x4.load(m, 8);
  70264. var m3 = SIMD.Float32x4.load(m, 12);
  70265. 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));
  70266. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  70267. result.x = SIMD.Float32x4.extractLane(r, 0);
  70268. result.y = SIMD.Float32x4.extractLane(r, 1);
  70269. result.z = SIMD.Float32x4.extractLane(r, 2);
  70270. };
  70271. return SIMDVector3;
  70272. }());
  70273. var SIMDMatrix = /** @class */ (function () {
  70274. function SIMDMatrix() {
  70275. }
  70276. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  70277. var tm = this.m;
  70278. var om = other.m;
  70279. var m0 = SIMD.Float32x4.load(om, 0);
  70280. var m1 = SIMD.Float32x4.load(om, 4);
  70281. var m2 = SIMD.Float32x4.load(om, 8);
  70282. var m3 = SIMD.Float32x4.load(om, 12);
  70283. for (var i = 0; i < 16; i += 4) {
  70284. 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)))));
  70285. }
  70286. return this;
  70287. };
  70288. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  70289. var src = this.m;
  70290. var dest = other.m;
  70291. // Load the 4 rows
  70292. var src0 = SIMD.Float32x4.load(src, 0);
  70293. var src1 = SIMD.Float32x4.load(src, 4);
  70294. var src2 = SIMD.Float32x4.load(src, 8);
  70295. var src3 = SIMD.Float32x4.load(src, 12);
  70296. // Transpose the source matrix. Sort of. Not a true transpose operation
  70297. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  70298. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  70299. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  70300. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  70301. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  70302. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  70303. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  70304. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  70305. // This is a true transposition, but it will lead to an incorrect result
  70306. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  70307. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  70308. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70309. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70310. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  70311. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  70312. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70313. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70314. // ----
  70315. tmp1 = SIMD.Float32x4.mul(row2, row3);
  70316. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70317. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  70318. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  70319. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70320. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  70321. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  70322. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  70323. // ----
  70324. tmp1 = SIMD.Float32x4.mul(row1, row2);
  70325. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70326. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  70327. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  70328. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70329. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  70330. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  70331. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  70332. // ----
  70333. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  70334. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70335. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  70336. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  70337. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  70338. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70339. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  70340. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  70341. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  70342. // ----
  70343. tmp1 = SIMD.Float32x4.mul(row0, row1);
  70344. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70345. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70346. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  70347. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70348. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70349. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  70350. // ----
  70351. tmp1 = SIMD.Float32x4.mul(row0, row3);
  70352. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70353. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  70354. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  70355. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70356. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  70357. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  70358. // ----
  70359. tmp1 = SIMD.Float32x4.mul(row0, row2);
  70360. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70361. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  70362. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  70363. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70364. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  70365. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  70366. // Compute determinant
  70367. var det = SIMD.Float32x4.mul(row0, minor0);
  70368. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  70369. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  70370. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  70371. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  70372. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  70373. // These shuffles aren't necessary if the faulty transposition is done
  70374. // up at the top of this function.
  70375. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  70376. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  70377. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  70378. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  70379. // Compute final values by multiplying with 1/det
  70380. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  70381. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  70382. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  70383. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  70384. return this;
  70385. };
  70386. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  70387. var out = result.m;
  70388. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  70389. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  70390. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  70391. // cc.kmVec3Subtract(f, pCenter, pEye);
  70392. var f = SIMD.Float32x4.sub(center, eye);
  70393. // cc.kmVec3Normalize(f, f);
  70394. var tmp = SIMD.Float32x4.mul(f, f);
  70395. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70396. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70397. // cc.kmVec3Assign(up, pUp);
  70398. // cc.kmVec3Normalize(up, up);
  70399. tmp = SIMD.Float32x4.mul(up, up);
  70400. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70401. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70402. // cc.kmVec3Cross(s, f, up);
  70403. 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)));
  70404. // cc.kmVec3Normalize(s, s);
  70405. tmp = SIMD.Float32x4.mul(s, s);
  70406. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70407. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70408. // cc.kmVec3Cross(u, s, f);
  70409. 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)));
  70410. // cc.kmVec3Normalize(s, s);
  70411. tmp = SIMD.Float32x4.mul(s, s);
  70412. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70413. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70414. var zero = SIMD.Float32x4.splat(0.0);
  70415. s = SIMD.Float32x4.neg(s);
  70416. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  70417. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  70418. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  70419. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  70420. 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);
  70421. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  70422. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  70423. 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)))));
  70424. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  70425. 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)))));
  70426. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  70427. 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)))));
  70428. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  70429. 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)))));
  70430. };
  70431. return SIMDMatrix;
  70432. }());
  70433. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  70434. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  70435. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  70436. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  70437. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  70438. var SIMDHelper = /** @class */ (function () {
  70439. function SIMDHelper() {
  70440. }
  70441. Object.defineProperty(SIMDHelper, "IsEnabled", {
  70442. get: function () {
  70443. return SIMDHelper._isEnabled;
  70444. },
  70445. enumerable: true,
  70446. configurable: true
  70447. });
  70448. SIMDHelper.DisableSIMD = function () {
  70449. // Replace functions
  70450. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  70451. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  70452. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  70453. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  70454. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  70455. SIMDHelper._isEnabled = false;
  70456. };
  70457. SIMDHelper.EnableSIMD = function () {
  70458. if (self.SIMD === undefined) {
  70459. return;
  70460. }
  70461. // check if polyfills needed
  70462. if (!self.Math.fround) {
  70463. self.Math.fround = (function (array) { return function (x) {
  70464. return array[0] = x, array[0];
  70465. }; })(new Float32Array(1));
  70466. }
  70467. if (!self.Math.imul) {
  70468. self.Math.imul = function (a, b) {
  70469. var ah = (a >>> 16) & 0xffff;
  70470. var al = a & 0xffff;
  70471. var bh = (b >>> 16) & 0xffff;
  70472. var bl = b & 0xffff;
  70473. // the shift by 0 fixes the sign on the high part
  70474. // the final |0 converts the unsigned value into a signed value
  70475. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  70476. };
  70477. }
  70478. // Replace functions
  70479. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  70480. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  70481. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  70482. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  70483. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  70484. SIMDHelper._isEnabled = true;
  70485. };
  70486. SIMDHelper._isEnabled = false;
  70487. return SIMDHelper;
  70488. }());
  70489. BABYLON.SIMDHelper = SIMDHelper;
  70490. })(BABYLON || (BABYLON = {}));
  70491. //# sourceMappingURL=babylon.math.SIMD.js.map
  70492. var BABYLON;
  70493. (function (BABYLON) {
  70494. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  70495. __extends(VRDistortionCorrectionPostProcess, _super);
  70496. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  70497. var _this = _super.call(this, name, "vrDistortionCorrection", [
  70498. 'LensCenter',
  70499. 'Scale',
  70500. 'ScaleIn',
  70501. 'HmdWarpParam'
  70502. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  70503. _this._isRightEye = isRightEye;
  70504. _this._distortionFactors = vrMetrics.distortionK;
  70505. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  70506. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  70507. _this.adaptScaleToCurrentViewport = true;
  70508. _this.onSizeChangedObservable.add(function () {
  70509. _this.aspectRatio = _this.width * .5 / _this.height;
  70510. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  70511. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  70512. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  70513. });
  70514. _this.onApplyObservable.add(function (effect) {
  70515. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  70516. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  70517. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  70518. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  70519. });
  70520. return _this;
  70521. }
  70522. return VRDistortionCorrectionPostProcess;
  70523. }(BABYLON.PostProcess));
  70524. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  70525. })(BABYLON || (BABYLON = {}));
  70526. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  70527. var BABYLON;
  70528. (function (BABYLON) {
  70529. var AnaglyphPostProcess = /** @class */ (function (_super) {
  70530. __extends(AnaglyphPostProcess, _super);
  70531. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  70532. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  70533. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70534. _this.onApplyObservable.add(function (effect) {
  70535. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  70536. });
  70537. return _this;
  70538. }
  70539. return AnaglyphPostProcess;
  70540. }(BABYLON.PostProcess));
  70541. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  70542. })(BABYLON || (BABYLON = {}));
  70543. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  70544. var BABYLON;
  70545. (function (BABYLON) {
  70546. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  70547. __extends(StereoscopicInterlacePostProcess, _super);
  70548. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  70549. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  70550. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70551. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70552. _this.onSizeChangedObservable.add(function () {
  70553. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70554. });
  70555. _this.onApplyObservable.add(function (effect) {
  70556. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  70557. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  70558. });
  70559. return _this;
  70560. }
  70561. return StereoscopicInterlacePostProcess;
  70562. }(BABYLON.PostProcess));
  70563. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  70564. })(BABYLON || (BABYLON = {}));
  70565. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  70566. var BABYLON;
  70567. (function (BABYLON) {
  70568. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  70569. function FreeCameraDeviceOrientationInput() {
  70570. var _this = this;
  70571. this._screenOrientationAngle = 0;
  70572. this._screenQuaternion = new BABYLON.Quaternion();
  70573. this._alpha = 0;
  70574. this._beta = 0;
  70575. this._gamma = 0;
  70576. this._orientationChanged = function () {
  70577. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  70578. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  70579. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  70580. };
  70581. this._deviceOrientation = function (evt) {
  70582. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  70583. _this._beta = evt.beta !== null ? evt.beta : 0;
  70584. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  70585. };
  70586. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  70587. this._orientationChanged();
  70588. }
  70589. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  70590. get: function () {
  70591. return this._camera;
  70592. },
  70593. set: function (camera) {
  70594. this._camera = camera;
  70595. if (this._camera != null && !this._camera.rotationQuaternion) {
  70596. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  70597. }
  70598. },
  70599. enumerable: true,
  70600. configurable: true
  70601. });
  70602. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70603. window.addEventListener("orientationchange", this._orientationChanged);
  70604. window.addEventListener("deviceorientation", this._deviceOrientation);
  70605. //In certain cases, the attach control is called AFTER orientation was changed,
  70606. //So this is needed.
  70607. this._orientationChanged();
  70608. };
  70609. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  70610. window.removeEventListener("orientationchange", this._orientationChanged);
  70611. window.removeEventListener("deviceorientation", this._deviceOrientation);
  70612. };
  70613. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  70614. //if no device orientation provided, don't update the rotation.
  70615. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  70616. if (!this._alpha)
  70617. return;
  70618. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  70619. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  70620. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  70621. //Mirror on XY Plane
  70622. this._camera.rotationQuaternion.z *= -1;
  70623. this._camera.rotationQuaternion.w *= -1;
  70624. };
  70625. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  70626. return "FreeCameraDeviceOrientationInput";
  70627. };
  70628. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  70629. return "deviceOrientation";
  70630. };
  70631. return FreeCameraDeviceOrientationInput;
  70632. }());
  70633. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  70634. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  70635. })(BABYLON || (BABYLON = {}));
  70636. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  70637. var BABYLON;
  70638. (function (BABYLON) {
  70639. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  70640. function ArcRotateCameraVRDeviceOrientationInput() {
  70641. this.alphaCorrection = 1;
  70642. this.betaCorrection = 1;
  70643. this.gammaCorrection = 1;
  70644. this._alpha = 0;
  70645. this._gamma = 0;
  70646. this._dirty = false;
  70647. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  70648. }
  70649. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70650. this.camera.attachControl(element, noPreventDefault);
  70651. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  70652. };
  70653. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  70654. if (evt.alpha !== null) {
  70655. this._alpha = +evt.alpha | 0;
  70656. }
  70657. if (evt.gamma !== null) {
  70658. this._gamma = +evt.gamma | 0;
  70659. }
  70660. this._dirty = true;
  70661. };
  70662. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  70663. if (this._dirty) {
  70664. this._dirty = false;
  70665. if (this._gamma < 0) {
  70666. this._gamma = 180 + this._gamma;
  70667. }
  70668. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  70669. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  70670. }
  70671. };
  70672. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  70673. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  70674. };
  70675. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  70676. return "ArcRotateCameraVRDeviceOrientationInput";
  70677. };
  70678. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  70679. return "VRDeviceOrientation";
  70680. };
  70681. return ArcRotateCameraVRDeviceOrientationInput;
  70682. }());
  70683. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  70684. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  70685. })(BABYLON || (BABYLON = {}));
  70686. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  70687. var BABYLON;
  70688. (function (BABYLON) {
  70689. var VRCameraMetrics = /** @class */ (function () {
  70690. function VRCameraMetrics() {
  70691. this.compensateDistortion = true;
  70692. }
  70693. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  70694. get: function () {
  70695. return this.hResolution / (2 * this.vResolution);
  70696. },
  70697. enumerable: true,
  70698. configurable: true
  70699. });
  70700. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  70701. get: function () {
  70702. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  70703. },
  70704. enumerable: true,
  70705. configurable: true
  70706. });
  70707. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  70708. get: function () {
  70709. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70710. var h = (4 * meters) / this.hScreenSize;
  70711. return BABYLON.Matrix.Translation(h, 0, 0);
  70712. },
  70713. enumerable: true,
  70714. configurable: true
  70715. });
  70716. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  70717. get: function () {
  70718. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70719. var h = (4 * meters) / this.hScreenSize;
  70720. return BABYLON.Matrix.Translation(-h, 0, 0);
  70721. },
  70722. enumerable: true,
  70723. configurable: true
  70724. });
  70725. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  70726. get: function () {
  70727. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  70728. },
  70729. enumerable: true,
  70730. configurable: true
  70731. });
  70732. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  70733. get: function () {
  70734. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  70735. },
  70736. enumerable: true,
  70737. configurable: true
  70738. });
  70739. VRCameraMetrics.GetDefault = function () {
  70740. var result = new VRCameraMetrics();
  70741. result.hResolution = 1280;
  70742. result.vResolution = 800;
  70743. result.hScreenSize = 0.149759993;
  70744. result.vScreenSize = 0.0935999975;
  70745. result.vScreenCenter = 0.0467999987;
  70746. result.eyeToScreenDistance = 0.0410000011;
  70747. result.lensSeparationDistance = 0.0635000020;
  70748. result.interpupillaryDistance = 0.0640000030;
  70749. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  70750. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  70751. result.postProcessScaleFactor = 1.714605507808412;
  70752. result.lensCenterOffset = 0.151976421;
  70753. return result;
  70754. };
  70755. return VRCameraMetrics;
  70756. }());
  70757. BABYLON.VRCameraMetrics = VRCameraMetrics;
  70758. })(BABYLON || (BABYLON = {}));
  70759. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  70760. var BABYLON;
  70761. (function (BABYLON) {
  70762. var WebVRFreeCamera = /** @class */ (function (_super) {
  70763. __extends(WebVRFreeCamera, _super);
  70764. function WebVRFreeCamera(name, position, scene, webVROptions) {
  70765. if (webVROptions === void 0) { webVROptions = {}; }
  70766. var _this = _super.call(this, name, position, scene) || this;
  70767. _this.webVROptions = webVROptions;
  70768. _this._vrDevice = null;
  70769. _this.rawPose = null;
  70770. _this._specsVersion = "1.1";
  70771. _this._attached = false;
  70772. _this._descendants = [];
  70773. _this.devicePosition = BABYLON.Vector3.Zero();
  70774. _this.deviceScaleFactor = 1;
  70775. _this.controllers = [];
  70776. _this.onControllersAttachedObservable = new BABYLON.Observable();
  70777. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  70778. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  70779. _this.minZ = 0.1;
  70780. //legacy support - the compensation boolean was removed.
  70781. if (arguments.length === 5) {
  70782. _this.webVROptions = arguments[4];
  70783. }
  70784. // default webVR options
  70785. if (_this.webVROptions.trackPosition == undefined) {
  70786. _this.webVROptions.trackPosition = true;
  70787. }
  70788. if (_this.webVROptions.controllerMeshes == undefined) {
  70789. _this.webVROptions.controllerMeshes = true;
  70790. }
  70791. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  70792. _this.webVROptions.defaultLightingOnControllers = true;
  70793. }
  70794. _this.rotationQuaternion = new BABYLON.Quaternion();
  70795. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70796. if (_this.webVROptions && _this.webVROptions.positionScale) {
  70797. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  70798. }
  70799. //enable VR
  70800. var engine = _this.getEngine();
  70801. _this._onVREnabled = function (success) { if (success) {
  70802. _this.initControllers();
  70803. } };
  70804. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  70805. engine.initWebVR().add(function (event) {
  70806. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  70807. return;
  70808. }
  70809. _this._vrDevice = event.vrDisplay;
  70810. //reset the rig parameters.
  70811. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  70812. if (_this._attached) {
  70813. _this.getEngine().enableVR();
  70814. }
  70815. });
  70816. if (typeof (VRFrameData) !== "undefined")
  70817. _this._frameData = new VRFrameData();
  70818. /**
  70819. * The idea behind the following lines:
  70820. * objects that have the camera as parent should actually have the rig cameras as a parent.
  70821. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  70822. * the second will not show it correctly.
  70823. *
  70824. * To solve this - each object that has the camera as parent will be added to a protected array.
  70825. * When the rig camera renders, it will take this array and set all of those to be its children.
  70826. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  70827. * Amazing!
  70828. */
  70829. scene.onBeforeCameraRenderObservable.add(function (camera) {
  70830. if (camera.parent === _this && _this.rigParenting) {
  70831. _this._descendants = _this.getDescendants(true, function (n) {
  70832. // don't take the cameras or the controllers!
  70833. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  70834. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  70835. return !isController && !isRigCamera;
  70836. });
  70837. _this._descendants.forEach(function (node) {
  70838. node.parent = camera;
  70839. });
  70840. }
  70841. });
  70842. scene.onAfterCameraRenderObservable.add(function (camera) {
  70843. if (camera.parent === _this && _this.rigParenting) {
  70844. _this._descendants.forEach(function (node) {
  70845. node.parent = _this;
  70846. });
  70847. }
  70848. });
  70849. return _this;
  70850. }
  70851. WebVRFreeCamera.prototype.dispose = function () {
  70852. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  70853. _super.prototype.dispose.call(this);
  70854. };
  70855. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  70856. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  70857. var gp = _a[_i];
  70858. if (gp.hand === name) {
  70859. return gp;
  70860. }
  70861. }
  70862. return null;
  70863. };
  70864. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  70865. get: function () {
  70866. if (!this._leftController) {
  70867. this._leftController = this.getControllerByName("left");
  70868. }
  70869. return this._leftController;
  70870. },
  70871. enumerable: true,
  70872. configurable: true
  70873. });
  70874. ;
  70875. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  70876. get: function () {
  70877. if (!this._rightController) {
  70878. this._rightController = this.getControllerByName("right");
  70879. }
  70880. return this._rightController;
  70881. },
  70882. enumerable: true,
  70883. configurable: true
  70884. });
  70885. ;
  70886. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  70887. if (length === void 0) { length = 100; }
  70888. if (this.leftCamera) {
  70889. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  70890. }
  70891. else {
  70892. return _super.prototype.getForwardRay.call(this, length);
  70893. }
  70894. };
  70895. WebVRFreeCamera.prototype._checkInputs = function () {
  70896. if (this._vrDevice && this._vrDevice.isPresenting) {
  70897. this._vrDevice.getFrameData(this._frameData);
  70898. this.updateFromDevice(this._frameData.pose);
  70899. }
  70900. _super.prototype._checkInputs.call(this);
  70901. };
  70902. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  70903. if (poseData && poseData.orientation) {
  70904. this.rawPose = poseData;
  70905. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  70906. if (this.getScene().useRightHandedSystem) {
  70907. this.deviceRotationQuaternion.z *= -1;
  70908. this.deviceRotationQuaternion.w *= -1;
  70909. }
  70910. if (this.webVROptions.trackPosition && this.rawPose.position) {
  70911. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  70912. if (this.getScene().useRightHandedSystem) {
  70913. this.devicePosition.z *= -1;
  70914. }
  70915. }
  70916. }
  70917. };
  70918. /**
  70919. * WebVR's attach control will start broadcasting frames to the device.
  70920. * Note that in certain browsers (chrome for example) this function must be called
  70921. * within a user-interaction callback. Example:
  70922. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  70923. *
  70924. * @param {HTMLElement} element
  70925. * @param {boolean} [noPreventDefault]
  70926. *
  70927. * @memberOf WebVRFreeCamera
  70928. */
  70929. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  70930. _super.prototype.attachControl.call(this, element, noPreventDefault);
  70931. this._attached = true;
  70932. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  70933. if (this._vrDevice) {
  70934. this.getEngine().enableVR();
  70935. }
  70936. };
  70937. WebVRFreeCamera.prototype.detachControl = function (element) {
  70938. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70939. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70940. _super.prototype.detachControl.call(this, element);
  70941. this._attached = false;
  70942. this.getEngine().disableVR();
  70943. };
  70944. WebVRFreeCamera.prototype.getClassName = function () {
  70945. return "WebVRFreeCamera";
  70946. };
  70947. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  70948. //uses the vrDisplay's "resetPose()".
  70949. //pitch and roll won't be affected.
  70950. this._vrDevice.resetPose();
  70951. };
  70952. WebVRFreeCamera.prototype._updateRigCameras = function () {
  70953. var camLeft = this._rigCameras[0];
  70954. var camRight = this._rigCameras[1];
  70955. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70956. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70957. camLeft.position.copyFrom(this.devicePosition);
  70958. camRight.position.copyFrom(this.devicePosition);
  70959. };
  70960. /**
  70961. * This function is called by the two RIG cameras.
  70962. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  70963. */
  70964. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  70965. var _this = this;
  70966. //WebVR 1.1
  70967. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  70968. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  70969. if (!this.getScene().useRightHandedSystem) {
  70970. [2, 6, 8, 9, 14].forEach(function (num) {
  70971. _this._webvrViewMatrix.m[num] *= -1;
  70972. });
  70973. }
  70974. // update the camera rotation matrix
  70975. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  70976. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  70977. // Computing target and final matrix
  70978. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  70979. var parentCamera = this._cameraRigParams["parentCamera"];
  70980. // should the view matrix be updated with scale and position offset?
  70981. if (parentCamera.deviceScaleFactor !== 1) {
  70982. this._webvrViewMatrix.invert();
  70983. // scale the position, if set
  70984. if (parentCamera.deviceScaleFactor) {
  70985. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  70986. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  70987. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  70988. }
  70989. this._webvrViewMatrix.invert();
  70990. }
  70991. return this._webvrViewMatrix;
  70992. };
  70993. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  70994. var _this = this;
  70995. var parentCamera = this.parent;
  70996. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  70997. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  70998. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  70999. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  71000. //babylon compatible matrix
  71001. if (!this.getScene().useRightHandedSystem) {
  71002. [8, 9, 10, 11].forEach(function (num) {
  71003. _this._projectionMatrix.m[num] *= -1;
  71004. });
  71005. }
  71006. return this._projectionMatrix;
  71007. };
  71008. WebVRFreeCamera.prototype.initControllers = function () {
  71009. var _this = this;
  71010. this.controllers = [];
  71011. var manager = this.getScene().gamepadManager;
  71012. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71013. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71014. var webVrController = gamepad;
  71015. if (webVrController.defaultModel) {
  71016. webVrController.defaultModel.setEnabled(false);
  71017. }
  71018. }
  71019. });
  71020. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71021. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71022. var webVrController_1 = gamepad;
  71023. if (_this.webVROptions.controllerMeshes) {
  71024. if (webVrController_1.defaultModel) {
  71025. webVrController_1.defaultModel.setEnabled(true);
  71026. }
  71027. else {
  71028. // Load the meshes
  71029. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  71030. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  71031. if (_this.webVROptions.defaultLightingOnControllers) {
  71032. if (!_this._lightOnControllers) {
  71033. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  71034. }
  71035. var activateLightOnSubMeshes_1 = function (mesh, light) {
  71036. var children = mesh.getChildren();
  71037. if (children.length !== 0) {
  71038. children.forEach(function (mesh) {
  71039. light.includedOnlyMeshes.push(mesh);
  71040. activateLightOnSubMeshes_1(mesh, light);
  71041. });
  71042. }
  71043. };
  71044. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  71045. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  71046. }
  71047. });
  71048. }
  71049. }
  71050. webVrController_1.attachToPoseControlledCamera(_this);
  71051. // since this is async - sanity check. Is the controller already stored?
  71052. if (_this.controllers.indexOf(webVrController_1) === -1) {
  71053. //add to the controllers array
  71054. _this.controllers.push(webVrController_1);
  71055. //did we find enough controllers? Great! let the developer know.
  71056. if (_this.controllers.length >= 2) {
  71057. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  71058. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  71059. // So we're overriding setting left & right manually to be sure
  71060. var firstViveWandDetected = false;
  71061. for (var i = 0; i < _this.controllers.length; i++) {
  71062. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  71063. if (!firstViveWandDetected) {
  71064. firstViveWandDetected = true;
  71065. _this.controllers[i].hand = "left";
  71066. }
  71067. else {
  71068. _this.controllers[i].hand = "right";
  71069. }
  71070. }
  71071. }
  71072. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  71073. }
  71074. }
  71075. }
  71076. });
  71077. };
  71078. return WebVRFreeCamera;
  71079. }(BABYLON.FreeCamera));
  71080. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  71081. })(BABYLON || (BABYLON = {}));
  71082. //# sourceMappingURL=babylon.webVRCamera.js.map
  71083. var BABYLON;
  71084. (function (BABYLON) {
  71085. // We're mainly based on the logic defined into the FreeCamera code
  71086. var DeviceOrientationCamera = /** @class */ (function (_super) {
  71087. __extends(DeviceOrientationCamera, _super);
  71088. function DeviceOrientationCamera(name, position, scene) {
  71089. var _this = _super.call(this, name, position, scene) || this;
  71090. _this._quaternionCache = new BABYLON.Quaternion();
  71091. _this.inputs.addDeviceOrientation();
  71092. return _this;
  71093. }
  71094. DeviceOrientationCamera.prototype.getClassName = function () {
  71095. return "DeviceOrientationCamera";
  71096. };
  71097. DeviceOrientationCamera.prototype._checkInputs = function () {
  71098. _super.prototype._checkInputs.call(this);
  71099. this._quaternionCache.copyFrom(this.rotationQuaternion);
  71100. if (this._initialQuaternion) {
  71101. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71102. }
  71103. };
  71104. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  71105. var _this = this;
  71106. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  71107. //can only work if this camera has a rotation quaternion already.
  71108. if (!this.rotationQuaternion)
  71109. return;
  71110. if (!this._initialQuaternion) {
  71111. this._initialQuaternion = new BABYLON.Quaternion();
  71112. }
  71113. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  71114. ['x', 'y', 'z'].forEach(function (axisName) {
  71115. if (!axis[axisName]) {
  71116. _this._initialQuaternion[axisName] = 0;
  71117. }
  71118. else {
  71119. _this._initialQuaternion[axisName] *= -1;
  71120. }
  71121. });
  71122. this._initialQuaternion.normalize();
  71123. //force rotation update
  71124. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71125. };
  71126. return DeviceOrientationCamera;
  71127. }(BABYLON.FreeCamera));
  71128. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  71129. })(BABYLON || (BABYLON = {}));
  71130. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  71131. var BABYLON;
  71132. (function (BABYLON) {
  71133. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  71134. __extends(VRDeviceOrientationFreeCamera, _super);
  71135. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71136. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71137. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71138. var _this = _super.call(this, name, position, scene) || this;
  71139. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71140. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71141. return _this;
  71142. }
  71143. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  71144. return "VRDeviceOrientationFreeCamera";
  71145. };
  71146. return VRDeviceOrientationFreeCamera;
  71147. }(BABYLON.DeviceOrientationCamera));
  71148. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  71149. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  71150. __extends(VRDeviceOrientationGamepadCamera, _super);
  71151. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71152. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71153. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71154. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  71155. _this.inputs.addGamepad();
  71156. return _this;
  71157. }
  71158. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  71159. return "VRDeviceOrientationGamepadCamera";
  71160. };
  71161. return VRDeviceOrientationGamepadCamera;
  71162. }(VRDeviceOrientationFreeCamera));
  71163. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  71164. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  71165. __extends(VRDeviceOrientationArcRotateCamera, _super);
  71166. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  71167. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71168. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71169. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71170. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71171. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71172. _this.inputs.addVRDeviceOrientation();
  71173. return _this;
  71174. }
  71175. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  71176. return "VRDeviceOrientationArcRotateCamera";
  71177. };
  71178. return VRDeviceOrientationArcRotateCamera;
  71179. }(BABYLON.ArcRotateCamera));
  71180. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  71181. })(BABYLON || (BABYLON = {}));
  71182. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  71183. var BABYLON;
  71184. (function (BABYLON) {
  71185. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  71186. __extends(AnaglyphFreeCamera, _super);
  71187. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  71188. var _this = _super.call(this, name, position, scene) || this;
  71189. _this.interaxialDistance = interaxialDistance;
  71190. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71191. return _this;
  71192. }
  71193. AnaglyphFreeCamera.prototype.getClassName = function () {
  71194. return "AnaglyphFreeCamera";
  71195. };
  71196. return AnaglyphFreeCamera;
  71197. }(BABYLON.FreeCamera));
  71198. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  71199. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  71200. __extends(AnaglyphArcRotateCamera, _super);
  71201. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  71202. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71203. _this.interaxialDistance = interaxialDistance;
  71204. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71205. return _this;
  71206. }
  71207. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  71208. return "AnaglyphArcRotateCamera";
  71209. };
  71210. return AnaglyphArcRotateCamera;
  71211. }(BABYLON.ArcRotateCamera));
  71212. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  71213. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  71214. __extends(AnaglyphGamepadCamera, _super);
  71215. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  71216. var _this = _super.call(this, name, position, scene) || this;
  71217. _this.interaxialDistance = interaxialDistance;
  71218. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71219. return _this;
  71220. }
  71221. AnaglyphGamepadCamera.prototype.getClassName = function () {
  71222. return "AnaglyphGamepadCamera";
  71223. };
  71224. return AnaglyphGamepadCamera;
  71225. }(BABYLON.GamepadCamera));
  71226. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  71227. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  71228. __extends(AnaglyphUniversalCamera, _super);
  71229. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  71230. var _this = _super.call(this, name, position, scene) || this;
  71231. _this.interaxialDistance = interaxialDistance;
  71232. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71233. return _this;
  71234. }
  71235. AnaglyphUniversalCamera.prototype.getClassName = function () {
  71236. return "AnaglyphUniversalCamera";
  71237. };
  71238. return AnaglyphUniversalCamera;
  71239. }(BABYLON.UniversalCamera));
  71240. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  71241. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  71242. __extends(StereoscopicFreeCamera, _super);
  71243. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71244. var _this = _super.call(this, name, position, scene) || this;
  71245. _this.interaxialDistance = interaxialDistance;
  71246. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71247. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71248. return _this;
  71249. }
  71250. StereoscopicFreeCamera.prototype.getClassName = function () {
  71251. return "StereoscopicFreeCamera";
  71252. };
  71253. return StereoscopicFreeCamera;
  71254. }(BABYLON.FreeCamera));
  71255. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  71256. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  71257. __extends(StereoscopicArcRotateCamera, _super);
  71258. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  71259. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71260. _this.interaxialDistance = interaxialDistance;
  71261. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71262. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71263. return _this;
  71264. }
  71265. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  71266. return "StereoscopicArcRotateCamera";
  71267. };
  71268. return StereoscopicArcRotateCamera;
  71269. }(BABYLON.ArcRotateCamera));
  71270. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  71271. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  71272. __extends(StereoscopicGamepadCamera, _super);
  71273. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71274. var _this = _super.call(this, name, position, scene) || this;
  71275. _this.interaxialDistance = interaxialDistance;
  71276. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71277. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71278. return _this;
  71279. }
  71280. StereoscopicGamepadCamera.prototype.getClassName = function () {
  71281. return "StereoscopicGamepadCamera";
  71282. };
  71283. return StereoscopicGamepadCamera;
  71284. }(BABYLON.GamepadCamera));
  71285. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  71286. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  71287. __extends(StereoscopicUniversalCamera, _super);
  71288. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71289. var _this = _super.call(this, name, position, scene) || this;
  71290. _this.interaxialDistance = interaxialDistance;
  71291. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71292. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71293. return _this;
  71294. }
  71295. StereoscopicUniversalCamera.prototype.getClassName = function () {
  71296. return "StereoscopicUniversalCamera";
  71297. };
  71298. return StereoscopicUniversalCamera;
  71299. }(BABYLON.UniversalCamera));
  71300. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  71301. })(BABYLON || (BABYLON = {}));
  71302. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  71303. var BABYLON;
  71304. (function (BABYLON) {
  71305. var VRExperienceHelper = /** @class */ (function () {
  71306. function VRExperienceHelper(scene, webVROptions) {
  71307. if (webVROptions === void 0) { webVROptions = {}; }
  71308. var _this = this;
  71309. this.webVROptions = webVROptions;
  71310. // Can the system support WebVR, even if a headset isn't plugged in?
  71311. this._webVRsupported = false;
  71312. // If WebVR is supported, is a headset plugged in and are we ready to present?
  71313. this._webVRready = false;
  71314. // Are we waiting for the requestPresent callback to complete?
  71315. this._webVRrequesting = false;
  71316. // Are we presenting to the headset right now?
  71317. this._webVRpresenting = false;
  71318. // Are we presenting in the fullscreen fallback?
  71319. this._fullscreenVRpresenting = false;
  71320. this._useCustomVRButton = false;
  71321. this._teleportationRequested = false;
  71322. this._teleportationEnabledOnLeftController = false;
  71323. this._teleportationEnabledOnRightController = false;
  71324. this._leftControllerReady = false;
  71325. this._rightControllerReady = false;
  71326. this._teleportationAllowed = false;
  71327. this._rotationAllowed = true;
  71328. this._teleportationRequestInitiated = false;
  71329. this._rotationRightAsked = false;
  71330. this._rotationLeftAsked = false;
  71331. this._teleportationFillColor = "#444444";
  71332. this._teleportationBorderColor = "#FFFFFF";
  71333. this._rotationAngle = 0;
  71334. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  71335. this._padSensibilityUp = 0.65;
  71336. this._padSensibilityDown = 0.35;
  71337. this.onNewMeshSelected = new BABYLON.Observable();
  71338. this._pointerDownOnMeshAsked = false;
  71339. this._isActionableMesh = false;
  71340. this._scene = scene;
  71341. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  71342. this._position = new BABYLON.Vector3(0, 2, 0);
  71343. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 1.7, 0), scene);
  71344. }
  71345. else {
  71346. this._position = this._scene.activeCamera.position.clone();
  71347. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, scene);
  71348. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  71349. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  71350. }
  71351. this._scene.activeCamera = this._deviceOrientationCamera;
  71352. this._canvas = scene.getEngine().getRenderingCanvas();
  71353. if (this._canvas) {
  71354. this._scene.activeCamera.attachControl(this._canvas);
  71355. }
  71356. if (webVROptions) {
  71357. if (webVROptions.useCustomVRButton) {
  71358. this._useCustomVRButton = true;
  71359. if (webVROptions.customVRButton) {
  71360. this._btnVR = webVROptions.customVRButton;
  71361. }
  71362. }
  71363. }
  71364. if (!this._useCustomVRButton) {
  71365. this._btnVR = document.createElement("BUTTON");
  71366. this._btnVR.className = "babylonVRicon";
  71367. this._btnVR.id = "babylonVRiconbtn";
  71368. this._btnVR.title = "Click to switch to VR";
  71369. 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) }";
  71370. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  71371. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  71372. // css += ".babylonVRicon.vrdisplaysupported { }";
  71373. // css += ".babylonVRicon.vrdisplayready { }";
  71374. // css += ".babylonVRicon.vrdisplayrequesting { }";
  71375. var style = document.createElement('style');
  71376. style.appendChild(document.createTextNode(css));
  71377. document.getElementsByTagName('head')[0].appendChild(style);
  71378. }
  71379. if (this._canvas) {
  71380. if (!this._useCustomVRButton) {
  71381. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71382. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71383. }
  71384. if (this._btnVR) {
  71385. this._btnVR.addEventListener("click", function () {
  71386. _this.enterVR();
  71387. });
  71388. }
  71389. window.addEventListener("resize", function () {
  71390. if (_this._canvas && !_this._useCustomVRButton) {
  71391. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  71392. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  71393. }
  71394. if (_this._fullscreenVRpresenting && _this._webVRready) {
  71395. _this.exitVR();
  71396. }
  71397. });
  71398. }
  71399. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71400. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71401. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71402. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71403. if (!this._useCustomVRButton) {
  71404. document.body.appendChild(this._btnVR);
  71405. }
  71406. // Exiting VR mode using 'ESC' key on desktop
  71407. this._onKeyDown = function (event) {
  71408. if (event.keyCode === 27 && _this.isInVRMode()) {
  71409. _this.exitVR();
  71410. }
  71411. };
  71412. document.addEventListener("keydown", this._onKeyDown);
  71413. // Exiting VR mode double tapping the touch screen
  71414. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  71415. if (_this.isInVRMode()) {
  71416. _this.exitVR();
  71417. if (_this._fullscreenVRpresenting) {
  71418. _this._scene.getEngine().switchFullscreen(true);
  71419. }
  71420. }
  71421. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  71422. // Listen for WebVR display changes
  71423. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  71424. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  71425. this._onVRRequestPresentStart = function () {
  71426. _this._webVRrequesting = true;
  71427. _this.updateButtonVisibility();
  71428. };
  71429. this._onVRRequestPresentComplete = function (success) {
  71430. _this._webVRrequesting = false;
  71431. _this.updateButtonVisibility();
  71432. };
  71433. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  71434. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  71435. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  71436. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  71437. // Create the cameras
  71438. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  71439. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  71440. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  71441. this.updateButtonVisibility();
  71442. }
  71443. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  71444. get: function () {
  71445. return this._deviceOrientationCamera;
  71446. },
  71447. enumerable: true,
  71448. configurable: true
  71449. });
  71450. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  71451. // Based on the current WebVR support, returns the current VR camera used
  71452. get: function () {
  71453. if (this._webVRready) {
  71454. return this._webVRCamera;
  71455. }
  71456. else {
  71457. return this._vrDeviceOrientationCamera;
  71458. }
  71459. },
  71460. enumerable: true,
  71461. configurable: true
  71462. });
  71463. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  71464. get: function () {
  71465. return this._webVRCamera;
  71466. },
  71467. enumerable: true,
  71468. configurable: true
  71469. });
  71470. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  71471. get: function () {
  71472. return this._vrDeviceOrientationCamera;
  71473. },
  71474. enumerable: true,
  71475. configurable: true
  71476. });
  71477. // Raised when one of the controller has loaded successfully its associated default mesh
  71478. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  71479. if (webVRController.hand === "left") {
  71480. this._leftControllerReady = true;
  71481. if (this._teleportationRequested && !this._teleportationEnabledOnLeftController) {
  71482. this._enableTeleportationOnController(webVRController);
  71483. }
  71484. }
  71485. if (webVRController.hand === "right") {
  71486. this._rightControllerReady = true;
  71487. if (this._teleportationRequested && !this._teleportationEnabledOnRightController) {
  71488. this._enableTeleportationOnController(webVRController);
  71489. }
  71490. }
  71491. if (this.onControllerMeshLoaded) {
  71492. this.onControllerMeshLoaded(webVRController);
  71493. }
  71494. };
  71495. VRExperienceHelper.prototype._onFullscreenChange = function () {
  71496. if (document.fullscreen !== undefined) {
  71497. this._fullscreenVRpresenting = document.fullscreen;
  71498. }
  71499. else if (document.mozFullScreen !== undefined) {
  71500. this._fullscreenVRpresenting = document.mozFullScreen;
  71501. }
  71502. else if (document.webkitIsFullScreen !== undefined) {
  71503. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  71504. }
  71505. else if (document.msIsFullScreen !== undefined) {
  71506. this._fullscreenVRpresenting = document.msIsFullScreen;
  71507. }
  71508. if (!this._fullscreenVRpresenting && this._canvas) {
  71509. this.exitVR();
  71510. if (!this._useCustomVRButton) {
  71511. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71512. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71513. }
  71514. }
  71515. };
  71516. VRExperienceHelper.prototype.isInVRMode = function () {
  71517. return this._webVRpresenting || this._fullscreenVRpresenting;
  71518. };
  71519. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  71520. var vrDisplay = this._scene.getEngine().getVRDevice();
  71521. if (vrDisplay) {
  71522. var wasPresenting = this._webVRpresenting;
  71523. // A VR display is connected
  71524. this._webVRpresenting = vrDisplay.isPresenting;
  71525. if (wasPresenting && !this._webVRpresenting)
  71526. this.exitVR();
  71527. }
  71528. else {
  71529. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  71530. }
  71531. this.updateButtonVisibility();
  71532. };
  71533. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  71534. this._webVRsupported = eventArgs.vrSupported;
  71535. this._webVRready = !!eventArgs.vrDisplay;
  71536. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  71537. this.updateButtonVisibility();
  71538. };
  71539. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  71540. if (!this._btnVR) {
  71541. return;
  71542. }
  71543. this._btnVR.className = "babylonVRicon";
  71544. if (this.isInVRMode()) {
  71545. this._btnVR.className += " vrdisplaypresenting";
  71546. }
  71547. else {
  71548. if (this._webVRready)
  71549. this._btnVR.className += " vrdisplayready";
  71550. if (this._webVRsupported)
  71551. this._btnVR.className += " vrdisplaysupported";
  71552. if (this._webVRrequesting)
  71553. this._btnVR.className += " vrdisplayrequesting";
  71554. }
  71555. };
  71556. /**
  71557. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  71558. * Otherwise, will use the fullscreen API.
  71559. */
  71560. VRExperienceHelper.prototype.enterVR = function () {
  71561. if (this._scene.activeCamera) {
  71562. this._position = this._scene.activeCamera.position.clone();
  71563. }
  71564. if (this.onEnteringVR) {
  71565. this.onEnteringVR();
  71566. }
  71567. if (this._webVRrequesting)
  71568. return;
  71569. // If WebVR is supported and a headset is connected
  71570. if (this._webVRready) {
  71571. if (!this._webVRpresenting) {
  71572. this._webVRCamera.position = this._position;
  71573. this._scene.activeCamera = this._webVRCamera;
  71574. }
  71575. }
  71576. else {
  71577. this._vrDeviceOrientationCamera.position = this._position;
  71578. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  71579. this._scene.getEngine().switchFullscreen(true);
  71580. this.updateButtonVisibility();
  71581. }
  71582. if (this._scene.activeCamera && this._canvas) {
  71583. this._scene.activeCamera.attachControl(this._canvas);
  71584. }
  71585. };
  71586. /**
  71587. * Attempt to exit VR, or fullscreen.
  71588. */
  71589. VRExperienceHelper.prototype.exitVR = function () {
  71590. if (this.onExitingVR) {
  71591. this.onExitingVR();
  71592. }
  71593. if (this._webVRpresenting) {
  71594. this._scene.getEngine().disableVR();
  71595. }
  71596. if (this._scene.activeCamera) {
  71597. this._position = this._scene.activeCamera.position.clone();
  71598. }
  71599. this._deviceOrientationCamera.position = this._position;
  71600. this._scene.activeCamera = this._deviceOrientationCamera;
  71601. if (this._canvas) {
  71602. this._scene.activeCamera.attachControl(this._canvas);
  71603. }
  71604. this.updateButtonVisibility();
  71605. };
  71606. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  71607. get: function () {
  71608. return this._position;
  71609. },
  71610. set: function (value) {
  71611. this._position = value;
  71612. if (this._scene.activeCamera) {
  71613. this._scene.activeCamera.position = value;
  71614. }
  71615. },
  71616. enumerable: true,
  71617. configurable: true
  71618. });
  71619. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  71620. var _this = this;
  71621. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  71622. this._teleportationRequested = true;
  71623. if (vrTeleportationOptions) {
  71624. if (vrTeleportationOptions.floorMeshName) {
  71625. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  71626. }
  71627. }
  71628. if (this._leftControllerReady && this._webVRCamera.leftController) {
  71629. this._enableTeleportationOnController(this._webVRCamera.leftController);
  71630. }
  71631. if (this._rightControllerReady && this._webVRCamera.rightController) {
  71632. this._enableTeleportationOnController(this._webVRCamera.rightController);
  71633. }
  71634. this._scene.gamepadManager.onGamepadConnectedObservable.add(function (pad) { return _this._onNewGamepadConnected(pad); });
  71635. // Creates an image processing post process for the vignette not relying
  71636. // on the main scene configuration for image processing to reduce setup and spaces
  71637. // (gamma/linear) conflicts.
  71638. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  71639. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  71640. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  71641. // Force recompilation of the postprocess to be ready before hand and not block the animation.
  71642. // Simply touching the property forces recompilation of the effect.
  71643. this._postProcessMove.imageProcessingConfiguration.vignetteEnabled = true;
  71644. // Go back to default (both variants would be compiled).
  71645. this._postProcessMove.imageProcessingConfiguration.vignetteEnabled = false;
  71646. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  71647. this._createGazeTracker();
  71648. this._createTeleportationCircles();
  71649. // To be optionnaly changed by user to define his custom selection logic
  71650. this.meshSelectionPredicate = function (mesh) {
  71651. return true;
  71652. };
  71653. this._meshSelectionPredicate = function (mesh) {
  71654. if (mesh.name.indexOf(_this._floorMeshName) !== -1 || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  71655. && mesh.name.indexOf("teleportationCircle") === -1
  71656. && mesh.name.indexOf("torusTeleportation") === -1
  71657. && mesh.name.indexOf("laserPointer") === -1)) {
  71658. return true;
  71659. }
  71660. return false;
  71661. };
  71662. this._scene.registerBeforeRender(function () {
  71663. _this._castRayAndSelectObject();
  71664. });
  71665. };
  71666. VRExperienceHelper.prototype._onNewGamepadConnected = function (gamepad) {
  71667. var _this = this;
  71668. if (gamepad.leftStick && gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71669. gamepad.onleftstickchanged(function (stickValues) {
  71670. // Listening to classic/xbox gamepad only if no VR controller is active
  71671. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  71672. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  71673. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  71674. if (!_this._teleportationRequestInitiated) {
  71675. if (stickValues.y < -_this._padSensibilityUp) {
  71676. _this._teleportationRequestInitiated = true;
  71677. }
  71678. }
  71679. else {
  71680. if (stickValues.y > -_this._padSensibilityDown) {
  71681. if (_this._teleportationAllowed) {
  71682. _this._teleportCamera();
  71683. }
  71684. _this._teleportationRequestInitiated = false;
  71685. }
  71686. }
  71687. }
  71688. });
  71689. }
  71690. if (gamepad.rightStick) {
  71691. gamepad.onrightstickchanged(function (stickValues) {
  71692. if (!_this._rotationLeftAsked) {
  71693. if (stickValues.x < -_this._padSensibilityUp) {
  71694. _this._rotationLeftAsked = true;
  71695. if (_this._rotationAllowed) {
  71696. _this._rotateCamera(false);
  71697. }
  71698. }
  71699. }
  71700. else {
  71701. if (stickValues.x > -_this._padSensibilityDown) {
  71702. _this._rotationLeftAsked = false;
  71703. }
  71704. }
  71705. if (!_this._rotationRightAsked) {
  71706. if (stickValues.x > _this._padSensibilityUp) {
  71707. _this._rotationRightAsked = true;
  71708. if (_this._rotationAllowed) {
  71709. _this._rotateCamera(true);
  71710. }
  71711. }
  71712. }
  71713. else {
  71714. if (stickValues.x < _this._padSensibilityDown) {
  71715. _this._rotationRightAsked = false;
  71716. }
  71717. }
  71718. });
  71719. }
  71720. };
  71721. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  71722. var _this = this;
  71723. var controllerMesh = webVRController.mesh;
  71724. if (controllerMesh) {
  71725. var childMeshes = controllerMesh.getChildMeshes();
  71726. for (var i = 0; i < childMeshes.length; i++) {
  71727. if (childMeshes[i].name === "POINTING_POSE") {
  71728. controllerMesh = childMeshes[i];
  71729. break;
  71730. }
  71731. }
  71732. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  71733. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  71734. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  71735. laserPointerMaterial.alpha = 0.6;
  71736. laserPointer.material = laserPointerMaterial;
  71737. laserPointer.rotation.x = Math.PI / 2;
  71738. laserPointer.parent = controllerMesh;
  71739. laserPointer.position.z = -0.5;
  71740. laserPointer.position.y = 0;
  71741. laserPointer.isVisible = false;
  71742. if (webVRController.hand === "left") {
  71743. this._leftLaserPointer = laserPointer;
  71744. }
  71745. else {
  71746. this._rightLaserPointer = laserPointer;
  71747. }
  71748. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  71749. // Enabling / disabling laserPointer
  71750. if (stateObject.value === 1) {
  71751. laserPointer.isVisible = !laserPointer.isVisible;
  71752. // Laser pointer can only be active on left or right, not both at the same time
  71753. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  71754. _this._rightLaserPointer.isVisible = false;
  71755. }
  71756. else if (_this._leftLaserPointer) {
  71757. _this._leftLaserPointer.isVisible = false;
  71758. }
  71759. }
  71760. });
  71761. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  71762. if (!_this._teleportationRequestInitiated) {
  71763. if (stateObject.y < -_this._padSensibilityUp) {
  71764. // If laser pointer wasn't enabled yet
  71765. if (webVRController.hand === "left" && _this._leftLaserPointer) {
  71766. _this._leftLaserPointer.isVisible = true;
  71767. if (_this._rightLaserPointer) {
  71768. _this._rightLaserPointer.isVisible = false;
  71769. }
  71770. }
  71771. else if (_this._rightLaserPointer) {
  71772. _this._rightLaserPointer.isVisible = true;
  71773. if (_this._leftLaserPointer) {
  71774. _this._leftLaserPointer.isVisible = false;
  71775. }
  71776. }
  71777. _this._teleportationRequestInitiated = true;
  71778. }
  71779. }
  71780. else {
  71781. // Listening to the proper controller values changes to confirm teleportation
  71782. if ((webVRController.hand === "left" && _this._leftLaserPointer && _this._leftLaserPointer.isVisible)
  71783. || (webVRController.hand === "right" && _this._rightLaserPointer && _this._rightLaserPointer.isVisible)) {
  71784. if (stateObject.y > -_this._padSensibilityDown) {
  71785. if (_this._teleportationAllowed) {
  71786. _this._teleportationAllowed = false;
  71787. _this._teleportCamera();
  71788. }
  71789. _this._teleportationRequestInitiated = false;
  71790. }
  71791. }
  71792. }
  71793. if (!_this._rotationLeftAsked) {
  71794. if (stateObject.x < -_this._padSensibilityUp) {
  71795. _this._rotationLeftAsked = true;
  71796. if (_this._rotationAllowed) {
  71797. _this._rotateCamera(false);
  71798. }
  71799. }
  71800. }
  71801. else {
  71802. if (stateObject.x > -_this._padSensibilityDown) {
  71803. _this._rotationLeftAsked = false;
  71804. }
  71805. }
  71806. if (!_this._rotationRightAsked) {
  71807. if (stateObject.x > _this._padSensibilityUp) {
  71808. _this._rotationRightAsked = true;
  71809. if (_this._rotationAllowed) {
  71810. _this._rotateCamera(true);
  71811. }
  71812. }
  71813. }
  71814. else {
  71815. if (stateObject.x < _this._padSensibilityDown) {
  71816. _this._rotationRightAsked = false;
  71817. }
  71818. }
  71819. });
  71820. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  71821. if (!_this._pointerDownOnMeshAsked) {
  71822. if (stateObject.value > _this._padSensibilityUp) {
  71823. _this._pointerDownOnMeshAsked = true;
  71824. if (_this._currentMeshSelected && _this._currentHit) {
  71825. _this._scene.simulatePointerDown(_this._currentHit);
  71826. }
  71827. }
  71828. }
  71829. else if (stateObject.value < _this._padSensibilityDown) {
  71830. if (_this._currentMeshSelected && _this._currentHit) {
  71831. _this._scene.simulatePointerUp(_this._currentHit);
  71832. }
  71833. _this._pointerDownOnMeshAsked = false;
  71834. }
  71835. });
  71836. }
  71837. };
  71838. // Gaze support used to point to teleport or to interact with an object
  71839. VRExperienceHelper.prototype._createGazeTracker = function () {
  71840. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  71841. this._gazeTracker.bakeCurrentTransformIntoVertices();
  71842. this._gazeTracker.isPickable = false;
  71843. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  71844. targetMat.specularColor = BABYLON.Color3.Black();
  71845. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  71846. targetMat.backFaceCulling = false;
  71847. this._gazeTracker.material = targetMat;
  71848. };
  71849. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  71850. this._teleportationCircle = BABYLON.Mesh.CreateGround("teleportationCircle", 2, 2, 2, this._scene);
  71851. this._teleportationCircle.isPickable = false;
  71852. var length = 512;
  71853. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  71854. dynamicTexture.hasAlpha = true;
  71855. var context = dynamicTexture.getContext();
  71856. var centerX = length / 2;
  71857. var centerY = length / 2;
  71858. var radius = 200;
  71859. context.beginPath();
  71860. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  71861. context.fillStyle = this._teleportationFillColor;
  71862. context.fill();
  71863. context.lineWidth = 10;
  71864. context.strokeStyle = this._teleportationBorderColor;
  71865. context.stroke();
  71866. context.closePath();
  71867. dynamicTexture.update();
  71868. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  71869. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  71870. this._teleportationCircle.material = teleportationCircleMaterial;
  71871. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  71872. torus.isPickable = false;
  71873. torus.parent = this._teleportationCircle;
  71874. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  71875. var keys = [];
  71876. keys.push({
  71877. frame: 0,
  71878. value: 0
  71879. });
  71880. keys.push({
  71881. frame: 30,
  71882. value: 0.4
  71883. });
  71884. keys.push({
  71885. frame: 60,
  71886. value: 0
  71887. });
  71888. animationInnerCircle.setKeys(keys);
  71889. var easingFunction = new BABYLON.SineEase();
  71890. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71891. animationInnerCircle.setEasingFunction(easingFunction);
  71892. torus.animations = [];
  71893. torus.animations.push(animationInnerCircle);
  71894. this._scene.beginAnimation(torus, 0, 60, true);
  71895. this._hideTeleportationCircle();
  71896. };
  71897. VRExperienceHelper.prototype._displayTeleportationCircle = function () {
  71898. this._teleportationCircle.isVisible = true;
  71899. this._teleportationCircle.getChildren()[0].isVisible = true;
  71900. };
  71901. VRExperienceHelper.prototype._hideTeleportationCircle = function () {
  71902. this._teleportationCircle.isVisible = false;
  71903. this._teleportationCircle.getChildren()[0].isVisible = false;
  71904. };
  71905. VRExperienceHelper.prototype._rotateCamera = function (right) {
  71906. var _this = this;
  71907. if (right) {
  71908. this._rotationAngle++;
  71909. }
  71910. else {
  71911. this._rotationAngle--;
  71912. }
  71913. this.currentVRCamera.animations = [];
  71914. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  71915. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71916. var animationRotationKeys = [];
  71917. animationRotationKeys.push({
  71918. frame: 0,
  71919. value: this.currentVRCamera.rotationQuaternion
  71920. });
  71921. animationRotationKeys.push({
  71922. frame: 6,
  71923. value: target
  71924. });
  71925. animationRotation.setKeys(animationRotationKeys);
  71926. var easingFunction = new BABYLON.CircleEase();
  71927. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71928. animationRotation.setEasingFunction(easingFunction);
  71929. this.currentVRCamera.animations.push(animationRotation);
  71930. this._postProcessMove.animations = [];
  71931. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71932. var vignetteWeightKeys = [];
  71933. vignetteWeightKeys.push({
  71934. frame: 0,
  71935. value: 0
  71936. });
  71937. vignetteWeightKeys.push({
  71938. frame: 3,
  71939. value: 4
  71940. });
  71941. vignetteWeightKeys.push({
  71942. frame: 6,
  71943. value: 0
  71944. });
  71945. animationPP.setKeys(vignetteWeightKeys);
  71946. animationPP.setEasingFunction(easingFunction);
  71947. this._postProcessMove.animations.push(animationPP);
  71948. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71949. var vignetteStretchKeys = [];
  71950. vignetteStretchKeys.push({
  71951. frame: 0,
  71952. value: 0
  71953. });
  71954. vignetteStretchKeys.push({
  71955. frame: 3,
  71956. value: 10
  71957. });
  71958. vignetteStretchKeys.push({
  71959. frame: 6,
  71960. value: 0
  71961. });
  71962. animationPP2.setKeys(vignetteStretchKeys);
  71963. animationPP2.setEasingFunction(easingFunction);
  71964. this._postProcessMove.animations.push(animationPP2);
  71965. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  71966. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  71967. this._postProcessMove.imageProcessingConfiguration.vignetteEnabled = true;
  71968. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  71969. _this._postProcessMove.imageProcessingConfiguration.vignetteEnabled = false;
  71970. });
  71971. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  71972. };
  71973. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  71974. if (hit.pickedPoint) {
  71975. this._teleportationAllowed = true;
  71976. if (this._teleportationRequestInitiated) {
  71977. this._displayTeleportationCircle();
  71978. }
  71979. else {
  71980. this._hideTeleportationCircle();
  71981. }
  71982. this._haloCenter.copyFrom(hit.pickedPoint);
  71983. this._teleportationCircle.position.copyFrom(hit.pickedPoint);
  71984. var pickNormal = hit.getNormal();
  71985. if (pickNormal) {
  71986. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  71987. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  71988. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationCircle.rotation);
  71989. }
  71990. this._teleportationCircle.position.y += 0.1;
  71991. }
  71992. };
  71993. VRExperienceHelper.prototype._teleportCamera = function () {
  71994. var _this = this;
  71995. this.currentVRCamera.animations = [];
  71996. var animationCameraTeleportationX = new BABYLON.Animation("animationCameraTeleportationX", "position.x", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71997. var animationCameraTeleportationXKeys = [];
  71998. animationCameraTeleportationXKeys.push({
  71999. frame: 0,
  72000. value: this.currentVRCamera.position.x
  72001. });
  72002. animationCameraTeleportationXKeys.push({
  72003. frame: 11,
  72004. value: this._haloCenter.x
  72005. });
  72006. var easingFunction = new BABYLON.CircleEase();
  72007. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72008. animationCameraTeleportationX.setKeys(animationCameraTeleportationXKeys);
  72009. animationCameraTeleportationX.setEasingFunction(easingFunction);
  72010. this.currentVRCamera.animations.push(animationCameraTeleportationX);
  72011. var animationCameraTeleportationY = new BABYLON.Animation("animationCameraTeleportationY", "position.y", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72012. var animationCameraTeleportationYKeys = [];
  72013. animationCameraTeleportationYKeys.push({
  72014. frame: 0,
  72015. value: this.currentVRCamera.position.y
  72016. });
  72017. animationCameraTeleportationYKeys.push({
  72018. frame: 11,
  72019. value: this._haloCenter.y + 1.7
  72020. });
  72021. animationCameraTeleportationY.setKeys(animationCameraTeleportationYKeys);
  72022. animationCameraTeleportationY.setEasingFunction(easingFunction);
  72023. this.currentVRCamera.animations.push(animationCameraTeleportationY);
  72024. var animationCameraTeleportationZ = new BABYLON.Animation("animationCameraTeleportationZ", "position.z", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72025. var animationCameraTeleportationZKeys = [];
  72026. animationCameraTeleportationZKeys.push({
  72027. frame: 0,
  72028. value: this.currentVRCamera.position.z
  72029. });
  72030. animationCameraTeleportationZKeys.push({
  72031. frame: 11,
  72032. value: this._haloCenter.z
  72033. });
  72034. animationCameraTeleportationZ.setKeys(animationCameraTeleportationZKeys);
  72035. animationCameraTeleportationZ.setEasingFunction(easingFunction);
  72036. this.currentVRCamera.animations.push(animationCameraTeleportationZ);
  72037. this._postProcessMove.animations = [];
  72038. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72039. var vignetteWeightKeys = [];
  72040. vignetteWeightKeys.push({
  72041. frame: 0,
  72042. value: 0
  72043. });
  72044. vignetteWeightKeys.push({
  72045. frame: 5,
  72046. value: 8
  72047. });
  72048. vignetteWeightKeys.push({
  72049. frame: 11,
  72050. value: 0
  72051. });
  72052. animationPP.setKeys(vignetteWeightKeys);
  72053. this._postProcessMove.animations.push(animationPP);
  72054. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72055. var vignetteStretchKeys = [];
  72056. vignetteStretchKeys.push({
  72057. frame: 0,
  72058. value: 0
  72059. });
  72060. vignetteStretchKeys.push({
  72061. frame: 5,
  72062. value: 10
  72063. });
  72064. vignetteStretchKeys.push({
  72065. frame: 11,
  72066. value: 0
  72067. });
  72068. animationPP2.setKeys(vignetteStretchKeys);
  72069. this._postProcessMove.animations.push(animationPP2);
  72070. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 8;
  72071. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 10;
  72072. this._postProcessMove.imageProcessingConfiguration.vignetteEnabled = true;
  72073. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  72074. _this._postProcessMove.imageProcessingConfiguration.vignetteEnabled = false;
  72075. });
  72076. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  72077. };
  72078. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  72079. var ray;
  72080. if ((!this.currentVRCamera.rightController && !this.currentVRCamera.leftController) ||
  72081. (this._leftLaserPointer && !this._leftLaserPointer.isVisible && !this._rightLaserPointer) ||
  72082. (this._rightLaserPointer && !this._rightLaserPointer.isVisible && !this._leftLaserPointer) ||
  72083. (this._rightLaserPointer && this._leftLaserPointer && !this._rightLaserPointer.isVisible && !this._leftLaserPointer.isVisible)) {
  72084. ray = this.currentVRCamera.getForwardRay();
  72085. }
  72086. else {
  72087. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  72088. ray = this.currentVRCamera.leftController.getForwardRay();
  72089. }
  72090. else {
  72091. ray = this.currentVRCamera.rightController.getForwardRay();
  72092. }
  72093. }
  72094. var hit = this._scene.pickWithRay(ray, this._meshSelectionPredicate);
  72095. // Moving the gazeTracker on the mesh face targetted
  72096. if (hit && hit.pickedPoint) {
  72097. var multiplier = 1;
  72098. if (this._isActionableMesh) {
  72099. multiplier = 3;
  72100. }
  72101. this._gazeTracker.scaling.x = hit.distance * multiplier;
  72102. this._gazeTracker.scaling.y = hit.distance * multiplier;
  72103. this._gazeTracker.scaling.z = hit.distance * multiplier;
  72104. var pickNormal = hit.getNormal();
  72105. // To avoid z-fighting
  72106. var deltaFighting = 0.002;
  72107. if (pickNormal) {
  72108. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72109. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72110. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  72111. }
  72112. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  72113. if (this._gazeTracker.position.x < 0) {
  72114. this._gazeTracker.position.x += deltaFighting;
  72115. }
  72116. else {
  72117. this._gazeTracker.position.x -= deltaFighting;
  72118. }
  72119. if (this._gazeTracker.position.y < 0) {
  72120. this._gazeTracker.position.y += deltaFighting;
  72121. }
  72122. else {
  72123. this._gazeTracker.position.y -= deltaFighting;
  72124. }
  72125. if (this._gazeTracker.position.z < 0) {
  72126. this._gazeTracker.position.z += deltaFighting;
  72127. }
  72128. else {
  72129. this._gazeTracker.position.z -= deltaFighting;
  72130. }
  72131. // Changing the size of the laser pointer based on the distance from the targetted point
  72132. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  72133. this._rightLaserPointer.scaling.y = hit.distance;
  72134. this._rightLaserPointer.position.z = -hit.distance / 2;
  72135. }
  72136. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  72137. this._leftLaserPointer.scaling.y = hit.distance;
  72138. this._leftLaserPointer.position.z = -hit.distance / 2;
  72139. }
  72140. }
  72141. if (hit && hit.pickedMesh) {
  72142. this._currentHit = hit;
  72143. // The object selected is the floor, we're in a teleportation scenario
  72144. if (hit.pickedMesh.name.indexOf(this._floorMeshName) !== -1 && hit.pickedPoint) {
  72145. // Moving the teleportation area to this targetted point
  72146. this._moveTeleportationSelectorTo(hit);
  72147. return;
  72148. }
  72149. // If not, we're in a selection scenario
  72150. this._hideTeleportationCircle();
  72151. this._teleportationAllowed = false;
  72152. if (hit.pickedMesh !== this._currentMeshSelected) {
  72153. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  72154. this._currentMeshSelected = hit.pickedMesh;
  72155. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  72156. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  72157. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  72158. this._isActionableMesh = true;
  72159. }
  72160. else {
  72161. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72162. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72163. this._isActionableMesh = false;
  72164. }
  72165. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  72166. }
  72167. else {
  72168. this._currentMeshSelected = null;
  72169. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72170. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72171. }
  72172. }
  72173. }
  72174. else {
  72175. this._currentHit = null;
  72176. this._currentMeshSelected = null;
  72177. this._teleportationAllowed = false;
  72178. this._hideTeleportationCircle();
  72179. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72180. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72181. }
  72182. };
  72183. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  72184. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  72185. this._leftLaserPointer.material.emissiveColor = color;
  72186. }
  72187. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  72188. this._rightLaserPointer.material.emissiveColor = color;
  72189. }
  72190. };
  72191. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  72192. if (this._gazeTracker.material) {
  72193. this._gazeTracker.material.emissiveColor = color;
  72194. }
  72195. };
  72196. VRExperienceHelper.prototype.dispose = function () {
  72197. if (this.isInVRMode()) {
  72198. this.exitVR();
  72199. }
  72200. this._deviceOrientationCamera.dispose();
  72201. if (this._passProcessMove) {
  72202. this._passProcessMove.dispose();
  72203. }
  72204. if (this._postProcessMove) {
  72205. this._postProcessMove.dispose();
  72206. }
  72207. if (this._webVRCamera) {
  72208. this._webVRCamera.dispose();
  72209. }
  72210. if (this._vrDeviceOrientationCamera) {
  72211. this._vrDeviceOrientationCamera.dispose();
  72212. }
  72213. if (!this._useCustomVRButton) {
  72214. document.body.removeChild(this._btnVR);
  72215. }
  72216. document.removeEventListener("keydown", this._onKeyDown);
  72217. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72218. };
  72219. VRExperienceHelper.prototype.getClassName = function () {
  72220. return "VRExperienceHelper";
  72221. };
  72222. return VRExperienceHelper;
  72223. }());
  72224. BABYLON.VRExperienceHelper = VRExperienceHelper;
  72225. })(BABYLON || (BABYLON = {}));
  72226. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  72227. // Mainly based on these 2 articles :
  72228. // 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
  72229. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  72230. var BABYLON;
  72231. (function (BABYLON) {
  72232. var JoystickAxis;
  72233. (function (JoystickAxis) {
  72234. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  72235. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  72236. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  72237. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  72238. var VirtualJoystick = /** @class */ (function () {
  72239. function VirtualJoystick(leftJoystick) {
  72240. var _this = this;
  72241. if (leftJoystick) {
  72242. this._leftJoystick = true;
  72243. }
  72244. else {
  72245. this._leftJoystick = false;
  72246. }
  72247. VirtualJoystick._globalJoystickIndex++;
  72248. // By default left & right arrow keys are moving the X
  72249. // and up & down keys are moving the Y
  72250. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  72251. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  72252. this.reverseLeftRight = false;
  72253. this.reverseUpDown = false;
  72254. // collections of pointers
  72255. this._touches = new BABYLON.StringDictionary();
  72256. this.deltaPosition = BABYLON.Vector3.Zero();
  72257. this._joystickSensibility = 25;
  72258. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  72259. this._onResize = function (evt) {
  72260. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  72261. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  72262. if (VirtualJoystick.vjCanvas) {
  72263. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  72264. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  72265. }
  72266. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  72267. };
  72268. // injecting a canvas element on top of the canvas 3D game
  72269. if (!VirtualJoystick.vjCanvas) {
  72270. window.addEventListener("resize", this._onResize, false);
  72271. VirtualJoystick.vjCanvas = document.createElement("canvas");
  72272. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  72273. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  72274. VirtualJoystick.vjCanvas.width = window.innerWidth;
  72275. VirtualJoystick.vjCanvas.height = window.innerHeight;
  72276. VirtualJoystick.vjCanvas.style.width = "100%";
  72277. VirtualJoystick.vjCanvas.style.height = "100%";
  72278. VirtualJoystick.vjCanvas.style.position = "absolute";
  72279. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  72280. VirtualJoystick.vjCanvas.style.top = "0px";
  72281. VirtualJoystick.vjCanvas.style.left = "0px";
  72282. VirtualJoystick.vjCanvas.style.zIndex = "5";
  72283. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  72284. // Support for jQuery PEP polyfill
  72285. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  72286. var context = VirtualJoystick.vjCanvas.getContext('2d');
  72287. if (!context) {
  72288. throw new Error("Unable to create canvas for virtual joystick");
  72289. }
  72290. VirtualJoystick.vjCanvasContext = context;
  72291. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  72292. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  72293. document.body.appendChild(VirtualJoystick.vjCanvas);
  72294. }
  72295. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  72296. this.pressed = false;
  72297. // default joystick color
  72298. this._joystickColor = "cyan";
  72299. this._joystickPointerID = -1;
  72300. // current joystick position
  72301. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  72302. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  72303. // origin joystick position
  72304. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  72305. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  72306. this._onPointerDownHandlerRef = function (evt) {
  72307. _this._onPointerDown(evt);
  72308. };
  72309. this._onPointerMoveHandlerRef = function (evt) {
  72310. _this._onPointerMove(evt);
  72311. };
  72312. this._onPointerUpHandlerRef = function (evt) {
  72313. _this._onPointerUp(evt);
  72314. };
  72315. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  72316. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  72317. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  72318. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  72319. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  72320. evt.preventDefault(); // Disables system menu
  72321. }, false);
  72322. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  72323. }
  72324. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  72325. this._joystickSensibility = newJoystickSensibility;
  72326. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  72327. };
  72328. VirtualJoystick.prototype._onPointerDown = function (e) {
  72329. var positionOnScreenCondition;
  72330. e.preventDefault();
  72331. if (this._leftJoystick === true) {
  72332. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  72333. }
  72334. else {
  72335. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  72336. }
  72337. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  72338. // First contact will be dedicated to the virtual joystick
  72339. this._joystickPointerID = e.pointerId;
  72340. this._joystickPointerStartPos.x = e.clientX;
  72341. this._joystickPointerStartPos.y = e.clientY;
  72342. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  72343. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  72344. this._deltaJoystickVector.x = 0;
  72345. this._deltaJoystickVector.y = 0;
  72346. this.pressed = true;
  72347. this._touches.add(e.pointerId.toString(), e);
  72348. }
  72349. else {
  72350. // You can only trigger the action buttons with a joystick declared
  72351. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  72352. this._action();
  72353. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  72354. }
  72355. }
  72356. };
  72357. VirtualJoystick.prototype._onPointerMove = function (e) {
  72358. // If the current pointer is the one associated to the joystick (first touch contact)
  72359. if (this._joystickPointerID == e.pointerId) {
  72360. this._joystickPointerPos.x = e.clientX;
  72361. this._joystickPointerPos.y = e.clientY;
  72362. this._deltaJoystickVector = this._joystickPointerPos.clone();
  72363. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  72364. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  72365. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  72366. switch (this._axisTargetedByLeftAndRight) {
  72367. case JoystickAxis.X:
  72368. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  72369. break;
  72370. case JoystickAxis.Y:
  72371. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  72372. break;
  72373. case JoystickAxis.Z:
  72374. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  72375. break;
  72376. }
  72377. var directionUpDown = this.reverseUpDown ? 1 : -1;
  72378. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  72379. switch (this._axisTargetedByUpAndDown) {
  72380. case JoystickAxis.X:
  72381. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  72382. break;
  72383. case JoystickAxis.Y:
  72384. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  72385. break;
  72386. case JoystickAxis.Z:
  72387. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  72388. break;
  72389. }
  72390. }
  72391. else {
  72392. var data = this._touches.get(e.pointerId.toString());
  72393. if (data) {
  72394. data.x = e.clientX;
  72395. data.y = e.clientY;
  72396. }
  72397. }
  72398. };
  72399. VirtualJoystick.prototype._onPointerUp = function (e) {
  72400. if (this._joystickPointerID == e.pointerId) {
  72401. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  72402. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  72403. this._joystickPointerID = -1;
  72404. this.pressed = false;
  72405. }
  72406. else {
  72407. var touch = this._touches.get(e.pointerId.toString());
  72408. if (touch) {
  72409. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  72410. }
  72411. }
  72412. this._deltaJoystickVector.x = 0;
  72413. this._deltaJoystickVector.y = 0;
  72414. this._touches.remove(e.pointerId.toString());
  72415. };
  72416. /**
  72417. * Change the color of the virtual joystick
  72418. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  72419. */
  72420. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  72421. this._joystickColor = newColor;
  72422. };
  72423. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  72424. this._action = action;
  72425. };
  72426. // Define which axis you'd like to control for left & right
  72427. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  72428. switch (axis) {
  72429. case JoystickAxis.X:
  72430. case JoystickAxis.Y:
  72431. case JoystickAxis.Z:
  72432. this._axisTargetedByLeftAndRight = axis;
  72433. break;
  72434. default:
  72435. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  72436. break;
  72437. }
  72438. };
  72439. // Define which axis you'd like to control for up & down
  72440. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  72441. switch (axis) {
  72442. case JoystickAxis.X:
  72443. case JoystickAxis.Y:
  72444. case JoystickAxis.Z:
  72445. this._axisTargetedByUpAndDown = axis;
  72446. break;
  72447. default:
  72448. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  72449. break;
  72450. }
  72451. };
  72452. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  72453. var _this = this;
  72454. if (this.pressed) {
  72455. this._touches.forEach(function (key, touch) {
  72456. if (touch.pointerId === _this._joystickPointerID) {
  72457. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  72458. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  72459. VirtualJoystick.vjCanvasContext.beginPath();
  72460. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  72461. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72462. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  72463. VirtualJoystick.vjCanvasContext.stroke();
  72464. VirtualJoystick.vjCanvasContext.closePath();
  72465. VirtualJoystick.vjCanvasContext.beginPath();
  72466. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72467. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  72468. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  72469. VirtualJoystick.vjCanvasContext.stroke();
  72470. VirtualJoystick.vjCanvasContext.closePath();
  72471. VirtualJoystick.vjCanvasContext.beginPath();
  72472. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72473. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  72474. VirtualJoystick.vjCanvasContext.stroke();
  72475. VirtualJoystick.vjCanvasContext.closePath();
  72476. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  72477. }
  72478. else {
  72479. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  72480. VirtualJoystick.vjCanvasContext.beginPath();
  72481. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  72482. VirtualJoystick.vjCanvasContext.beginPath();
  72483. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  72484. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  72485. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  72486. VirtualJoystick.vjCanvasContext.stroke();
  72487. VirtualJoystick.vjCanvasContext.closePath();
  72488. touch.prevX = touch.x;
  72489. touch.prevY = touch.y;
  72490. }
  72491. ;
  72492. });
  72493. }
  72494. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  72495. };
  72496. VirtualJoystick.prototype.releaseCanvas = function () {
  72497. if (VirtualJoystick.vjCanvas) {
  72498. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  72499. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  72500. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  72501. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  72502. window.removeEventListener("resize", this._onResize);
  72503. document.body.removeChild(VirtualJoystick.vjCanvas);
  72504. VirtualJoystick.vjCanvas = null;
  72505. }
  72506. };
  72507. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  72508. VirtualJoystick._globalJoystickIndex = 0;
  72509. return VirtualJoystick;
  72510. }());
  72511. BABYLON.VirtualJoystick = VirtualJoystick;
  72512. })(BABYLON || (BABYLON = {}));
  72513. //# sourceMappingURL=babylon.virtualJoystick.js.map
  72514. var BABYLON;
  72515. (function (BABYLON) {
  72516. // We're mainly based on the logic defined into the FreeCamera code
  72517. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  72518. __extends(VirtualJoysticksCamera, _super);
  72519. function VirtualJoysticksCamera(name, position, scene) {
  72520. var _this = _super.call(this, name, position, scene) || this;
  72521. _this.inputs.addVirtualJoystick();
  72522. return _this;
  72523. }
  72524. VirtualJoysticksCamera.prototype.getClassName = function () {
  72525. return "VirtualJoysticksCamera";
  72526. };
  72527. return VirtualJoysticksCamera;
  72528. }(BABYLON.FreeCamera));
  72529. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  72530. })(BABYLON || (BABYLON = {}));
  72531. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  72532. var BABYLON;
  72533. (function (BABYLON) {
  72534. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  72535. function FreeCameraVirtualJoystickInput() {
  72536. }
  72537. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  72538. return this._leftjoystick;
  72539. };
  72540. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  72541. return this._rightjoystick;
  72542. };
  72543. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  72544. if (this._leftjoystick) {
  72545. var camera = this.camera;
  72546. var speed = camera._computeLocalCameraSpeed() * 50;
  72547. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  72548. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  72549. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  72550. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  72551. if (!this._leftjoystick.pressed) {
  72552. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  72553. }
  72554. if (!this._rightjoystick.pressed) {
  72555. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  72556. }
  72557. }
  72558. };
  72559. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  72560. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  72561. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  72562. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  72563. this._leftjoystick.setJoystickSensibility(0.15);
  72564. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  72565. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  72566. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  72567. this._rightjoystick.reverseUpDown = true;
  72568. this._rightjoystick.setJoystickSensibility(0.05);
  72569. this._rightjoystick.setJoystickColor("yellow");
  72570. };
  72571. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  72572. this._leftjoystick.releaseCanvas();
  72573. this._rightjoystick.releaseCanvas();
  72574. };
  72575. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  72576. return "FreeCameraVirtualJoystickInput";
  72577. };
  72578. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  72579. return "virtualJoystick";
  72580. };
  72581. return FreeCameraVirtualJoystickInput;
  72582. }());
  72583. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  72584. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  72585. })(BABYLON || (BABYLON = {}));
  72586. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  72587. var BABYLON;
  72588. (function (BABYLON) {
  72589. var SimplificationSettings = /** @class */ (function () {
  72590. function SimplificationSettings(quality, distance, optimizeMesh) {
  72591. this.quality = quality;
  72592. this.distance = distance;
  72593. this.optimizeMesh = optimizeMesh;
  72594. }
  72595. return SimplificationSettings;
  72596. }());
  72597. BABYLON.SimplificationSettings = SimplificationSettings;
  72598. var SimplificationQueue = /** @class */ (function () {
  72599. function SimplificationQueue() {
  72600. this.running = false;
  72601. this._simplificationArray = [];
  72602. }
  72603. SimplificationQueue.prototype.addTask = function (task) {
  72604. this._simplificationArray.push(task);
  72605. };
  72606. SimplificationQueue.prototype.executeNext = function () {
  72607. var task = this._simplificationArray.pop();
  72608. if (task) {
  72609. this.running = true;
  72610. this.runSimplification(task);
  72611. }
  72612. else {
  72613. this.running = false;
  72614. }
  72615. };
  72616. SimplificationQueue.prototype.runSimplification = function (task) {
  72617. var _this = this;
  72618. if (task.parallelProcessing) {
  72619. //parallel simplifier
  72620. task.settings.forEach(function (setting) {
  72621. var simplifier = _this.getSimplifier(task);
  72622. simplifier.simplify(setting, function (newMesh) {
  72623. task.mesh.addLODLevel(setting.distance, newMesh);
  72624. newMesh.isVisible = true;
  72625. //check if it is the last
  72626. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  72627. //all done, run the success callback.
  72628. task.successCallback();
  72629. }
  72630. _this.executeNext();
  72631. });
  72632. });
  72633. }
  72634. else {
  72635. //single simplifier.
  72636. var simplifier = this.getSimplifier(task);
  72637. var runDecimation = function (setting, callback) {
  72638. simplifier.simplify(setting, function (newMesh) {
  72639. task.mesh.addLODLevel(setting.distance, newMesh);
  72640. newMesh.isVisible = true;
  72641. //run the next quality level
  72642. callback();
  72643. });
  72644. };
  72645. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  72646. runDecimation(task.settings[loop.index], function () {
  72647. loop.executeNext();
  72648. });
  72649. }, function () {
  72650. //execution ended, run the success callback.
  72651. if (task.successCallback) {
  72652. task.successCallback();
  72653. }
  72654. _this.executeNext();
  72655. });
  72656. }
  72657. };
  72658. SimplificationQueue.prototype.getSimplifier = function (task) {
  72659. switch (task.simplificationType) {
  72660. case SimplificationType.QUADRATIC:
  72661. default:
  72662. return new QuadraticErrorSimplification(task.mesh);
  72663. }
  72664. };
  72665. return SimplificationQueue;
  72666. }());
  72667. BABYLON.SimplificationQueue = SimplificationQueue;
  72668. /**
  72669. * The implemented types of simplification.
  72670. * At the moment only Quadratic Error Decimation is implemented.
  72671. */
  72672. var SimplificationType;
  72673. (function (SimplificationType) {
  72674. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  72675. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  72676. var DecimationTriangle = /** @class */ (function () {
  72677. function DecimationTriangle(vertices) {
  72678. this.vertices = vertices;
  72679. this.error = new Array(4);
  72680. this.deleted = false;
  72681. this.isDirty = false;
  72682. this.deletePending = false;
  72683. this.borderFactor = 0;
  72684. }
  72685. return DecimationTriangle;
  72686. }());
  72687. BABYLON.DecimationTriangle = DecimationTriangle;
  72688. var DecimationVertex = /** @class */ (function () {
  72689. function DecimationVertex(position, id) {
  72690. this.position = position;
  72691. this.id = id;
  72692. this.isBorder = true;
  72693. this.q = new QuadraticMatrix();
  72694. this.triangleCount = 0;
  72695. this.triangleStart = 0;
  72696. this.originalOffsets = [];
  72697. }
  72698. DecimationVertex.prototype.updatePosition = function (newPosition) {
  72699. this.position.copyFrom(newPosition);
  72700. };
  72701. return DecimationVertex;
  72702. }());
  72703. BABYLON.DecimationVertex = DecimationVertex;
  72704. var QuadraticMatrix = /** @class */ (function () {
  72705. function QuadraticMatrix(data) {
  72706. this.data = new Array(10);
  72707. for (var i = 0; i < 10; ++i) {
  72708. if (data && data[i]) {
  72709. this.data[i] = data[i];
  72710. }
  72711. else {
  72712. this.data[i] = 0;
  72713. }
  72714. }
  72715. }
  72716. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  72717. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  72718. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  72719. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  72720. return det;
  72721. };
  72722. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  72723. for (var i = 0; i < 10; ++i) {
  72724. this.data[i] += matrix.data[i];
  72725. }
  72726. };
  72727. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  72728. for (var i = 0; i < 10; ++i) {
  72729. this.data[i] += data[i];
  72730. }
  72731. };
  72732. QuadraticMatrix.prototype.add = function (matrix) {
  72733. var m = new QuadraticMatrix();
  72734. for (var i = 0; i < 10; ++i) {
  72735. m.data[i] = this.data[i] + matrix.data[i];
  72736. }
  72737. return m;
  72738. };
  72739. QuadraticMatrix.FromData = function (a, b, c, d) {
  72740. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  72741. };
  72742. //returning an array to avoid garbage collection
  72743. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  72744. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  72745. };
  72746. return QuadraticMatrix;
  72747. }());
  72748. BABYLON.QuadraticMatrix = QuadraticMatrix;
  72749. var Reference = /** @class */ (function () {
  72750. function Reference(vertexId, triangleId) {
  72751. this.vertexId = vertexId;
  72752. this.triangleId = triangleId;
  72753. }
  72754. return Reference;
  72755. }());
  72756. BABYLON.Reference = Reference;
  72757. /**
  72758. * An implementation of the Quadratic Error simplification algorithm.
  72759. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  72760. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  72761. * @author RaananW
  72762. */
  72763. var QuadraticErrorSimplification = /** @class */ (function () {
  72764. function QuadraticErrorSimplification(_mesh) {
  72765. this._mesh = _mesh;
  72766. this.syncIterations = 5000;
  72767. this.aggressiveness = 7;
  72768. this.decimationIterations = 100;
  72769. this.boundingBoxEpsilon = BABYLON.Epsilon;
  72770. }
  72771. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  72772. var _this = this;
  72773. this.initDecimatedMesh();
  72774. //iterating through the submeshes array, one after the other.
  72775. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  72776. _this.initWithMesh(loop.index, function () {
  72777. _this.runDecimation(settings, loop.index, function () {
  72778. loop.executeNext();
  72779. });
  72780. }, settings.optimizeMesh);
  72781. }, function () {
  72782. setTimeout(function () {
  72783. successCallback(_this._reconstructedMesh);
  72784. }, 0);
  72785. });
  72786. };
  72787. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  72788. var _this = this;
  72789. var targetCount = ~~(this.triangles.length * settings.quality);
  72790. var deletedTriangles = 0;
  72791. var triangleCount = this.triangles.length;
  72792. var iterationFunction = function (iteration, callback) {
  72793. setTimeout(function () {
  72794. if (iteration % 5 === 0) {
  72795. _this.updateMesh(iteration === 0);
  72796. }
  72797. for (var i = 0; i < _this.triangles.length; ++i) {
  72798. _this.triangles[i].isDirty = false;
  72799. }
  72800. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  72801. var trianglesIterator = function (i) {
  72802. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  72803. var t = _this.triangles[tIdx];
  72804. if (!t)
  72805. return;
  72806. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  72807. return;
  72808. }
  72809. for (var j = 0; j < 3; ++j) {
  72810. if (t.error[j] < threshold) {
  72811. var deleted0 = [];
  72812. var deleted1 = [];
  72813. var v0 = t.vertices[j];
  72814. var v1 = t.vertices[(j + 1) % 3];
  72815. if (v0.isBorder || v1.isBorder)
  72816. continue;
  72817. var p = BABYLON.Vector3.Zero();
  72818. var n = BABYLON.Vector3.Zero();
  72819. var uv = BABYLON.Vector2.Zero();
  72820. var color = new BABYLON.Color4(0, 0, 0, 1);
  72821. _this.calculateError(v0, v1, p, n, uv, color);
  72822. var delTr = new Array();
  72823. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  72824. continue;
  72825. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  72826. continue;
  72827. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  72828. continue;
  72829. var uniqueArray = new Array();
  72830. delTr.forEach(function (deletedT) {
  72831. if (uniqueArray.indexOf(deletedT) === -1) {
  72832. deletedT.deletePending = true;
  72833. uniqueArray.push(deletedT);
  72834. }
  72835. });
  72836. if (uniqueArray.length % 2 !== 0) {
  72837. continue;
  72838. }
  72839. v0.q = v1.q.add(v0.q);
  72840. v0.updatePosition(p);
  72841. var tStart = _this.references.length;
  72842. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  72843. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  72844. var tCount = _this.references.length - tStart;
  72845. if (tCount <= v0.triangleCount) {
  72846. if (tCount) {
  72847. for (var c = 0; c < tCount; c++) {
  72848. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  72849. }
  72850. }
  72851. }
  72852. else {
  72853. v0.triangleStart = tStart;
  72854. }
  72855. v0.triangleCount = tCount;
  72856. break;
  72857. }
  72858. }
  72859. };
  72860. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  72861. }, 0);
  72862. };
  72863. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  72864. if (triangleCount - deletedTriangles <= targetCount)
  72865. loop.breakLoop();
  72866. else {
  72867. iterationFunction(loop.index, function () {
  72868. loop.executeNext();
  72869. });
  72870. }
  72871. }, function () {
  72872. setTimeout(function () {
  72873. //reconstruct this part of the mesh
  72874. _this.reconstructMesh(submeshIndex);
  72875. successCallback();
  72876. }, 0);
  72877. });
  72878. };
  72879. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  72880. var _this = this;
  72881. this.vertices = [];
  72882. this.triangles = [];
  72883. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  72884. var indices = this._mesh.getIndices();
  72885. var submesh = this._mesh.subMeshes[submeshIndex];
  72886. var findInVertices = function (positionToSearch) {
  72887. if (optimizeMesh) {
  72888. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  72889. if (_this.vertices[ii].position.equals(positionToSearch)) {
  72890. return _this.vertices[ii];
  72891. }
  72892. }
  72893. }
  72894. return null;
  72895. };
  72896. var vertexReferences = [];
  72897. var vertexInit = function (i) {
  72898. if (!positionData) {
  72899. return;
  72900. }
  72901. var offset = i + submesh.verticesStart;
  72902. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  72903. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  72904. vertex.originalOffsets.push(offset);
  72905. if (vertex.id === _this.vertices.length) {
  72906. _this.vertices.push(vertex);
  72907. }
  72908. vertexReferences.push(vertex.id);
  72909. };
  72910. //var totalVertices = mesh.getTotalVertices();
  72911. var totalVertices = submesh.verticesCount;
  72912. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  72913. var indicesInit = function (i) {
  72914. if (!indices) {
  72915. return;
  72916. }
  72917. var offset = (submesh.indexStart / 3) + i;
  72918. var pos = (offset * 3);
  72919. var i0 = indices[pos + 0];
  72920. var i1 = indices[pos + 1];
  72921. var i2 = indices[pos + 2];
  72922. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  72923. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  72924. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  72925. var triangle = new DecimationTriangle([v0, v1, v2]);
  72926. triangle.originalOffset = pos;
  72927. _this.triangles.push(triangle);
  72928. };
  72929. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  72930. _this.init(callback);
  72931. });
  72932. });
  72933. };
  72934. QuadraticErrorSimplification.prototype.init = function (callback) {
  72935. var _this = this;
  72936. var triangleInit1 = function (i) {
  72937. var t = _this.triangles[i];
  72938. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  72939. for (var j = 0; j < 3; j++) {
  72940. 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))));
  72941. }
  72942. };
  72943. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  72944. var triangleInit2 = function (i) {
  72945. var t = _this.triangles[i];
  72946. for (var j = 0; j < 3; ++j) {
  72947. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  72948. }
  72949. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  72950. };
  72951. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  72952. callback();
  72953. });
  72954. });
  72955. };
  72956. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  72957. var newTriangles = [];
  72958. var i;
  72959. for (i = 0; i < this.vertices.length; ++i) {
  72960. this.vertices[i].triangleCount = 0;
  72961. }
  72962. var t;
  72963. var j;
  72964. for (i = 0; i < this.triangles.length; ++i) {
  72965. if (!this.triangles[i].deleted) {
  72966. t = this.triangles[i];
  72967. for (j = 0; j < 3; ++j) {
  72968. t.vertices[j].triangleCount = 1;
  72969. }
  72970. newTriangles.push(t);
  72971. }
  72972. }
  72973. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  72974. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  72975. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  72976. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  72977. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  72978. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72979. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  72980. var vertexCount = 0;
  72981. for (i = 0; i < this.vertices.length; ++i) {
  72982. var vertex = this.vertices[i];
  72983. vertex.id = vertexCount;
  72984. if (vertex.triangleCount) {
  72985. vertex.originalOffsets.forEach(function (originalOffset) {
  72986. if (!normalData) {
  72987. return;
  72988. }
  72989. newPositionData.push(vertex.position.x);
  72990. newPositionData.push(vertex.position.y);
  72991. newPositionData.push(vertex.position.z);
  72992. newNormalData.push(normalData[originalOffset * 3]);
  72993. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  72994. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  72995. if (uvs && uvs.length) {
  72996. newUVsData.push(uvs[(originalOffset * 2)]);
  72997. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  72998. }
  72999. else if (colorsData && colorsData.length) {
  73000. newColorsData.push(colorsData[(originalOffset * 4)]);
  73001. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  73002. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  73003. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  73004. }
  73005. ++vertexCount;
  73006. });
  73007. }
  73008. }
  73009. var startingIndex = this._reconstructedMesh.getTotalIndices();
  73010. var startingVertex = this._reconstructedMesh.getTotalVertices();
  73011. var submeshesArray = this._reconstructedMesh.subMeshes;
  73012. this._reconstructedMesh.subMeshes = [];
  73013. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  73014. var originalIndices = this._mesh.getIndices();
  73015. for (i = 0; i < newTriangles.length; ++i) {
  73016. t = newTriangles[i]; //now get the new referencing point for each vertex
  73017. [0, 1, 2].forEach(function (idx) {
  73018. var id = originalIndices[t.originalOffset + idx];
  73019. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  73020. if (offset < 0)
  73021. offset = 0;
  73022. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  73023. });
  73024. }
  73025. //overwriting the old vertex buffers and indices.
  73026. this._reconstructedMesh.setIndices(newIndicesArray);
  73027. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  73028. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  73029. if (newUVsData.length > 0)
  73030. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  73031. if (newColorsData.length > 0)
  73032. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  73033. //create submesh
  73034. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  73035. if (submeshIndex > 0) {
  73036. this._reconstructedMesh.subMeshes = [];
  73037. submeshesArray.forEach(function (submesh) {
  73038. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  73039. });
  73040. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  73041. }
  73042. };
  73043. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  73044. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  73045. this._reconstructedMesh.material = this._mesh.material;
  73046. this._reconstructedMesh.parent = this._mesh.parent;
  73047. this._reconstructedMesh.isVisible = false;
  73048. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  73049. };
  73050. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  73051. for (var i = 0; i < vertex1.triangleCount; ++i) {
  73052. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  73053. if (t.deleted)
  73054. continue;
  73055. var s = this.references[vertex1.triangleStart + i].vertexId;
  73056. var v1 = t.vertices[(s + 1) % 3];
  73057. var v2 = t.vertices[(s + 2) % 3];
  73058. if ((v1 === vertex2 || v2 === vertex2)) {
  73059. deletedArray[i] = true;
  73060. delTr.push(t);
  73061. continue;
  73062. }
  73063. var d1 = v1.position.subtract(point);
  73064. d1 = d1.normalize();
  73065. var d2 = v2.position.subtract(point);
  73066. d2 = d2.normalize();
  73067. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  73068. return true;
  73069. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  73070. deletedArray[i] = false;
  73071. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  73072. return true;
  73073. }
  73074. return false;
  73075. };
  73076. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  73077. var newDeleted = deletedTriangles;
  73078. for (var i = 0; i < vertex.triangleCount; ++i) {
  73079. var ref = this.references[vertex.triangleStart + i];
  73080. var t = this.triangles[ref.triangleId];
  73081. if (t.deleted)
  73082. continue;
  73083. if (deletedArray[i] && t.deletePending) {
  73084. t.deleted = true;
  73085. newDeleted++;
  73086. continue;
  73087. }
  73088. t.vertices[ref.vertexId] = origVertex;
  73089. t.isDirty = true;
  73090. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  73091. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  73092. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  73093. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73094. this.references.push(ref);
  73095. }
  73096. return newDeleted;
  73097. };
  73098. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  73099. for (var i = 0; i < this.vertices.length; ++i) {
  73100. var vCount = [];
  73101. var vId = [];
  73102. var v = this.vertices[i];
  73103. var j;
  73104. for (j = 0; j < v.triangleCount; ++j) {
  73105. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  73106. for (var ii = 0; ii < 3; ii++) {
  73107. var ofs = 0;
  73108. var vv = triangle.vertices[ii];
  73109. while (ofs < vCount.length) {
  73110. if (vId[ofs] === vv.id)
  73111. break;
  73112. ++ofs;
  73113. }
  73114. if (ofs === vCount.length) {
  73115. vCount.push(1);
  73116. vId.push(vv.id);
  73117. }
  73118. else {
  73119. vCount[ofs]++;
  73120. }
  73121. }
  73122. }
  73123. for (j = 0; j < vCount.length; ++j) {
  73124. if (vCount[j] === 1) {
  73125. this.vertices[vId[j]].isBorder = true;
  73126. }
  73127. else {
  73128. this.vertices[vId[j]].isBorder = false;
  73129. }
  73130. }
  73131. }
  73132. };
  73133. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  73134. if (identifyBorders === void 0) { identifyBorders = false; }
  73135. var i;
  73136. if (!identifyBorders) {
  73137. var newTrianglesVector = [];
  73138. for (i = 0; i < this.triangles.length; ++i) {
  73139. if (!this.triangles[i].deleted) {
  73140. newTrianglesVector.push(this.triangles[i]);
  73141. }
  73142. }
  73143. this.triangles = newTrianglesVector;
  73144. }
  73145. for (i = 0; i < this.vertices.length; ++i) {
  73146. this.vertices[i].triangleCount = 0;
  73147. this.vertices[i].triangleStart = 0;
  73148. }
  73149. var t;
  73150. var j;
  73151. var v;
  73152. for (i = 0; i < this.triangles.length; ++i) {
  73153. t = this.triangles[i];
  73154. for (j = 0; j < 3; ++j) {
  73155. v = t.vertices[j];
  73156. v.triangleCount++;
  73157. }
  73158. }
  73159. var tStart = 0;
  73160. for (i = 0; i < this.vertices.length; ++i) {
  73161. this.vertices[i].triangleStart = tStart;
  73162. tStart += this.vertices[i].triangleCount;
  73163. this.vertices[i].triangleCount = 0;
  73164. }
  73165. var newReferences = new Array(this.triangles.length * 3);
  73166. for (i = 0; i < this.triangles.length; ++i) {
  73167. t = this.triangles[i];
  73168. for (j = 0; j < 3; ++j) {
  73169. v = t.vertices[j];
  73170. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  73171. v.triangleCount++;
  73172. }
  73173. }
  73174. this.references = newReferences;
  73175. if (identifyBorders) {
  73176. this.identifyBorder();
  73177. }
  73178. };
  73179. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  73180. var x = point.x;
  73181. var y = point.y;
  73182. var z = point.z;
  73183. 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
  73184. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  73185. };
  73186. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  73187. var q = vertex1.q.add(vertex2.q);
  73188. var border = vertex1.isBorder && vertex2.isBorder;
  73189. var error = 0;
  73190. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  73191. if (qDet !== 0 && !border) {
  73192. if (!pointResult) {
  73193. pointResult = BABYLON.Vector3.Zero();
  73194. }
  73195. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  73196. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  73197. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  73198. error = this.vertexError(q, pointResult);
  73199. }
  73200. else {
  73201. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  73202. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  73203. var error1 = this.vertexError(q, vertex1.position);
  73204. var error2 = this.vertexError(q, vertex2.position);
  73205. var error3 = this.vertexError(q, p3);
  73206. error = Math.min(error1, error2, error3);
  73207. if (error === error1) {
  73208. if (pointResult) {
  73209. pointResult.copyFrom(vertex1.position);
  73210. }
  73211. }
  73212. else if (error === error2) {
  73213. if (pointResult) {
  73214. pointResult.copyFrom(vertex2.position);
  73215. }
  73216. }
  73217. else {
  73218. if (pointResult) {
  73219. pointResult.copyFrom(p3);
  73220. }
  73221. }
  73222. }
  73223. return error;
  73224. };
  73225. return QuadraticErrorSimplification;
  73226. }());
  73227. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  73228. })(BABYLON || (BABYLON = {}));
  73229. //# sourceMappingURL=babylon.meshSimplification.js.map
  73230. var BABYLON;
  73231. (function (BABYLON) {
  73232. var Internals;
  73233. (function (Internals) {
  73234. var MeshLODLevel = /** @class */ (function () {
  73235. function MeshLODLevel(distance, mesh) {
  73236. this.distance = distance;
  73237. this.mesh = mesh;
  73238. }
  73239. return MeshLODLevel;
  73240. }());
  73241. Internals.MeshLODLevel = MeshLODLevel;
  73242. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  73243. })(BABYLON || (BABYLON = {}));
  73244. //# sourceMappingURL=babylon.meshLODLevel.js.map
  73245. var BABYLON;
  73246. (function (BABYLON) {
  73247. // Standard optimizations
  73248. var SceneOptimization = /** @class */ (function () {
  73249. function SceneOptimization(priority) {
  73250. if (priority === void 0) { priority = 0; }
  73251. this.priority = priority;
  73252. this.apply = function (scene) {
  73253. return true; // Return true if everything that can be done was applied
  73254. };
  73255. }
  73256. return SceneOptimization;
  73257. }());
  73258. BABYLON.SceneOptimization = SceneOptimization;
  73259. var TextureOptimization = /** @class */ (function (_super) {
  73260. __extends(TextureOptimization, _super);
  73261. function TextureOptimization(priority, maximumSize) {
  73262. if (priority === void 0) { priority = 0; }
  73263. if (maximumSize === void 0) { maximumSize = 1024; }
  73264. var _this = _super.call(this, priority) || this;
  73265. _this.priority = priority;
  73266. _this.maximumSize = maximumSize;
  73267. _this.apply = function (scene) {
  73268. var allDone = true;
  73269. for (var index = 0; index < scene.textures.length; index++) {
  73270. var texture = scene.textures[index];
  73271. if (!texture.canRescale || texture.getContext) {
  73272. continue;
  73273. }
  73274. var currentSize = texture.getSize();
  73275. var maxDimension = Math.max(currentSize.width, currentSize.height);
  73276. if (maxDimension > _this.maximumSize) {
  73277. texture.scale(0.5);
  73278. allDone = false;
  73279. }
  73280. }
  73281. return allDone;
  73282. };
  73283. return _this;
  73284. }
  73285. return TextureOptimization;
  73286. }(SceneOptimization));
  73287. BABYLON.TextureOptimization = TextureOptimization;
  73288. var HardwareScalingOptimization = /** @class */ (function (_super) {
  73289. __extends(HardwareScalingOptimization, _super);
  73290. function HardwareScalingOptimization(priority, maximumScale) {
  73291. if (priority === void 0) { priority = 0; }
  73292. if (maximumScale === void 0) { maximumScale = 2; }
  73293. var _this = _super.call(this, priority) || this;
  73294. _this.priority = priority;
  73295. _this.maximumScale = maximumScale;
  73296. _this._currentScale = 1;
  73297. _this.apply = function (scene) {
  73298. _this._currentScale++;
  73299. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  73300. return _this._currentScale >= _this.maximumScale;
  73301. };
  73302. return _this;
  73303. }
  73304. return HardwareScalingOptimization;
  73305. }(SceneOptimization));
  73306. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  73307. var ShadowsOptimization = /** @class */ (function (_super) {
  73308. __extends(ShadowsOptimization, _super);
  73309. function ShadowsOptimization() {
  73310. var _this = _super !== null && _super.apply(this, arguments) || this;
  73311. _this.apply = function (scene) {
  73312. scene.shadowsEnabled = false;
  73313. return true;
  73314. };
  73315. return _this;
  73316. }
  73317. return ShadowsOptimization;
  73318. }(SceneOptimization));
  73319. BABYLON.ShadowsOptimization = ShadowsOptimization;
  73320. var PostProcessesOptimization = /** @class */ (function (_super) {
  73321. __extends(PostProcessesOptimization, _super);
  73322. function PostProcessesOptimization() {
  73323. var _this = _super !== null && _super.apply(this, arguments) || this;
  73324. _this.apply = function (scene) {
  73325. scene.postProcessesEnabled = false;
  73326. return true;
  73327. };
  73328. return _this;
  73329. }
  73330. return PostProcessesOptimization;
  73331. }(SceneOptimization));
  73332. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  73333. var LensFlaresOptimization = /** @class */ (function (_super) {
  73334. __extends(LensFlaresOptimization, _super);
  73335. function LensFlaresOptimization() {
  73336. var _this = _super !== null && _super.apply(this, arguments) || this;
  73337. _this.apply = function (scene) {
  73338. scene.lensFlaresEnabled = false;
  73339. return true;
  73340. };
  73341. return _this;
  73342. }
  73343. return LensFlaresOptimization;
  73344. }(SceneOptimization));
  73345. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  73346. var ParticlesOptimization = /** @class */ (function (_super) {
  73347. __extends(ParticlesOptimization, _super);
  73348. function ParticlesOptimization() {
  73349. var _this = _super !== null && _super.apply(this, arguments) || this;
  73350. _this.apply = function (scene) {
  73351. scene.particlesEnabled = false;
  73352. return true;
  73353. };
  73354. return _this;
  73355. }
  73356. return ParticlesOptimization;
  73357. }(SceneOptimization));
  73358. BABYLON.ParticlesOptimization = ParticlesOptimization;
  73359. var RenderTargetsOptimization = /** @class */ (function (_super) {
  73360. __extends(RenderTargetsOptimization, _super);
  73361. function RenderTargetsOptimization() {
  73362. var _this = _super !== null && _super.apply(this, arguments) || this;
  73363. _this.apply = function (scene) {
  73364. scene.renderTargetsEnabled = false;
  73365. return true;
  73366. };
  73367. return _this;
  73368. }
  73369. return RenderTargetsOptimization;
  73370. }(SceneOptimization));
  73371. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  73372. var MergeMeshesOptimization = /** @class */ (function (_super) {
  73373. __extends(MergeMeshesOptimization, _super);
  73374. function MergeMeshesOptimization() {
  73375. var _this = _super !== null && _super.apply(this, arguments) || this;
  73376. _this._canBeMerged = function (abstractMesh) {
  73377. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  73378. return false;
  73379. }
  73380. var mesh = abstractMesh;
  73381. if (!mesh.isVisible || !mesh.isEnabled()) {
  73382. return false;
  73383. }
  73384. if (mesh.instances.length > 0) {
  73385. return false;
  73386. }
  73387. if (mesh.skeleton || mesh.hasLODLevels) {
  73388. return false;
  73389. }
  73390. if (mesh.parent) {
  73391. return false;
  73392. }
  73393. return true;
  73394. };
  73395. _this.apply = function (scene, updateSelectionTree) {
  73396. var globalPool = scene.meshes.slice(0);
  73397. var globalLength = globalPool.length;
  73398. for (var index = 0; index < globalLength; index++) {
  73399. var currentPool = new Array();
  73400. var current = globalPool[index];
  73401. // Checks
  73402. if (!_this._canBeMerged(current)) {
  73403. continue;
  73404. }
  73405. currentPool.push(current);
  73406. // Find compatible meshes
  73407. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  73408. var otherMesh = globalPool[subIndex];
  73409. if (!_this._canBeMerged(otherMesh)) {
  73410. continue;
  73411. }
  73412. if (otherMesh.material !== current.material) {
  73413. continue;
  73414. }
  73415. if (otherMesh.checkCollisions !== current.checkCollisions) {
  73416. continue;
  73417. }
  73418. currentPool.push(otherMesh);
  73419. globalLength--;
  73420. globalPool.splice(subIndex, 1);
  73421. subIndex--;
  73422. }
  73423. if (currentPool.length < 2) {
  73424. continue;
  73425. }
  73426. // Merge meshes
  73427. BABYLON.Mesh.MergeMeshes(currentPool);
  73428. }
  73429. if (updateSelectionTree != undefined) {
  73430. if (updateSelectionTree) {
  73431. scene.createOrUpdateSelectionOctree();
  73432. }
  73433. }
  73434. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  73435. scene.createOrUpdateSelectionOctree();
  73436. }
  73437. return true;
  73438. };
  73439. return _this;
  73440. }
  73441. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  73442. get: function () {
  73443. return MergeMeshesOptimization._UpdateSelectionTree;
  73444. },
  73445. set: function (value) {
  73446. MergeMeshesOptimization._UpdateSelectionTree = value;
  73447. },
  73448. enumerable: true,
  73449. configurable: true
  73450. });
  73451. MergeMeshesOptimization._UpdateSelectionTree = false;
  73452. return MergeMeshesOptimization;
  73453. }(SceneOptimization));
  73454. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  73455. // Options
  73456. var SceneOptimizerOptions = /** @class */ (function () {
  73457. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  73458. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  73459. if (trackerDuration === void 0) { trackerDuration = 2000; }
  73460. this.targetFrameRate = targetFrameRate;
  73461. this.trackerDuration = trackerDuration;
  73462. this.optimizations = new Array();
  73463. }
  73464. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  73465. var result = new SceneOptimizerOptions(targetFrameRate);
  73466. var priority = 0;
  73467. result.optimizations.push(new MergeMeshesOptimization(priority));
  73468. result.optimizations.push(new ShadowsOptimization(priority));
  73469. result.optimizations.push(new LensFlaresOptimization(priority));
  73470. // Next priority
  73471. priority++;
  73472. result.optimizations.push(new PostProcessesOptimization(priority));
  73473. result.optimizations.push(new ParticlesOptimization(priority));
  73474. // Next priority
  73475. priority++;
  73476. result.optimizations.push(new TextureOptimization(priority, 1024));
  73477. return result;
  73478. };
  73479. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  73480. var result = new SceneOptimizerOptions(targetFrameRate);
  73481. var priority = 0;
  73482. result.optimizations.push(new MergeMeshesOptimization(priority));
  73483. result.optimizations.push(new ShadowsOptimization(priority));
  73484. result.optimizations.push(new LensFlaresOptimization(priority));
  73485. // Next priority
  73486. priority++;
  73487. result.optimizations.push(new PostProcessesOptimization(priority));
  73488. result.optimizations.push(new ParticlesOptimization(priority));
  73489. // Next priority
  73490. priority++;
  73491. result.optimizations.push(new TextureOptimization(priority, 512));
  73492. // Next priority
  73493. priority++;
  73494. result.optimizations.push(new RenderTargetsOptimization(priority));
  73495. // Next priority
  73496. priority++;
  73497. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  73498. return result;
  73499. };
  73500. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  73501. var result = new SceneOptimizerOptions(targetFrameRate);
  73502. var priority = 0;
  73503. result.optimizations.push(new MergeMeshesOptimization(priority));
  73504. result.optimizations.push(new ShadowsOptimization(priority));
  73505. result.optimizations.push(new LensFlaresOptimization(priority));
  73506. // Next priority
  73507. priority++;
  73508. result.optimizations.push(new PostProcessesOptimization(priority));
  73509. result.optimizations.push(new ParticlesOptimization(priority));
  73510. // Next priority
  73511. priority++;
  73512. result.optimizations.push(new TextureOptimization(priority, 256));
  73513. // Next priority
  73514. priority++;
  73515. result.optimizations.push(new RenderTargetsOptimization(priority));
  73516. // Next priority
  73517. priority++;
  73518. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  73519. return result;
  73520. };
  73521. return SceneOptimizerOptions;
  73522. }());
  73523. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  73524. // Scene optimizer tool
  73525. var SceneOptimizer = /** @class */ (function () {
  73526. function SceneOptimizer() {
  73527. }
  73528. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  73529. // TODO: add an epsilon
  73530. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  73531. if (onSuccess) {
  73532. onSuccess();
  73533. }
  73534. return;
  73535. }
  73536. // Apply current level of optimizations
  73537. var allDone = true;
  73538. var noOptimizationApplied = true;
  73539. for (var index = 0; index < options.optimizations.length; index++) {
  73540. var optimization = options.optimizations[index];
  73541. if (optimization.priority === currentPriorityLevel) {
  73542. noOptimizationApplied = false;
  73543. allDone = allDone && optimization.apply(scene);
  73544. }
  73545. }
  73546. // If no optimization was applied, this is a failure :(
  73547. if (noOptimizationApplied) {
  73548. if (onFailure) {
  73549. onFailure();
  73550. }
  73551. return;
  73552. }
  73553. // If all optimizations were done, move to next level
  73554. if (allDone) {
  73555. currentPriorityLevel++;
  73556. }
  73557. // Let's the system running for a specific amount of time before checking FPS
  73558. scene.executeWhenReady(function () {
  73559. setTimeout(function () {
  73560. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  73561. }, options.trackerDuration);
  73562. });
  73563. };
  73564. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  73565. if (!options) {
  73566. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  73567. }
  73568. // Let's the system running for a specific amount of time before checking FPS
  73569. scene.executeWhenReady(function () {
  73570. setTimeout(function () {
  73571. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  73572. }, options.trackerDuration);
  73573. });
  73574. };
  73575. return SceneOptimizer;
  73576. }());
  73577. BABYLON.SceneOptimizer = SceneOptimizer;
  73578. })(BABYLON || (BABYLON = {}));
  73579. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  73580. var BABYLON;
  73581. (function (BABYLON) {
  73582. var OutlineRenderer = /** @class */ (function () {
  73583. function OutlineRenderer(scene) {
  73584. this.zOffset = 1;
  73585. this._scene = scene;
  73586. }
  73587. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  73588. var _this = this;
  73589. if (useOverlay === void 0) { useOverlay = false; }
  73590. var scene = this._scene;
  73591. var engine = this._scene.getEngine();
  73592. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73593. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  73594. return;
  73595. }
  73596. var mesh = subMesh.getRenderingMesh();
  73597. var material = subMesh.getMaterial();
  73598. if (!material || !scene.activeCamera) {
  73599. return;
  73600. }
  73601. engine.enableEffect(this._effect);
  73602. // Logarithmic depth
  73603. if (material.useLogarithmicDepth) {
  73604. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  73605. }
  73606. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  73607. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  73608. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73609. // Bones
  73610. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73611. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73612. }
  73613. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73614. // Alpha test
  73615. if (material && material.needAlphaTesting()) {
  73616. var alphaTexture = material.getAlphaTestTexture();
  73617. if (alphaTexture) {
  73618. this._effect.setTexture("diffuseSampler", alphaTexture);
  73619. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73620. }
  73621. }
  73622. engine.setZOffset(-this.zOffset);
  73623. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  73624. engine.setZOffset(0);
  73625. };
  73626. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  73627. var defines = [];
  73628. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  73629. var mesh = subMesh.getMesh();
  73630. var material = subMesh.getMaterial();
  73631. if (material) {
  73632. // Alpha test
  73633. if (material.needAlphaTesting()) {
  73634. defines.push("#define ALPHATEST");
  73635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73636. attribs.push(BABYLON.VertexBuffer.UVKind);
  73637. defines.push("#define UV1");
  73638. }
  73639. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73640. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73641. defines.push("#define UV2");
  73642. }
  73643. }
  73644. //Logarithmic depth
  73645. if (material.useLogarithmicDepth) {
  73646. defines.push("#define LOGARITHMICDEPTH");
  73647. }
  73648. }
  73649. // Bones
  73650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73653. if (mesh.numBoneInfluencers > 4) {
  73654. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73655. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73656. }
  73657. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73658. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73659. }
  73660. else {
  73661. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73662. }
  73663. // Instances
  73664. if (useInstances) {
  73665. defines.push("#define INSTANCES");
  73666. attribs.push("world0");
  73667. attribs.push("world1");
  73668. attribs.push("world2");
  73669. attribs.push("world3");
  73670. }
  73671. // Get correct effect
  73672. var join = defines.join("\n");
  73673. if (this._cachedDefines !== join) {
  73674. this._cachedDefines = join;
  73675. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  73676. }
  73677. return this._effect.isReady();
  73678. };
  73679. return OutlineRenderer;
  73680. }());
  73681. BABYLON.OutlineRenderer = OutlineRenderer;
  73682. })(BABYLON || (BABYLON = {}));
  73683. //# sourceMappingURL=babylon.outlineRenderer.js.map
  73684. var BABYLON;
  73685. (function (BABYLON) {
  73686. var FaceAdjacencies = /** @class */ (function () {
  73687. function FaceAdjacencies() {
  73688. this.edges = new Array();
  73689. this.edgesConnectedCount = 0;
  73690. }
  73691. return FaceAdjacencies;
  73692. }());
  73693. var EdgesRenderer = /** @class */ (function () {
  73694. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  73695. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  73696. if (epsilon === void 0) { epsilon = 0.95; }
  73697. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  73698. this.edgesWidthScalerForOrthographic = 1000.0;
  73699. this.edgesWidthScalerForPerspective = 50.0;
  73700. this._linesPositions = new Array();
  73701. this._linesNormals = new Array();
  73702. this._linesIndices = new Array();
  73703. this._buffers = {};
  73704. this._checkVerticesInsteadOfIndices = false;
  73705. this._source = source;
  73706. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  73707. this._epsilon = epsilon;
  73708. this._prepareRessources();
  73709. this._generateEdgesLines();
  73710. }
  73711. EdgesRenderer.prototype._prepareRessources = function () {
  73712. if (this._lineShader) {
  73713. return;
  73714. }
  73715. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  73716. attributes: ["position", "normal"],
  73717. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  73718. });
  73719. this._lineShader.disableDepthWrite = true;
  73720. this._lineShader.backFaceCulling = false;
  73721. };
  73722. EdgesRenderer.prototype._rebuild = function () {
  73723. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73724. if (buffer) {
  73725. buffer._rebuild();
  73726. }
  73727. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73728. if (buffer) {
  73729. buffer._rebuild();
  73730. }
  73731. var scene = this._source.getScene();
  73732. var engine = scene.getEngine();
  73733. this._ib = engine.createIndexBuffer(this._linesIndices);
  73734. };
  73735. EdgesRenderer.prototype.dispose = function () {
  73736. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73737. if (buffer) {
  73738. buffer.dispose();
  73739. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  73740. }
  73741. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73742. if (buffer) {
  73743. buffer.dispose();
  73744. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  73745. }
  73746. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  73747. this._lineShader.dispose();
  73748. };
  73749. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  73750. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  73751. return 0;
  73752. }
  73753. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  73754. return 1;
  73755. }
  73756. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  73757. return 2;
  73758. }
  73759. return -1;
  73760. };
  73761. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  73762. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  73763. return 0;
  73764. }
  73765. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  73766. return 1;
  73767. }
  73768. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  73769. return 2;
  73770. }
  73771. return -1;
  73772. };
  73773. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  73774. var needToCreateLine;
  73775. if (edge === undefined) {
  73776. needToCreateLine = true;
  73777. }
  73778. else {
  73779. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  73780. needToCreateLine = dotProduct < this._epsilon;
  73781. }
  73782. if (needToCreateLine) {
  73783. var offset = this._linesPositions.length / 3;
  73784. var normal = p0.subtract(p1);
  73785. normal.normalize();
  73786. // Positions
  73787. this._linesPositions.push(p0.x);
  73788. this._linesPositions.push(p0.y);
  73789. this._linesPositions.push(p0.z);
  73790. this._linesPositions.push(p0.x);
  73791. this._linesPositions.push(p0.y);
  73792. this._linesPositions.push(p0.z);
  73793. this._linesPositions.push(p1.x);
  73794. this._linesPositions.push(p1.y);
  73795. this._linesPositions.push(p1.z);
  73796. this._linesPositions.push(p1.x);
  73797. this._linesPositions.push(p1.y);
  73798. this._linesPositions.push(p1.z);
  73799. // Normals
  73800. this._linesNormals.push(p1.x);
  73801. this._linesNormals.push(p1.y);
  73802. this._linesNormals.push(p1.z);
  73803. this._linesNormals.push(-1);
  73804. this._linesNormals.push(p1.x);
  73805. this._linesNormals.push(p1.y);
  73806. this._linesNormals.push(p1.z);
  73807. this._linesNormals.push(1);
  73808. this._linesNormals.push(p0.x);
  73809. this._linesNormals.push(p0.y);
  73810. this._linesNormals.push(p0.z);
  73811. this._linesNormals.push(-1);
  73812. this._linesNormals.push(p0.x);
  73813. this._linesNormals.push(p0.y);
  73814. this._linesNormals.push(p0.z);
  73815. this._linesNormals.push(1);
  73816. // Indices
  73817. this._linesIndices.push(offset);
  73818. this._linesIndices.push(offset + 1);
  73819. this._linesIndices.push(offset + 2);
  73820. this._linesIndices.push(offset);
  73821. this._linesIndices.push(offset + 2);
  73822. this._linesIndices.push(offset + 3);
  73823. }
  73824. };
  73825. EdgesRenderer.prototype._generateEdgesLines = function () {
  73826. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  73827. var indices = this._source.getIndices();
  73828. if (!indices || !positions) {
  73829. return;
  73830. }
  73831. // First let's find adjacencies
  73832. var adjacencies = new Array();
  73833. var faceNormals = new Array();
  73834. var index;
  73835. var faceAdjacencies;
  73836. // Prepare faces
  73837. for (index = 0; index < indices.length; index += 3) {
  73838. faceAdjacencies = new FaceAdjacencies();
  73839. var p0Index = indices[index];
  73840. var p1Index = indices[index + 1];
  73841. var p2Index = indices[index + 2];
  73842. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  73843. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  73844. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  73845. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  73846. faceNormal.normalize();
  73847. faceNormals.push(faceNormal);
  73848. adjacencies.push(faceAdjacencies);
  73849. }
  73850. // Scan
  73851. for (index = 0; index < adjacencies.length; index++) {
  73852. faceAdjacencies = adjacencies[index];
  73853. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  73854. var otherFaceAdjacencies = adjacencies[otherIndex];
  73855. if (faceAdjacencies.edgesConnectedCount === 3) {
  73856. break;
  73857. }
  73858. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  73859. continue;
  73860. }
  73861. var otherP0 = indices[otherIndex * 3];
  73862. var otherP1 = indices[otherIndex * 3 + 1];
  73863. var otherP2 = indices[otherIndex * 3 + 2];
  73864. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  73865. var otherEdgeIndex = 0;
  73866. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  73867. continue;
  73868. }
  73869. switch (edgeIndex) {
  73870. case 0:
  73871. if (this._checkVerticesInsteadOfIndices) {
  73872. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73873. }
  73874. else {
  73875. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  73876. }
  73877. break;
  73878. case 1:
  73879. if (this._checkVerticesInsteadOfIndices) {
  73880. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73881. }
  73882. else {
  73883. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  73884. }
  73885. break;
  73886. case 2:
  73887. if (this._checkVerticesInsteadOfIndices) {
  73888. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73889. }
  73890. else {
  73891. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  73892. }
  73893. break;
  73894. }
  73895. if (otherEdgeIndex === -1) {
  73896. continue;
  73897. }
  73898. faceAdjacencies.edges[edgeIndex] = otherIndex;
  73899. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  73900. faceAdjacencies.edgesConnectedCount++;
  73901. otherFaceAdjacencies.edgesConnectedCount++;
  73902. if (faceAdjacencies.edgesConnectedCount === 3) {
  73903. break;
  73904. }
  73905. }
  73906. }
  73907. }
  73908. // Create lines
  73909. for (index = 0; index < adjacencies.length; index++) {
  73910. // 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
  73911. var current = adjacencies[index];
  73912. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  73913. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  73914. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  73915. }
  73916. // Merge into a single mesh
  73917. var engine = this._source.getScene().getEngine();
  73918. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  73919. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  73920. this._ib = engine.createIndexBuffer(this._linesIndices);
  73921. this._indicesCount = this._linesIndices.length;
  73922. };
  73923. EdgesRenderer.prototype.render = function () {
  73924. var scene = this._source.getScene();
  73925. if (!this._lineShader.isReady() || !scene.activeCamera) {
  73926. return;
  73927. }
  73928. var engine = scene.getEngine();
  73929. this._lineShader._preBind();
  73930. // VBOs
  73931. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  73932. scene.resetCachedMaterial();
  73933. this._lineShader.setColor4("color", this._source.edgesColor);
  73934. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  73935. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  73936. }
  73937. else {
  73938. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  73939. }
  73940. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  73941. this._lineShader.bind(this._source.getWorldMatrix());
  73942. // Draw order
  73943. engine.draw(true, 0, this._indicesCount);
  73944. this._lineShader.unbind();
  73945. engine.setDepthWrite(true);
  73946. };
  73947. return EdgesRenderer;
  73948. }());
  73949. BABYLON.EdgesRenderer = EdgesRenderer;
  73950. })(BABYLON || (BABYLON = {}));
  73951. //# sourceMappingURL=babylon.edgesRenderer.js.map
  73952. var BABYLON;
  73953. (function (BABYLON) {
  73954. /**
  73955. * Special Glow Blur post process only blurring the alpha channel
  73956. * It enforces keeping the most luminous color in the color channel.
  73957. */
  73958. var GlowBlurPostProcess = /** @class */ (function (_super) {
  73959. __extends(GlowBlurPostProcess, _super);
  73960. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  73961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73962. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  73963. _this.direction = direction;
  73964. _this.kernel = kernel;
  73965. _this.onApplyObservable.add(function (effect) {
  73966. effect.setFloat2("screenSize", _this.width, _this.height);
  73967. effect.setVector2("direction", _this.direction);
  73968. effect.setFloat("blurWidth", _this.kernel);
  73969. });
  73970. return _this;
  73971. }
  73972. return GlowBlurPostProcess;
  73973. }(BABYLON.PostProcess));
  73974. /**
  73975. * The highlight layer Helps adding a glow effect around a mesh.
  73976. *
  73977. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  73978. * glowy meshes to your scene.
  73979. *
  73980. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  73981. */
  73982. var HighlightLayer = /** @class */ (function () {
  73983. /**
  73984. * Instantiates a new highlight Layer and references it to the scene..
  73985. * @param name The name of the layer
  73986. * @param scene The scene to use the layer in
  73987. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  73988. */
  73989. function HighlightLayer(name, scene, options) {
  73990. this.name = name;
  73991. this._vertexBuffers = {};
  73992. this._mainTextureDesiredSize = { width: 0, height: 0 };
  73993. this._meshes = {};
  73994. this._maxSize = 0;
  73995. this._shouldRender = false;
  73996. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  73997. this._excludedMeshes = {};
  73998. /**
  73999. * Specifies whether or not the inner glow is ACTIVE in the layer.
  74000. */
  74001. this.innerGlow = true;
  74002. /**
  74003. * Specifies whether or not the outer glow is ACTIVE in the layer.
  74004. */
  74005. this.outerGlow = true;
  74006. /**
  74007. * Specifies wether the highlight layer is enabled or not.
  74008. */
  74009. this.isEnabled = true;
  74010. /**
  74011. * An event triggered when the highlight layer has been disposed.
  74012. * @type {BABYLON.Observable}
  74013. */
  74014. this.onDisposeObservable = new BABYLON.Observable();
  74015. /**
  74016. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  74017. * @type {BABYLON.Observable}
  74018. */
  74019. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  74020. /**
  74021. * An event triggered when the highlight layer is being blurred.
  74022. * @type {BABYLON.Observable}
  74023. */
  74024. this.onBeforeBlurObservable = new BABYLON.Observable();
  74025. /**
  74026. * An event triggered when the highlight layer has been blurred.
  74027. * @type {BABYLON.Observable}
  74028. */
  74029. this.onAfterBlurObservable = new BABYLON.Observable();
  74030. /**
  74031. * An event triggered when the glowing blurred texture is being merged in the scene.
  74032. * @type {BABYLON.Observable}
  74033. */
  74034. this.onBeforeComposeObservable = new BABYLON.Observable();
  74035. /**
  74036. * An event triggered when the glowing blurred texture has been merged in the scene.
  74037. * @type {BABYLON.Observable}
  74038. */
  74039. this.onAfterComposeObservable = new BABYLON.Observable();
  74040. /**
  74041. * An event triggered when the highlight layer changes its size.
  74042. * @type {BABYLON.Observable}
  74043. */
  74044. this.onSizeChangedObservable = new BABYLON.Observable();
  74045. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74046. var engine = scene.getEngine();
  74047. this._engine = engine;
  74048. this._maxSize = this._engine.getCaps().maxTextureSize;
  74049. this._scene.highlightLayers.push(this);
  74050. // Warn on stencil.
  74051. if (!this._engine.isStencilEnable) {
  74052. 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 }");
  74053. }
  74054. // Adapt options
  74055. this._options = options || {
  74056. mainTextureRatio: 0.5,
  74057. blurTextureSizeRatio: 0.5,
  74058. blurHorizontalSize: 1.0,
  74059. blurVerticalSize: 1.0,
  74060. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  74061. camera: null
  74062. };
  74063. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  74064. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  74065. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  74066. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  74067. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  74068. // VBO
  74069. var vertices = [];
  74070. vertices.push(1, 1);
  74071. vertices.push(-1, 1);
  74072. vertices.push(-1, -1);
  74073. vertices.push(1, -1);
  74074. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74076. this._createIndexBuffer();
  74077. // Effect
  74078. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  74079. // Render target
  74080. this.setMainTextureSize();
  74081. // Create Textures and post processes
  74082. this.createTextureAndPostProcesses();
  74083. }
  74084. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  74085. /**
  74086. * Gets the horizontal size of the blur.
  74087. */
  74088. get: function () {
  74089. return this._horizontalBlurPostprocess.kernel;
  74090. },
  74091. /**
  74092. * Specifies the horizontal size of the blur.
  74093. */
  74094. set: function (value) {
  74095. this._horizontalBlurPostprocess.kernel = value;
  74096. },
  74097. enumerable: true,
  74098. configurable: true
  74099. });
  74100. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  74101. /**
  74102. * Gets the vertical size of the blur.
  74103. */
  74104. get: function () {
  74105. return this._verticalBlurPostprocess.kernel;
  74106. },
  74107. /**
  74108. * Specifies the vertical size of the blur.
  74109. */
  74110. set: function (value) {
  74111. this._verticalBlurPostprocess.kernel = value;
  74112. },
  74113. enumerable: true,
  74114. configurable: true
  74115. });
  74116. Object.defineProperty(HighlightLayer.prototype, "camera", {
  74117. /**
  74118. * Gets the camera attached to the layer.
  74119. */
  74120. get: function () {
  74121. return this._options.camera;
  74122. },
  74123. enumerable: true,
  74124. configurable: true
  74125. });
  74126. HighlightLayer.prototype._createIndexBuffer = function () {
  74127. var engine = this._scene.getEngine();
  74128. // Indices
  74129. var indices = [];
  74130. indices.push(0);
  74131. indices.push(1);
  74132. indices.push(2);
  74133. indices.push(0);
  74134. indices.push(2);
  74135. indices.push(3);
  74136. this._indexBuffer = engine.createIndexBuffer(indices);
  74137. };
  74138. HighlightLayer.prototype._rebuild = function () {
  74139. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74140. if (vb) {
  74141. vb._rebuild();
  74142. }
  74143. this._createIndexBuffer();
  74144. };
  74145. /**
  74146. * Creates the render target textures and post processes used in the highlight layer.
  74147. */
  74148. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  74149. var _this = this;
  74150. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  74151. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  74152. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  74153. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  74154. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  74155. width: this._mainTextureDesiredSize.width,
  74156. height: this._mainTextureDesiredSize.height
  74157. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74158. this._mainTexture.activeCamera = this._options.camera;
  74159. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74160. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74161. this._mainTexture.anisotropicFilteringLevel = 1;
  74162. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74163. this._mainTexture.renderParticles = false;
  74164. this._mainTexture.renderList = null;
  74165. this._mainTexture.ignoreCameraViewport = true;
  74166. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  74167. width: blurTextureWidth,
  74168. height: blurTextureHeight
  74169. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74170. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74171. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74172. this._blurTexture.anisotropicFilteringLevel = 16;
  74173. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74174. this._blurTexture.renderParticles = false;
  74175. this._blurTexture.ignoreCameraViewport = true;
  74176. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74177. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  74178. effect.setTexture("textureSampler", _this._mainTexture);
  74179. });
  74180. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  74181. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74182. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74183. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74184. });
  74185. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74186. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74187. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74188. });
  74189. }
  74190. else {
  74191. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74192. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74193. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74194. });
  74195. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74196. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74197. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74198. });
  74199. }
  74200. this._mainTexture.onAfterUnbindObservable.add(function () {
  74201. _this.onBeforeBlurObservable.notifyObservers(_this);
  74202. var internalTexture = _this._blurTexture.getInternalTexture();
  74203. if (internalTexture) {
  74204. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  74205. }
  74206. _this.onAfterBlurObservable.notifyObservers(_this);
  74207. });
  74208. // Custom render function
  74209. var renderSubMesh = function (subMesh) {
  74210. if (!_this._meshes) {
  74211. return;
  74212. }
  74213. var material = subMesh.getMaterial();
  74214. var mesh = subMesh.getRenderingMesh();
  74215. var scene = _this._scene;
  74216. var engine = scene.getEngine();
  74217. if (!material) {
  74218. return;
  74219. }
  74220. // Culling
  74221. engine.setState(material.backFaceCulling);
  74222. // Managing instances
  74223. var batch = mesh._getInstancesRenderList(subMesh._id);
  74224. if (batch.mustReturn) {
  74225. return;
  74226. }
  74227. // Excluded Mesh
  74228. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  74229. return;
  74230. }
  74231. ;
  74232. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74233. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  74234. var emissiveTexture = null;
  74235. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  74236. emissiveTexture = material.emissiveTexture;
  74237. }
  74238. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  74239. engine.enableEffect(_this._glowMapGenerationEffect);
  74240. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  74241. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  74242. if (highlightLayerMesh) {
  74243. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  74244. }
  74245. else {
  74246. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  74247. }
  74248. // Alpha test
  74249. if (material && material.needAlphaTesting()) {
  74250. var alphaTexture = material.getAlphaTestTexture();
  74251. if (alphaTexture) {
  74252. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  74253. var textureMatrix = alphaTexture.getTextureMatrix();
  74254. if (textureMatrix) {
  74255. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  74256. }
  74257. }
  74258. }
  74259. // Glow emissive only
  74260. if (emissiveTexture) {
  74261. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  74262. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  74263. }
  74264. // Bones
  74265. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74266. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74267. }
  74268. // Draw
  74269. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  74270. }
  74271. else {
  74272. // Need to reset refresh rate of the shadowMap
  74273. _this._mainTexture.resetRefreshCounter();
  74274. }
  74275. };
  74276. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74277. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  74278. var index;
  74279. var engine = _this._scene.getEngine();
  74280. if (depthOnlySubMeshes.length) {
  74281. engine.setColorWrite(false);
  74282. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74283. renderSubMesh(depthOnlySubMeshes.data[index]);
  74284. }
  74285. engine.setColorWrite(true);
  74286. }
  74287. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74288. renderSubMesh(opaqueSubMeshes.data[index]);
  74289. }
  74290. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74291. renderSubMesh(alphaTestSubMeshes.data[index]);
  74292. }
  74293. for (index = 0; index < transparentSubMeshes.length; index++) {
  74294. renderSubMesh(transparentSubMeshes.data[index]);
  74295. }
  74296. };
  74297. this._mainTexture.onClearObservable.add(function (engine) {
  74298. engine.clear(HighlightLayer.neutralColor, true, true, true);
  74299. });
  74300. };
  74301. /**
  74302. * Checks for the readiness of the element composing the layer.
  74303. * @param subMesh the mesh to check for
  74304. * @param useInstances specify wether or not to use instances to render the mesh
  74305. * @param emissiveTexture the associated emissive texture used to generate the glow
  74306. * @return true if ready otherwise, false
  74307. */
  74308. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  74309. var material = subMesh.getMaterial();
  74310. if (!material) {
  74311. return false;
  74312. }
  74313. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  74314. return false;
  74315. }
  74316. var defines = [];
  74317. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74318. var mesh = subMesh.getMesh();
  74319. var uv1 = false;
  74320. var uv2 = false;
  74321. // Alpha test
  74322. if (material && material.needAlphaTesting()) {
  74323. var alphaTexture = material.getAlphaTestTexture();
  74324. if (alphaTexture) {
  74325. defines.push("#define ALPHATEST");
  74326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  74327. alphaTexture.coordinatesIndex === 1) {
  74328. defines.push("#define DIFFUSEUV2");
  74329. uv2 = true;
  74330. }
  74331. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74332. defines.push("#define DIFFUSEUV1");
  74333. uv1 = true;
  74334. }
  74335. }
  74336. }
  74337. // Emissive
  74338. if (emissiveTexture) {
  74339. defines.push("#define EMISSIVE");
  74340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  74341. emissiveTexture.coordinatesIndex === 1) {
  74342. defines.push("#define EMISSIVEUV2");
  74343. uv2 = true;
  74344. }
  74345. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74346. defines.push("#define EMISSIVEUV1");
  74347. uv1 = true;
  74348. }
  74349. }
  74350. if (uv1) {
  74351. attribs.push(BABYLON.VertexBuffer.UVKind);
  74352. defines.push("#define UV1");
  74353. }
  74354. if (uv2) {
  74355. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74356. defines.push("#define UV2");
  74357. }
  74358. // Bones
  74359. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74362. if (mesh.numBoneInfluencers > 4) {
  74363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74365. }
  74366. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74367. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74368. }
  74369. else {
  74370. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74371. }
  74372. // Instances
  74373. if (useInstances) {
  74374. defines.push("#define INSTANCES");
  74375. attribs.push("world0");
  74376. attribs.push("world1");
  74377. attribs.push("world2");
  74378. attribs.push("world3");
  74379. }
  74380. // Get correct effect
  74381. var join = defines.join("\n");
  74382. if (this._cachedDefines !== join) {
  74383. this._cachedDefines = join;
  74384. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  74385. }
  74386. return this._glowMapGenerationEffect.isReady();
  74387. };
  74388. /**
  74389. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  74390. */
  74391. HighlightLayer.prototype.render = function () {
  74392. var currentEffect = this._glowMapMergeEffect;
  74393. // Check
  74394. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  74395. return;
  74396. var engine = this._scene.getEngine();
  74397. this.onBeforeComposeObservable.notifyObservers(this);
  74398. // Render
  74399. engine.enableEffect(currentEffect);
  74400. engine.setState(false);
  74401. // Cache
  74402. var previousStencilBuffer = engine.getStencilBuffer();
  74403. var previousStencilFunction = engine.getStencilFunction();
  74404. var previousStencilMask = engine.getStencilMask();
  74405. var previousStencilOperationPass = engine.getStencilOperationPass();
  74406. var previousStencilOperationFail = engine.getStencilOperationFail();
  74407. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  74408. var previousAlphaMode = engine.getAlphaMode();
  74409. // Texture
  74410. currentEffect.setTexture("textureSampler", this._blurTexture);
  74411. // VBOs
  74412. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  74413. // Stencil operations
  74414. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  74415. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  74416. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  74417. // Draw order
  74418. engine.setAlphaMode(this._options.alphaBlendingMode);
  74419. engine.setStencilMask(0x00);
  74420. engine.setStencilBuffer(true);
  74421. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  74422. if (this.outerGlow) {
  74423. currentEffect.setFloat("offset", 0);
  74424. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  74425. engine.draw(true, 0, 6);
  74426. }
  74427. if (this.innerGlow) {
  74428. currentEffect.setFloat("offset", 1);
  74429. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  74430. engine.draw(true, 0, 6);
  74431. }
  74432. // Restore Cache
  74433. engine.setStencilFunction(previousStencilFunction);
  74434. engine.setStencilMask(previousStencilMask);
  74435. engine.setAlphaMode(previousAlphaMode);
  74436. engine.setStencilBuffer(previousStencilBuffer);
  74437. engine.setStencilOperationPass(previousStencilOperationPass);
  74438. engine.setStencilOperationFail(previousStencilOperationFail);
  74439. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  74440. engine._stencilState.reset();
  74441. this.onAfterComposeObservable.notifyObservers(this);
  74442. // Handle size changes.
  74443. var size = this._mainTexture.getSize();
  74444. this.setMainTextureSize();
  74445. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  74446. // Recreate RTT and post processes on size change.
  74447. this.onSizeChangedObservable.notifyObservers(this);
  74448. this.disposeTextureAndPostProcesses();
  74449. this.createTextureAndPostProcesses();
  74450. }
  74451. };
  74452. /**
  74453. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  74454. * @param mesh The mesh to exclude from the highlight layer
  74455. */
  74456. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  74457. if (!this._excludedMeshes) {
  74458. return;
  74459. }
  74460. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  74461. if (!meshExcluded) {
  74462. this._excludedMeshes[mesh.uniqueId] = {
  74463. mesh: mesh,
  74464. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  74465. mesh.getEngine().setStencilBuffer(false);
  74466. }),
  74467. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  74468. mesh.getEngine().setStencilBuffer(true);
  74469. }),
  74470. };
  74471. }
  74472. };
  74473. /**
  74474. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  74475. * @param mesh The mesh to highlight
  74476. */
  74477. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  74478. if (!this._excludedMeshes) {
  74479. return;
  74480. }
  74481. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  74482. if (meshExcluded) {
  74483. if (meshExcluded.beforeRender) {
  74484. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  74485. }
  74486. if (meshExcluded.afterRender) {
  74487. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  74488. }
  74489. }
  74490. this._excludedMeshes[mesh.uniqueId] = null;
  74491. };
  74492. /**
  74493. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  74494. * @param mesh The mesh to highlight
  74495. * @param color The color of the highlight
  74496. * @param glowEmissiveOnly Extract the glow from the emissive texture
  74497. */
  74498. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  74499. var _this = this;
  74500. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  74501. if (!this._meshes) {
  74502. return;
  74503. }
  74504. var meshHighlight = this._meshes[mesh.uniqueId];
  74505. if (meshHighlight) {
  74506. meshHighlight.color = color;
  74507. }
  74508. else {
  74509. this._meshes[mesh.uniqueId] = {
  74510. mesh: mesh,
  74511. color: color,
  74512. // Lambda required for capture due to Observable this context
  74513. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  74514. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  74515. _this.defaultStencilReference(mesh);
  74516. }
  74517. else {
  74518. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  74519. }
  74520. }),
  74521. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  74522. glowEmissiveOnly: glowEmissiveOnly
  74523. };
  74524. }
  74525. this._shouldRender = true;
  74526. };
  74527. /**
  74528. * Remove a mesh from the highlight layer in order to make it stop glowing.
  74529. * @param mesh The mesh to highlight
  74530. */
  74531. HighlightLayer.prototype.removeMesh = function (mesh) {
  74532. if (!this._meshes) {
  74533. return;
  74534. }
  74535. var meshHighlight = this._meshes[mesh.uniqueId];
  74536. if (meshHighlight) {
  74537. if (meshHighlight.observerHighlight) {
  74538. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74539. }
  74540. if (meshHighlight.observerDefault) {
  74541. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74542. }
  74543. }
  74544. this._meshes[mesh.uniqueId] = null;
  74545. this._shouldRender = false;
  74546. for (var meshHighlightToCheck in this._meshes) {
  74547. if (meshHighlightToCheck) {
  74548. this._shouldRender = true;
  74549. break;
  74550. }
  74551. }
  74552. };
  74553. /**
  74554. * Returns true if the layer contains information to display, otherwise false.
  74555. */
  74556. HighlightLayer.prototype.shouldRender = function () {
  74557. return this.isEnabled && this._shouldRender;
  74558. };
  74559. /**
  74560. * Sets the main texture desired size which is the closest power of two
  74561. * of the engine canvas size.
  74562. */
  74563. HighlightLayer.prototype.setMainTextureSize = function () {
  74564. if (this._options.mainTextureFixedSize) {
  74565. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  74566. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  74567. }
  74568. else {
  74569. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  74570. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  74571. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  74572. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  74573. }
  74574. };
  74575. /**
  74576. * Force the stencil to the normal expected value for none glowing parts
  74577. */
  74578. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  74579. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  74580. };
  74581. /**
  74582. * Dispose only the render target textures and post process.
  74583. */
  74584. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  74585. this._blurTexture.dispose();
  74586. this._mainTexture.dispose();
  74587. this._downSamplePostprocess.dispose();
  74588. this._horizontalBlurPostprocess.dispose();
  74589. this._verticalBlurPostprocess.dispose();
  74590. };
  74591. /**
  74592. * Dispose the highlight layer and free resources.
  74593. */
  74594. HighlightLayer.prototype.dispose = function () {
  74595. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74596. if (vertexBuffer) {
  74597. vertexBuffer.dispose();
  74598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74599. }
  74600. if (this._indexBuffer) {
  74601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74602. this._indexBuffer = null;
  74603. }
  74604. // Clean textures and post processes
  74605. this.disposeTextureAndPostProcesses();
  74606. if (this._meshes) {
  74607. // Clean mesh references
  74608. for (var id in this._meshes) {
  74609. var meshHighlight = this._meshes[id];
  74610. if (meshHighlight && meshHighlight.mesh) {
  74611. if (meshHighlight.observerHighlight) {
  74612. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74613. }
  74614. if (meshHighlight.observerDefault) {
  74615. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74616. }
  74617. }
  74618. }
  74619. this._meshes = null;
  74620. }
  74621. if (this._excludedMeshes) {
  74622. for (var id in this._excludedMeshes) {
  74623. var meshHighlight = this._excludedMeshes[id];
  74624. if (meshHighlight) {
  74625. if (meshHighlight.beforeRender) {
  74626. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  74627. }
  74628. if (meshHighlight.afterRender) {
  74629. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  74630. }
  74631. }
  74632. }
  74633. this._excludedMeshes = null;
  74634. }
  74635. // Remove from scene
  74636. var index = this._scene.highlightLayers.indexOf(this, 0);
  74637. if (index > -1) {
  74638. this._scene.highlightLayers.splice(index, 1);
  74639. }
  74640. // Callback
  74641. this.onDisposeObservable.notifyObservers(this);
  74642. this.onDisposeObservable.clear();
  74643. this.onBeforeRenderMainTextureObservable.clear();
  74644. this.onBeforeBlurObservable.clear();
  74645. this.onBeforeComposeObservable.clear();
  74646. this.onAfterComposeObservable.clear();
  74647. this.onSizeChangedObservable.clear();
  74648. };
  74649. /**
  74650. * The neutral color used during the preparation of the glow effect.
  74651. * This is black by default as the blend operation is a blend operation.
  74652. */
  74653. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  74654. /**
  74655. * Stencil value used for glowing meshes.
  74656. */
  74657. HighlightLayer.glowingMeshStencilReference = 0x02;
  74658. /**
  74659. * Stencil value used for the other meshes in the scene.
  74660. */
  74661. HighlightLayer.normalMeshStencilReference = 0x01;
  74662. return HighlightLayer;
  74663. }());
  74664. BABYLON.HighlightLayer = HighlightLayer;
  74665. })(BABYLON || (BABYLON = {}));
  74666. //# sourceMappingURL=babylon.highlightlayer.js.map
  74667. var BABYLON;
  74668. (function (BABYLON) {
  74669. var AssetTaskState;
  74670. (function (AssetTaskState) {
  74671. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  74672. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  74673. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  74674. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  74675. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  74676. var AbstractAssetTask = /** @class */ (function () {
  74677. function AbstractAssetTask(name) {
  74678. this.name = name;
  74679. this.isCompleted = false;
  74680. this.taskState = AssetTaskState.INIT;
  74681. }
  74682. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74683. var _this = this;
  74684. this.taskState = AssetTaskState.RUNNING;
  74685. this.runTask(scene, function () {
  74686. _this.onDoneCallback(onSuccess, onError);
  74687. }, function (msg, exception) {
  74688. _this.onErrorCallback(onError, msg, exception);
  74689. });
  74690. };
  74691. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74692. throw new Error("runTask is not implemented");
  74693. };
  74694. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  74695. this.taskState = AssetTaskState.ERROR;
  74696. this.errorObject = {
  74697. message: message,
  74698. exception: exception
  74699. };
  74700. if (this.onError) {
  74701. this.onError(this, message, exception);
  74702. }
  74703. onError();
  74704. };
  74705. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  74706. try {
  74707. this.taskState = AssetTaskState.DONE;
  74708. this.isCompleted = true;
  74709. if (this.onSuccess) {
  74710. this.onSuccess(this);
  74711. }
  74712. onSuccess();
  74713. }
  74714. catch (e) {
  74715. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  74716. }
  74717. };
  74718. return AbstractAssetTask;
  74719. }());
  74720. BABYLON.AbstractAssetTask = AbstractAssetTask;
  74721. var AssetsProgressEvent = /** @class */ (function () {
  74722. function AssetsProgressEvent(remainingCount, totalCount, task) {
  74723. this.remainingCount = remainingCount;
  74724. this.totalCount = totalCount;
  74725. this.task = task;
  74726. }
  74727. return AssetsProgressEvent;
  74728. }());
  74729. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  74730. var MeshAssetTask = /** @class */ (function (_super) {
  74731. __extends(MeshAssetTask, _super);
  74732. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  74733. var _this = _super.call(this, name) || this;
  74734. _this.name = name;
  74735. _this.meshesNames = meshesNames;
  74736. _this.rootUrl = rootUrl;
  74737. _this.sceneFilename = sceneFilename;
  74738. return _this;
  74739. }
  74740. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74741. var _this = this;
  74742. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  74743. _this.loadedMeshes = meshes;
  74744. _this.loadedParticleSystems = particleSystems;
  74745. _this.loadedSkeletons = skeletons;
  74746. onSuccess();
  74747. }, null, function (scene, message, exception) {
  74748. onError(message, exception);
  74749. });
  74750. };
  74751. return MeshAssetTask;
  74752. }(AbstractAssetTask));
  74753. BABYLON.MeshAssetTask = MeshAssetTask;
  74754. var TextFileAssetTask = /** @class */ (function (_super) {
  74755. __extends(TextFileAssetTask, _super);
  74756. function TextFileAssetTask(name, url) {
  74757. var _this = _super.call(this, name) || this;
  74758. _this.name = name;
  74759. _this.url = url;
  74760. return _this;
  74761. }
  74762. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74763. var _this = this;
  74764. BABYLON.Tools.LoadFile(this.url, function (data) {
  74765. _this.text = data;
  74766. onSuccess();
  74767. }, undefined, scene.database, false, function (request, exception) {
  74768. if (request) {
  74769. onError(request.status + " " + request.statusText, exception);
  74770. }
  74771. });
  74772. };
  74773. return TextFileAssetTask;
  74774. }(AbstractAssetTask));
  74775. BABYLON.TextFileAssetTask = TextFileAssetTask;
  74776. var BinaryFileAssetTask = /** @class */ (function (_super) {
  74777. __extends(BinaryFileAssetTask, _super);
  74778. function BinaryFileAssetTask(name, url) {
  74779. var _this = _super.call(this, name) || this;
  74780. _this.name = name;
  74781. _this.url = url;
  74782. return _this;
  74783. }
  74784. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74785. var _this = this;
  74786. BABYLON.Tools.LoadFile(this.url, function (data) {
  74787. _this.data = data;
  74788. onSuccess();
  74789. }, undefined, scene.database, true, function (request, exception) {
  74790. if (request) {
  74791. onError(request.status + " " + request.statusText, exception);
  74792. }
  74793. });
  74794. };
  74795. return BinaryFileAssetTask;
  74796. }(AbstractAssetTask));
  74797. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  74798. var ImageAssetTask = /** @class */ (function (_super) {
  74799. __extends(ImageAssetTask, _super);
  74800. function ImageAssetTask(name, url) {
  74801. var _this = _super.call(this, name) || this;
  74802. _this.name = name;
  74803. _this.url = url;
  74804. return _this;
  74805. }
  74806. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74807. var _this = this;
  74808. var img = new Image();
  74809. BABYLON.Tools.SetCorsBehavior(this.url, img);
  74810. img.onload = function () {
  74811. _this.image = img;
  74812. onSuccess();
  74813. };
  74814. img.onerror = function (err) {
  74815. onError("Error loading image", err);
  74816. };
  74817. img.src = this.url;
  74818. };
  74819. return ImageAssetTask;
  74820. }(AbstractAssetTask));
  74821. BABYLON.ImageAssetTask = ImageAssetTask;
  74822. var TextureAssetTask = /** @class */ (function (_super) {
  74823. __extends(TextureAssetTask, _super);
  74824. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  74825. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74826. var _this = _super.call(this, name) || this;
  74827. _this.name = name;
  74828. _this.url = url;
  74829. _this.noMipmap = noMipmap;
  74830. _this.invertY = invertY;
  74831. _this.samplingMode = samplingMode;
  74832. return _this;
  74833. }
  74834. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74835. var onload = function () {
  74836. onSuccess();
  74837. };
  74838. var onerror = function (message, exception) {
  74839. onError(message, exception);
  74840. };
  74841. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  74842. };
  74843. return TextureAssetTask;
  74844. }(AbstractAssetTask));
  74845. BABYLON.TextureAssetTask = TextureAssetTask;
  74846. var CubeTextureAssetTask = /** @class */ (function (_super) {
  74847. __extends(CubeTextureAssetTask, _super);
  74848. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  74849. var _this = _super.call(this, name) || this;
  74850. _this.name = name;
  74851. _this.url = url;
  74852. _this.extensions = extensions;
  74853. _this.noMipmap = noMipmap;
  74854. _this.files = files;
  74855. return _this;
  74856. }
  74857. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74858. var onload = function () {
  74859. onSuccess();
  74860. };
  74861. var onerror = function (message, exception) {
  74862. onError(message, exception);
  74863. };
  74864. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  74865. };
  74866. return CubeTextureAssetTask;
  74867. }(AbstractAssetTask));
  74868. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  74869. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  74870. __extends(HDRCubeTextureAssetTask, _super);
  74871. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  74872. if (noMipmap === void 0) { noMipmap = false; }
  74873. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74874. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74875. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74876. var _this = _super.call(this, name) || this;
  74877. _this.name = name;
  74878. _this.url = url;
  74879. _this.size = size;
  74880. _this.noMipmap = noMipmap;
  74881. _this.generateHarmonics = generateHarmonics;
  74882. _this.useInGammaSpace = useInGammaSpace;
  74883. _this.usePMREMGenerator = usePMREMGenerator;
  74884. return _this;
  74885. }
  74886. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74887. var onload = function () {
  74888. onSuccess();
  74889. };
  74890. var onerror = function (message, exception) {
  74891. onError(message, exception);
  74892. };
  74893. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  74894. };
  74895. return HDRCubeTextureAssetTask;
  74896. }(AbstractAssetTask));
  74897. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  74898. var AssetsManager = /** @class */ (function () {
  74899. function AssetsManager(scene) {
  74900. this.tasks = new Array();
  74901. this.waitingTasksCount = 0;
  74902. //Observables
  74903. this.onTaskSuccessObservable = new BABYLON.Observable();
  74904. this.onTaskErrorObservable = new BABYLON.Observable();
  74905. this.onTasksDoneObservable = new BABYLON.Observable();
  74906. this.onProgressObservable = new BABYLON.Observable();
  74907. this.useDefaultLoadingScreen = true;
  74908. this._scene = scene;
  74909. }
  74910. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  74911. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  74912. this.tasks.push(task);
  74913. return task;
  74914. };
  74915. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  74916. var task = new TextFileAssetTask(taskName, url);
  74917. this.tasks.push(task);
  74918. return task;
  74919. };
  74920. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  74921. var task = new BinaryFileAssetTask(taskName, url);
  74922. this.tasks.push(task);
  74923. return task;
  74924. };
  74925. AssetsManager.prototype.addImageTask = function (taskName, url) {
  74926. var task = new ImageAssetTask(taskName, url);
  74927. this.tasks.push(task);
  74928. return task;
  74929. };
  74930. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  74931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74932. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  74933. this.tasks.push(task);
  74934. return task;
  74935. };
  74936. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  74937. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  74938. this.tasks.push(task);
  74939. return task;
  74940. };
  74941. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  74942. if (noMipmap === void 0) { noMipmap = false; }
  74943. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74944. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74945. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74946. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  74947. this.tasks.push(task);
  74948. return task;
  74949. };
  74950. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  74951. this.waitingTasksCount--;
  74952. try {
  74953. if (this.onProgress) {
  74954. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  74955. }
  74956. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  74957. }
  74958. catch (e) {
  74959. BABYLON.Tools.Error("Error running progress callbacks.");
  74960. console.log(e);
  74961. }
  74962. if (this.waitingTasksCount === 0) {
  74963. try {
  74964. if (this.onFinish) {
  74965. this.onFinish(this.tasks);
  74966. }
  74967. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74968. }
  74969. catch (e) {
  74970. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  74971. console.log(e);
  74972. }
  74973. this._scene.getEngine().hideLoadingUI();
  74974. }
  74975. };
  74976. AssetsManager.prototype._runTask = function (task) {
  74977. var _this = this;
  74978. var done = function () {
  74979. try {
  74980. if (_this.onTaskSuccess) {
  74981. _this.onTaskSuccess(task);
  74982. }
  74983. _this.onTaskSuccessObservable.notifyObservers(task);
  74984. _this._decreaseWaitingTasksCount(task);
  74985. }
  74986. catch (e) {
  74987. error("Error executing task success callbacks", e);
  74988. }
  74989. };
  74990. var error = function (message, exception) {
  74991. task.errorObject = task.errorObject || {
  74992. message: message,
  74993. exception: exception
  74994. };
  74995. if (_this.onTaskError) {
  74996. _this.onTaskError(task);
  74997. }
  74998. _this.onTaskErrorObservable.notifyObservers(task);
  74999. _this._decreaseWaitingTasksCount(task);
  75000. };
  75001. task.run(this._scene, done, error);
  75002. };
  75003. AssetsManager.prototype.reset = function () {
  75004. this.tasks = new Array();
  75005. return this;
  75006. };
  75007. AssetsManager.prototype.load = function () {
  75008. this.waitingTasksCount = this.tasks.length;
  75009. if (this.waitingTasksCount === 0) {
  75010. if (this.onFinish) {
  75011. this.onFinish(this.tasks);
  75012. }
  75013. this.onTasksDoneObservable.notifyObservers(this.tasks);
  75014. return this;
  75015. }
  75016. if (this.useDefaultLoadingScreen) {
  75017. this._scene.getEngine().displayLoadingUI();
  75018. }
  75019. for (var index = 0; index < this.tasks.length; index++) {
  75020. var task = this.tasks[index];
  75021. this._runTask(task);
  75022. }
  75023. return this;
  75024. };
  75025. return AssetsManager;
  75026. }());
  75027. BABYLON.AssetsManager = AssetsManager;
  75028. })(BABYLON || (BABYLON = {}));
  75029. //# sourceMappingURL=babylon.assetsManager.js.map
  75030. var BABYLON;
  75031. (function (BABYLON) {
  75032. var serializedGeometries = [];
  75033. var serializeGeometry = function (geometry, serializationGeometries) {
  75034. if (serializedGeometries[geometry.id]) {
  75035. return;
  75036. }
  75037. if (geometry.doNotSerialize) {
  75038. return;
  75039. }
  75040. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  75041. serializationGeometries.boxes.push(geometry.serialize());
  75042. }
  75043. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  75044. serializationGeometries.spheres.push(geometry.serialize());
  75045. }
  75046. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  75047. serializationGeometries.cylinders.push(geometry.serialize());
  75048. }
  75049. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  75050. serializationGeometries.toruses.push(geometry.serialize());
  75051. }
  75052. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  75053. serializationGeometries.grounds.push(geometry.serialize());
  75054. }
  75055. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  75056. serializationGeometries.planes.push(geometry.serialize());
  75057. }
  75058. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  75059. serializationGeometries.torusKnots.push(geometry.serialize());
  75060. }
  75061. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  75062. throw new Error("Unknown primitive type");
  75063. }
  75064. else {
  75065. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  75066. }
  75067. serializedGeometries[geometry.id] = true;
  75068. };
  75069. var serializeMesh = function (mesh, serializationScene) {
  75070. var serializationObject = {};
  75071. // Geometry
  75072. var geometry = mesh._geometry;
  75073. if (geometry) {
  75074. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  75075. // 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
  75076. serializeGeometry(geometry, serializationScene.geometries);
  75077. }
  75078. }
  75079. // Custom
  75080. if (mesh.serialize) {
  75081. mesh.serialize(serializationObject);
  75082. }
  75083. return serializationObject;
  75084. };
  75085. var finalizeSingleMesh = function (mesh, serializationObject) {
  75086. //only works if the mesh is already loaded
  75087. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75088. //serialize material
  75089. if (mesh.material) {
  75090. if (mesh.material instanceof BABYLON.StandardMaterial) {
  75091. serializationObject.materials = serializationObject.materials || [];
  75092. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75093. serializationObject.materials.push(mesh.material.serialize());
  75094. }
  75095. }
  75096. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  75097. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  75098. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75099. serializationObject.multiMaterials.push(mesh.material.serialize());
  75100. }
  75101. }
  75102. }
  75103. //serialize geometry
  75104. var geometry = mesh._geometry;
  75105. if (geometry) {
  75106. if (!serializationObject.geometries) {
  75107. serializationObject.geometries = {};
  75108. serializationObject.geometries.boxes = [];
  75109. serializationObject.geometries.spheres = [];
  75110. serializationObject.geometries.cylinders = [];
  75111. serializationObject.geometries.toruses = [];
  75112. serializationObject.geometries.grounds = [];
  75113. serializationObject.geometries.planes = [];
  75114. serializationObject.geometries.torusKnots = [];
  75115. serializationObject.geometries.vertexData = [];
  75116. }
  75117. serializeGeometry(geometry, serializationObject.geometries);
  75118. }
  75119. // Skeletons
  75120. if (mesh.skeleton) {
  75121. serializationObject.skeletons = serializationObject.skeletons || [];
  75122. serializationObject.skeletons.push(mesh.skeleton.serialize());
  75123. }
  75124. //serialize the actual mesh
  75125. serializationObject.meshes = serializationObject.meshes || [];
  75126. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75127. }
  75128. };
  75129. var SceneSerializer = /** @class */ (function () {
  75130. function SceneSerializer() {
  75131. }
  75132. SceneSerializer.ClearCache = function () {
  75133. serializedGeometries = [];
  75134. };
  75135. SceneSerializer.Serialize = function (scene) {
  75136. var serializationObject = {};
  75137. SceneSerializer.ClearCache();
  75138. // Scene
  75139. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  75140. serializationObject.autoClear = scene.autoClear;
  75141. serializationObject.clearColor = scene.clearColor.asArray();
  75142. serializationObject.ambientColor = scene.ambientColor.asArray();
  75143. serializationObject.gravity = scene.gravity.asArray();
  75144. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  75145. serializationObject.workerCollisions = scene.workerCollisions;
  75146. // Fog
  75147. if (scene.fogMode && scene.fogMode !== 0) {
  75148. serializationObject.fogMode = scene.fogMode;
  75149. serializationObject.fogColor = scene.fogColor.asArray();
  75150. serializationObject.fogStart = scene.fogStart;
  75151. serializationObject.fogEnd = scene.fogEnd;
  75152. serializationObject.fogDensity = scene.fogDensity;
  75153. }
  75154. //Physics
  75155. if (scene.isPhysicsEnabled()) {
  75156. var physicEngine = scene.getPhysicsEngine();
  75157. if (physicEngine) {
  75158. serializationObject.physicsEnabled = true;
  75159. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  75160. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  75161. }
  75162. }
  75163. // Metadata
  75164. if (scene.metadata) {
  75165. serializationObject.metadata = scene.metadata;
  75166. }
  75167. // Morph targets
  75168. serializationObject.morphTargetManagers = [];
  75169. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  75170. var abstractMesh = _a[_i];
  75171. var manager = abstractMesh.morphTargetManager;
  75172. if (manager) {
  75173. serializationObject.morphTargetManagers.push(manager.serialize());
  75174. }
  75175. }
  75176. // Lights
  75177. serializationObject.lights = [];
  75178. var index;
  75179. var light;
  75180. for (index = 0; index < scene.lights.length; index++) {
  75181. light = scene.lights[index];
  75182. if (!light.doNotSerialize) {
  75183. serializationObject.lights.push(light.serialize());
  75184. }
  75185. }
  75186. // Cameras
  75187. serializationObject.cameras = [];
  75188. for (index = 0; index < scene.cameras.length; index++) {
  75189. var camera = scene.cameras[index];
  75190. if (!camera.doNotSerialize) {
  75191. serializationObject.cameras.push(camera.serialize());
  75192. }
  75193. }
  75194. if (scene.activeCamera) {
  75195. serializationObject.activeCameraID = scene.activeCamera.id;
  75196. }
  75197. // Animations
  75198. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  75199. // Materials
  75200. serializationObject.materials = [];
  75201. serializationObject.multiMaterials = [];
  75202. var material;
  75203. for (index = 0; index < scene.materials.length; index++) {
  75204. material = scene.materials[index];
  75205. if (!material.doNotSerialize) {
  75206. serializationObject.materials.push(material.serialize());
  75207. }
  75208. }
  75209. // MultiMaterials
  75210. serializationObject.multiMaterials = [];
  75211. for (index = 0; index < scene.multiMaterials.length; index++) {
  75212. var multiMaterial = scene.multiMaterials[index];
  75213. serializationObject.multiMaterials.push(multiMaterial.serialize());
  75214. }
  75215. // Skeletons
  75216. serializationObject.skeletons = [];
  75217. for (index = 0; index < scene.skeletons.length; index++) {
  75218. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  75219. }
  75220. // Transform nodes
  75221. serializationObject.transformNodes = [];
  75222. for (index = 0; index < scene.transformNodes.length; index++) {
  75223. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  75224. }
  75225. // Geometries
  75226. serializationObject.geometries = {};
  75227. serializationObject.geometries.boxes = [];
  75228. serializationObject.geometries.spheres = [];
  75229. serializationObject.geometries.cylinders = [];
  75230. serializationObject.geometries.toruses = [];
  75231. serializationObject.geometries.grounds = [];
  75232. serializationObject.geometries.planes = [];
  75233. serializationObject.geometries.torusKnots = [];
  75234. serializationObject.geometries.vertexData = [];
  75235. serializedGeometries = [];
  75236. var geometries = scene.getGeometries();
  75237. for (index = 0; index < geometries.length; index++) {
  75238. var geometry = geometries[index];
  75239. if (geometry.isReady()) {
  75240. serializeGeometry(geometry, serializationObject.geometries);
  75241. }
  75242. }
  75243. // Meshes
  75244. serializationObject.meshes = [];
  75245. for (index = 0; index < scene.meshes.length; index++) {
  75246. var abstractMesh = scene.meshes[index];
  75247. if (abstractMesh instanceof BABYLON.Mesh) {
  75248. var mesh = abstractMesh;
  75249. if (!mesh.doNotSerialize) {
  75250. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75251. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75252. }
  75253. }
  75254. }
  75255. }
  75256. // Particles Systems
  75257. serializationObject.particleSystems = [];
  75258. for (index = 0; index < scene.particleSystems.length; index++) {
  75259. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  75260. }
  75261. // Lens flares
  75262. serializationObject.lensFlareSystems = [];
  75263. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  75264. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  75265. }
  75266. // Shadows
  75267. serializationObject.shadowGenerators = [];
  75268. for (index = 0; index < scene.lights.length; index++) {
  75269. light = scene.lights[index];
  75270. var shadowGenerator = light.getShadowGenerator();
  75271. if (shadowGenerator) {
  75272. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75273. }
  75274. }
  75275. // Action Manager
  75276. if (scene.actionManager) {
  75277. serializationObject.actions = scene.actionManager.serialize("scene");
  75278. }
  75279. // Audio
  75280. serializationObject.sounds = [];
  75281. for (index = 0; index < scene.soundTracks.length; index++) {
  75282. var soundtrack = scene.soundTracks[index];
  75283. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  75284. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  75285. }
  75286. }
  75287. return serializationObject;
  75288. };
  75289. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  75290. if (withParents === void 0) { withParents = false; }
  75291. if (withChildren === void 0) { withChildren = false; }
  75292. var serializationObject = {};
  75293. SceneSerializer.ClearCache();
  75294. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  75295. if (withParents || withChildren) {
  75296. //deliberate for loop! not for each, appended should be processed as well.
  75297. for (var i = 0; i < toSerialize.length; ++i) {
  75298. if (withChildren) {
  75299. toSerialize[i].getDescendants().forEach(function (node) {
  75300. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  75301. toSerialize.push(node);
  75302. }
  75303. });
  75304. }
  75305. //make sure the array doesn't contain the object already
  75306. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  75307. toSerialize.push(toSerialize[i].parent);
  75308. }
  75309. }
  75310. }
  75311. toSerialize.forEach(function (mesh) {
  75312. finalizeSingleMesh(mesh, serializationObject);
  75313. });
  75314. return serializationObject;
  75315. };
  75316. return SceneSerializer;
  75317. }());
  75318. BABYLON.SceneSerializer = SceneSerializer;
  75319. })(BABYLON || (BABYLON = {}));
  75320. //# sourceMappingURL=babylon.sceneSerializer.js.map
  75321. var BABYLON;
  75322. (function (BABYLON) {
  75323. var ReflectionProbe = /** @class */ (function () {
  75324. function ReflectionProbe(name, size, scene, generateMipMaps) {
  75325. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75326. var _this = this;
  75327. this.name = name;
  75328. this._viewMatrix = BABYLON.Matrix.Identity();
  75329. this._target = BABYLON.Vector3.Zero();
  75330. this._add = BABYLON.Vector3.Zero();
  75331. this.invertYAxis = false;
  75332. this.position = BABYLON.Vector3.Zero();
  75333. this._scene = scene;
  75334. this._scene.reflectionProbes.push(this);
  75335. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  75336. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  75337. switch (faceIndex) {
  75338. case 0:
  75339. _this._add.copyFromFloats(1, 0, 0);
  75340. break;
  75341. case 1:
  75342. _this._add.copyFromFloats(-1, 0, 0);
  75343. break;
  75344. case 2:
  75345. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  75346. break;
  75347. case 3:
  75348. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  75349. break;
  75350. case 4:
  75351. _this._add.copyFromFloats(0, 0, 1);
  75352. break;
  75353. case 5:
  75354. _this._add.copyFromFloats(0, 0, -1);
  75355. break;
  75356. }
  75357. if (_this._attachedMesh) {
  75358. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  75359. }
  75360. _this.position.addToRef(_this._add, _this._target);
  75361. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  75362. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  75363. scene._forcedViewPosition = _this.position;
  75364. });
  75365. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  75366. scene._forcedViewPosition = null;
  75367. scene.updateTransformMatrix(true);
  75368. });
  75369. if (scene.activeCamera) {
  75370. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75371. }
  75372. }
  75373. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  75374. get: function () {
  75375. return this._renderTargetTexture.samples;
  75376. },
  75377. set: function (value) {
  75378. this._renderTargetTexture.samples = value;
  75379. },
  75380. enumerable: true,
  75381. configurable: true
  75382. });
  75383. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  75384. get: function () {
  75385. return this._renderTargetTexture.refreshRate;
  75386. },
  75387. set: function (value) {
  75388. this._renderTargetTexture.refreshRate = value;
  75389. },
  75390. enumerable: true,
  75391. configurable: true
  75392. });
  75393. ReflectionProbe.prototype.getScene = function () {
  75394. return this._scene;
  75395. };
  75396. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  75397. get: function () {
  75398. return this._renderTargetTexture;
  75399. },
  75400. enumerable: true,
  75401. configurable: true
  75402. });
  75403. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  75404. get: function () {
  75405. return this._renderTargetTexture.renderList;
  75406. },
  75407. enumerable: true,
  75408. configurable: true
  75409. });
  75410. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  75411. this._attachedMesh = mesh;
  75412. };
  75413. /**
  75414. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  75415. *
  75416. * @param renderingGroupId The rendering group id corresponding to its index
  75417. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  75418. */
  75419. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  75420. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  75421. };
  75422. ReflectionProbe.prototype.dispose = function () {
  75423. var index = this._scene.reflectionProbes.indexOf(this);
  75424. if (index !== -1) {
  75425. // Remove from the scene if found
  75426. this._scene.reflectionProbes.splice(index, 1);
  75427. }
  75428. if (this._renderTargetTexture) {
  75429. this._renderTargetTexture.dispose();
  75430. this._renderTargetTexture = null;
  75431. }
  75432. };
  75433. return ReflectionProbe;
  75434. }());
  75435. BABYLON.ReflectionProbe = ReflectionProbe;
  75436. })(BABYLON || (BABYLON = {}));
  75437. //# sourceMappingURL=babylon.reflectionProbe.js.map
  75438. var BABYLON;
  75439. (function (BABYLON) {
  75440. var Layer = /** @class */ (function () {
  75441. function Layer(name, imgUrl, scene, isBackground, color) {
  75442. this.name = name;
  75443. this.scale = new BABYLON.Vector2(1, 1);
  75444. this.offset = new BABYLON.Vector2(0, 0);
  75445. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  75446. this.layerMask = 0x0FFFFFFF;
  75447. this._vertexBuffers = {};
  75448. // Events
  75449. /**
  75450. * An event triggered when the layer is disposed.
  75451. * @type {BABYLON.Observable}
  75452. */
  75453. this.onDisposeObservable = new BABYLON.Observable();
  75454. /**
  75455. * An event triggered before rendering the scene
  75456. * @type {BABYLON.Observable}
  75457. */
  75458. this.onBeforeRenderObservable = new BABYLON.Observable();
  75459. /**
  75460. * An event triggered after rendering the scene
  75461. * @type {BABYLON.Observable}
  75462. */
  75463. this.onAfterRenderObservable = new BABYLON.Observable();
  75464. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  75465. this.isBackground = isBackground === undefined ? true : isBackground;
  75466. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  75467. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  75468. this._scene.layers.push(this);
  75469. var engine = this._scene.getEngine();
  75470. // VBO
  75471. var vertices = [];
  75472. vertices.push(1, 1);
  75473. vertices.push(-1, 1);
  75474. vertices.push(-1, -1);
  75475. vertices.push(1, -1);
  75476. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75478. this._createIndexBuffer();
  75479. // Effects
  75480. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  75481. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  75482. }
  75483. Object.defineProperty(Layer.prototype, "onDispose", {
  75484. set: function (callback) {
  75485. if (this._onDisposeObserver) {
  75486. this.onDisposeObservable.remove(this._onDisposeObserver);
  75487. }
  75488. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  75489. },
  75490. enumerable: true,
  75491. configurable: true
  75492. });
  75493. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  75494. set: function (callback) {
  75495. if (this._onBeforeRenderObserver) {
  75496. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75497. }
  75498. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75499. },
  75500. enumerable: true,
  75501. configurable: true
  75502. });
  75503. Object.defineProperty(Layer.prototype, "onAfterRender", {
  75504. set: function (callback) {
  75505. if (this._onAfterRenderObserver) {
  75506. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75507. }
  75508. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75509. },
  75510. enumerable: true,
  75511. configurable: true
  75512. });
  75513. Layer.prototype._createIndexBuffer = function () {
  75514. var engine = this._scene.getEngine();
  75515. // Indices
  75516. var indices = [];
  75517. indices.push(0);
  75518. indices.push(1);
  75519. indices.push(2);
  75520. indices.push(0);
  75521. indices.push(2);
  75522. indices.push(3);
  75523. this._indexBuffer = engine.createIndexBuffer(indices);
  75524. };
  75525. Layer.prototype._rebuild = function () {
  75526. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75527. if (vb) {
  75528. vb._rebuild();
  75529. }
  75530. this._createIndexBuffer();
  75531. };
  75532. Layer.prototype.render = function () {
  75533. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  75534. // Check
  75535. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  75536. return;
  75537. var engine = this._scene.getEngine();
  75538. this.onBeforeRenderObservable.notifyObservers(this);
  75539. // Render
  75540. engine.enableEffect(currentEffect);
  75541. engine.setState(false);
  75542. // Texture
  75543. currentEffect.setTexture("textureSampler", this.texture);
  75544. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  75545. // Color
  75546. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  75547. // Scale / offset
  75548. currentEffect.setVector2("offset", this.offset);
  75549. currentEffect.setVector2("scale", this.scale);
  75550. // VBOs
  75551. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75552. // Draw order
  75553. if (!this.alphaTest) {
  75554. engine.setAlphaMode(this.alphaBlendingMode);
  75555. engine.draw(true, 0, 6);
  75556. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75557. }
  75558. else {
  75559. engine.draw(true, 0, 6);
  75560. }
  75561. this.onAfterRenderObservable.notifyObservers(this);
  75562. };
  75563. Layer.prototype.dispose = function () {
  75564. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75565. if (vertexBuffer) {
  75566. vertexBuffer.dispose();
  75567. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75568. }
  75569. if (this._indexBuffer) {
  75570. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75571. this._indexBuffer = null;
  75572. }
  75573. if (this.texture) {
  75574. this.texture.dispose();
  75575. this.texture = null;
  75576. }
  75577. // Remove from scene
  75578. var index = this._scene.layers.indexOf(this);
  75579. this._scene.layers.splice(index, 1);
  75580. // Callback
  75581. this.onDisposeObservable.notifyObservers(this);
  75582. this.onDisposeObservable.clear();
  75583. this.onAfterRenderObservable.clear();
  75584. this.onBeforeRenderObservable.clear();
  75585. };
  75586. return Layer;
  75587. }());
  75588. BABYLON.Layer = Layer;
  75589. })(BABYLON || (BABYLON = {}));
  75590. //# sourceMappingURL=babylon.layer.js.map
  75591. var BABYLON;
  75592. (function (BABYLON) {
  75593. var TextureTools = /** @class */ (function () {
  75594. function TextureTools() {
  75595. }
  75596. /**
  75597. * Uses the GPU to create a copy texture rescaled at a given size
  75598. * @param texture Texture to copy from
  75599. * @param width Desired width
  75600. * @param height Desired height
  75601. * @return Generated texture
  75602. */
  75603. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  75604. if (useBilinearMode === void 0) { useBilinearMode = true; }
  75605. var scene = texture.getScene();
  75606. var engine = scene.getEngine();
  75607. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  75608. rtt.wrapU = texture.wrapU;
  75609. rtt.wrapV = texture.wrapV;
  75610. rtt.uOffset = texture.uOffset;
  75611. rtt.vOffset = texture.vOffset;
  75612. rtt.uScale = texture.uScale;
  75613. rtt.vScale = texture.vScale;
  75614. rtt.uAng = texture.uAng;
  75615. rtt.vAng = texture.vAng;
  75616. rtt.wAng = texture.wAng;
  75617. rtt.coordinatesIndex = texture.coordinatesIndex;
  75618. rtt.level = texture.level;
  75619. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  75620. rtt._texture.isReady = false;
  75621. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75622. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75623. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75624. passPostProcess.getEffect().executeWhenCompiled(function () {
  75625. passPostProcess.onApply = function (effect) {
  75626. effect.setTexture("textureSampler", texture);
  75627. };
  75628. var internalTexture = rtt.getInternalTexture();
  75629. if (internalTexture) {
  75630. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  75631. engine.unBindFramebuffer(internalTexture);
  75632. rtt.disposeFramebufferObjects();
  75633. passPostProcess.dispose();
  75634. internalTexture.isReady = true;
  75635. }
  75636. });
  75637. return rtt;
  75638. };
  75639. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  75640. if (!scene._environmentBRDFTexture) {
  75641. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75642. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75643. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75644. scene._environmentBRDFTexture = texture;
  75645. }
  75646. return scene._environmentBRDFTexture;
  75647. };
  75648. 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=";
  75649. return TextureTools;
  75650. }());
  75651. BABYLON.TextureTools = TextureTools;
  75652. })(BABYLON || (BABYLON = {}));
  75653. //# sourceMappingURL=babylon.textureTools.js.map
  75654. var BABYLON;
  75655. (function (BABYLON) {
  75656. var FramingBehavior = /** @class */ (function () {
  75657. function FramingBehavior() {
  75658. this._mode = FramingBehavior.FitFrustumSidesMode;
  75659. this._radiusScale = 1.0;
  75660. this._positionScale = 0.5;
  75661. this._defaultElevation = 0.3;
  75662. this._elevationReturnTime = 1500;
  75663. this._elevationReturnWaitTime = 1000;
  75664. this._zoomStopsAnimation = false;
  75665. this._framingTime = 1500;
  75666. this._isPointerDown = false;
  75667. this._lastInteractionTime = -Infinity;
  75668. // Framing control
  75669. this._animatables = new Array();
  75670. this._betaIsAnimating = false;
  75671. }
  75672. Object.defineProperty(FramingBehavior.prototype, "name", {
  75673. get: function () {
  75674. return "Framing";
  75675. },
  75676. enumerable: true,
  75677. configurable: true
  75678. });
  75679. Object.defineProperty(FramingBehavior.prototype, "mode", {
  75680. /**
  75681. * Gets current mode used by the behavior.
  75682. */
  75683. get: function () {
  75684. return this._mode;
  75685. },
  75686. /**
  75687. * Sets the current mode used by the behavior
  75688. */
  75689. set: function (mode) {
  75690. this._mode = mode;
  75691. },
  75692. enumerable: true,
  75693. configurable: true
  75694. });
  75695. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  75696. /**
  75697. * Gets the scale applied to the radius
  75698. */
  75699. get: function () {
  75700. return this._radiusScale;
  75701. },
  75702. /**
  75703. * Sets the scale applied to the radius (1 by default)
  75704. */
  75705. set: function (radius) {
  75706. this._radiusScale = radius;
  75707. },
  75708. enumerable: true,
  75709. configurable: true
  75710. });
  75711. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  75712. /**
  75713. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75714. */
  75715. get: function () {
  75716. return this._positionScale;
  75717. },
  75718. /**
  75719. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75720. */
  75721. set: function (scale) {
  75722. this._positionScale = scale;
  75723. },
  75724. enumerable: true,
  75725. configurable: true
  75726. });
  75727. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  75728. /**
  75729. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75730. * behaviour is triggered, in radians.
  75731. */
  75732. get: function () {
  75733. return this._defaultElevation;
  75734. },
  75735. /**
  75736. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75737. * behaviour is triggered, in radians.
  75738. */
  75739. set: function (elevation) {
  75740. this._defaultElevation = elevation;
  75741. },
  75742. enumerable: true,
  75743. configurable: true
  75744. });
  75745. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  75746. /**
  75747. * Gets the time (in milliseconds) taken to return to the default beta position.
  75748. * Negative value indicates camera should not return to default.
  75749. */
  75750. get: function () {
  75751. return this._elevationReturnTime;
  75752. },
  75753. /**
  75754. * Sets the time (in milliseconds) taken to return to the default beta position.
  75755. * Negative value indicates camera should not return to default.
  75756. */
  75757. set: function (speed) {
  75758. this._elevationReturnTime = speed;
  75759. },
  75760. enumerable: true,
  75761. configurable: true
  75762. });
  75763. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  75764. /**
  75765. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75766. */
  75767. get: function () {
  75768. return this._elevationReturnWaitTime;
  75769. },
  75770. /**
  75771. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75772. */
  75773. set: function (time) {
  75774. this._elevationReturnWaitTime = time;
  75775. },
  75776. enumerable: true,
  75777. configurable: true
  75778. });
  75779. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  75780. /**
  75781. * Gets the flag that indicates if user zooming should stop animation.
  75782. */
  75783. get: function () {
  75784. return this._zoomStopsAnimation;
  75785. },
  75786. /**
  75787. * Sets the flag that indicates if user zooming should stop animation.
  75788. */
  75789. set: function (flag) {
  75790. this._zoomStopsAnimation = flag;
  75791. },
  75792. enumerable: true,
  75793. configurable: true
  75794. });
  75795. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  75796. /**
  75797. * Gets the transition time when framing the mesh, in milliseconds
  75798. */
  75799. get: function () {
  75800. return this._framingTime;
  75801. },
  75802. /**
  75803. * Sets the transition time when framing the mesh, in milliseconds
  75804. */
  75805. set: function (time) {
  75806. this._framingTime = time;
  75807. },
  75808. enumerable: true,
  75809. configurable: true
  75810. });
  75811. FramingBehavior.prototype.init = function () {
  75812. // Do notihng
  75813. };
  75814. FramingBehavior.prototype.attach = function (camera) {
  75815. var _this = this;
  75816. this._attachedCamera = camera;
  75817. var scene = this._attachedCamera.getScene();
  75818. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  75819. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  75820. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75821. _this._isPointerDown = true;
  75822. return;
  75823. }
  75824. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  75825. _this._isPointerDown = false;
  75826. }
  75827. });
  75828. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  75829. if (mesh) {
  75830. _this.zoomOnMesh(mesh);
  75831. }
  75832. });
  75833. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75834. // Stop the animation if there is user interaction and the animation should stop for this interaction
  75835. _this._applyUserInteraction();
  75836. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  75837. // back to the default position after a given timeout
  75838. _this._maintainCameraAboveGround();
  75839. });
  75840. };
  75841. FramingBehavior.prototype.detach = function () {
  75842. if (!this._attachedCamera) {
  75843. return;
  75844. }
  75845. var scene = this._attachedCamera.getScene();
  75846. if (this._onPrePointerObservableObserver) {
  75847. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  75848. }
  75849. if (this._onAfterCheckInputsObserver) {
  75850. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75851. }
  75852. if (this._onMeshTargetChangedObserver) {
  75853. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75854. }
  75855. this._attachedCamera = null;
  75856. };
  75857. /**
  75858. * Targets the given mesh and updates zoom level accordingly.
  75859. * @param mesh The mesh to target.
  75860. * @param radius Optional. If a cached radius position already exists, overrides default.
  75861. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75862. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75863. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75864. */
  75865. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  75866. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75867. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75868. mesh.computeWorldMatrix(true);
  75869. var boundingBox = mesh.getBoundingInfo().boundingBox;
  75870. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  75871. };
  75872. /**
  75873. * Targets the given mesh with its children and updates zoom level accordingly.
  75874. * @param mesh The mesh to target.
  75875. * @param radius Optional. If a cached radius position already exists, overrides default.
  75876. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75877. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75878. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75879. */
  75880. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  75881. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75882. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75883. mesh.computeWorldMatrix(true);
  75884. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  75885. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  75886. };
  75887. /**
  75888. * Targets the given meshes with their children and updates zoom level accordingly.
  75889. * @param meshes The mesh to target.
  75890. * @param radius Optional. If a cached radius position already exists, overrides default.
  75891. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75892. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75893. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75894. */
  75895. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  75896. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75897. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75898. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75899. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  75900. for (var i = 0; i < meshes.length; i++) {
  75901. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  75902. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  75903. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  75904. }
  75905. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  75906. };
  75907. /**
  75908. * Targets the given mesh and updates zoom level accordingly.
  75909. * @param mesh The mesh to target.
  75910. * @param radius Optional. If a cached radius position already exists, overrides default.
  75911. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75912. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75913. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75914. */
  75915. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  75916. var _this = this;
  75917. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75918. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75919. var zoomTarget;
  75920. if (!this._attachedCamera) {
  75921. return;
  75922. }
  75923. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  75924. var bottom = minimumWorld.y;
  75925. var top = maximumWorld.y;
  75926. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  75927. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  75928. if (focusOnOriginXZ) {
  75929. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  75930. }
  75931. else {
  75932. var centerWorld = minimumWorld.add(radiusWorld);
  75933. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  75934. }
  75935. if (!this._vectorTransition) {
  75936. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  75937. }
  75938. this._betaIsAnimating = true;
  75939. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  75940. if (animatable) {
  75941. this._animatables.push(animatable);
  75942. }
  75943. // sets the radius and lower radius bounds
  75944. // Small delta ensures camera is not always at lower zoom limit.
  75945. var radius = 0;
  75946. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  75947. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  75948. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  75949. radius = position;
  75950. }
  75951. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  75952. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  75953. if (this._attachedCamera.lowerRadiusLimit === null) {
  75954. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  75955. }
  75956. }
  75957. // Set sensibilities
  75958. var extend = maximumWorld.subtract(minimumWorld).length();
  75959. this._attachedCamera.panningSensibility = 5000 / extend;
  75960. this._attachedCamera.wheelPrecision = 100 / radius;
  75961. // transition to new radius
  75962. if (!this._radiusTransition) {
  75963. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75964. }
  75965. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  75966. if (onAnimationEnd) {
  75967. onAnimationEnd();
  75968. }
  75969. if (_this._attachedCamera) {
  75970. _this._attachedCamera.storeState();
  75971. }
  75972. });
  75973. if (animatable) {
  75974. this._animatables.push(animatable);
  75975. }
  75976. };
  75977. /**
  75978. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  75979. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  75980. * frustum width.
  75981. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  75982. * to fully enclose the mesh in the viewing frustum.
  75983. */
  75984. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  75985. var size = maximumWorld.subtract(minimumWorld);
  75986. var boxVectorGlobalDiagonal = size.length();
  75987. var frustumSlope = this._getFrustumSlope();
  75988. // Formula for setting distance
  75989. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  75990. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  75991. // Horizon distance
  75992. var radius = radiusWithoutFraming * this._radiusScale;
  75993. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  75994. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  75995. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  75996. var camera = this._attachedCamera;
  75997. if (!camera) {
  75998. return 0;
  75999. }
  76000. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76001. // Don't exceed the requested limit
  76002. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  76003. }
  76004. // Don't exceed the upper radius limit
  76005. if (camera.upperRadiusLimit) {
  76006. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  76007. }
  76008. return distance;
  76009. };
  76010. /**
  76011. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  76012. * is automatically returned to its default position (expected to be above ground plane).
  76013. */
  76014. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  76015. var _this = this;
  76016. if (this._elevationReturnTime < 0) {
  76017. return;
  76018. }
  76019. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  76020. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  76021. var limitBeta = Math.PI * 0.5;
  76022. // Bring the camera back up if below the ground plane
  76023. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  76024. this._betaIsAnimating = true;
  76025. //Transition to new position
  76026. this.stopAllAnimations();
  76027. if (!this._betaTransition) {
  76028. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  76029. }
  76030. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  76031. _this._clearAnimationLocks();
  76032. _this.stopAllAnimations();
  76033. });
  76034. if (animatabe) {
  76035. this._animatables.push(animatabe);
  76036. }
  76037. }
  76038. };
  76039. /**
  76040. * Returns the frustum slope based on the canvas ratio and camera FOV
  76041. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  76042. */
  76043. FramingBehavior.prototype._getFrustumSlope = function () {
  76044. // Calculate the viewport ratio
  76045. // Aspect Ratio is Height/Width.
  76046. var camera = this._attachedCamera;
  76047. if (!camera) {
  76048. return BABYLON.Vector2.Zero();
  76049. }
  76050. var engine = camera.getScene().getEngine();
  76051. var aspectRatio = engine.getAspectRatio(camera);
  76052. // Camera FOV is the vertical field of view (top-bottom) in radians.
  76053. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  76054. var frustumSlopeY = Math.tan(camera.fov / 2);
  76055. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  76056. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  76057. // along the forward vector.
  76058. var frustumSlopeX = frustumSlopeY * aspectRatio;
  76059. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  76060. };
  76061. /**
  76062. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  76063. */
  76064. FramingBehavior.prototype._clearAnimationLocks = function () {
  76065. this._betaIsAnimating = false;
  76066. };
  76067. /**
  76068. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  76069. */
  76070. FramingBehavior.prototype._applyUserInteraction = function () {
  76071. if (this.isUserIsMoving) {
  76072. this._lastInteractionTime = BABYLON.Tools.Now;
  76073. this.stopAllAnimations();
  76074. this._clearAnimationLocks();
  76075. }
  76076. };
  76077. /**
  76078. * Stops and removes all animations that have been applied to the camera
  76079. */
  76080. FramingBehavior.prototype.stopAllAnimations = function () {
  76081. if (this._attachedCamera) {
  76082. this._attachedCamera.animations = [];
  76083. }
  76084. while (this._animatables.length) {
  76085. if (this._animatables[0]) {
  76086. this._animatables[0].onAnimationEnd = null;
  76087. this._animatables[0].stop();
  76088. }
  76089. this._animatables.shift();
  76090. }
  76091. };
  76092. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  76093. /**
  76094. * Gets a value indicating if the user is moving the camera
  76095. */
  76096. get: function () {
  76097. if (!this._attachedCamera) {
  76098. return false;
  76099. }
  76100. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76101. this._attachedCamera.inertialBetaOffset !== 0 ||
  76102. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76103. this._attachedCamera.inertialPanningX !== 0 ||
  76104. this._attachedCamera.inertialPanningY !== 0 ||
  76105. this._isPointerDown;
  76106. },
  76107. enumerable: true,
  76108. configurable: true
  76109. });
  76110. /**
  76111. * The easing function used by animations
  76112. */
  76113. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  76114. /**
  76115. * The easing mode used by animations
  76116. */
  76117. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  76118. // Statics
  76119. /**
  76120. * The camera can move all the way towards the mesh.
  76121. */
  76122. FramingBehavior.IgnoreBoundsSizeMode = 0;
  76123. /**
  76124. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  76125. */
  76126. FramingBehavior.FitFrustumSidesMode = 1;
  76127. return FramingBehavior;
  76128. }());
  76129. BABYLON.FramingBehavior = FramingBehavior;
  76130. })(BABYLON || (BABYLON = {}));
  76131. //# sourceMappingURL=babylon.framingBehavior.js.map
  76132. var BABYLON;
  76133. (function (BABYLON) {
  76134. /**
  76135. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  76136. */
  76137. var BouncingBehavior = /** @class */ (function () {
  76138. function BouncingBehavior() {
  76139. /**
  76140. * The duration of the animation, in milliseconds
  76141. */
  76142. this.transitionDuration = 450;
  76143. /**
  76144. * Length of the distance animated by the transition when lower radius is reached
  76145. */
  76146. this.lowerRadiusTransitionRange = 2;
  76147. /**
  76148. * Length of the distance animated by the transition when upper radius is reached
  76149. */
  76150. this.upperRadiusTransitionRange = -2;
  76151. this._autoTransitionRange = false;
  76152. // Animations
  76153. this._radiusIsAnimating = false;
  76154. this._radiusBounceTransition = null;
  76155. this._animatables = new Array();
  76156. }
  76157. Object.defineProperty(BouncingBehavior.prototype, "name", {
  76158. get: function () {
  76159. return "Bouncing";
  76160. },
  76161. enumerable: true,
  76162. configurable: true
  76163. });
  76164. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  76165. /**
  76166. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76167. */
  76168. get: function () {
  76169. return this._autoTransitionRange;
  76170. },
  76171. /**
  76172. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76173. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  76174. */
  76175. set: function (value) {
  76176. var _this = this;
  76177. if (this._autoTransitionRange === value) {
  76178. return;
  76179. }
  76180. this._autoTransitionRange = value;
  76181. var camera = this._attachedCamera;
  76182. if (!camera) {
  76183. return;
  76184. }
  76185. if (value) {
  76186. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76187. if (!mesh) {
  76188. return;
  76189. }
  76190. mesh.computeWorldMatrix(true);
  76191. var diagonal = mesh.getBoundingInfo().diagonalLength;
  76192. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  76193. _this.upperRadiusTransitionRange = diagonal * 0.05;
  76194. });
  76195. }
  76196. else if (this._onMeshTargetChangedObserver) {
  76197. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76198. }
  76199. },
  76200. enumerable: true,
  76201. configurable: true
  76202. });
  76203. BouncingBehavior.prototype.init = function () {
  76204. // Do notihng
  76205. };
  76206. BouncingBehavior.prototype.attach = function (camera) {
  76207. var _this = this;
  76208. this._attachedCamera = camera;
  76209. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76210. if (!_this._attachedCamera) {
  76211. return;
  76212. }
  76213. // Add the bounce animation to the lower radius limit
  76214. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  76215. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  76216. }
  76217. // Add the bounce animation to the upper radius limit
  76218. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  76219. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  76220. }
  76221. });
  76222. };
  76223. BouncingBehavior.prototype.detach = function () {
  76224. if (!this._attachedCamera) {
  76225. return;
  76226. }
  76227. if (this._onAfterCheckInputsObserver) {
  76228. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76229. }
  76230. if (this._onMeshTargetChangedObserver) {
  76231. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76232. }
  76233. this._attachedCamera = null;
  76234. };
  76235. /**
  76236. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  76237. * @param radiusLimit The limit to check against.
  76238. * @return Bool to indicate if at limit.
  76239. */
  76240. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  76241. if (!this._attachedCamera) {
  76242. return false;
  76243. }
  76244. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  76245. return true;
  76246. }
  76247. return false;
  76248. };
  76249. /**
  76250. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  76251. * @param radiusDelta The delta by which to animate to. Can be negative.
  76252. */
  76253. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  76254. var _this = this;
  76255. if (!this._attachedCamera) {
  76256. return;
  76257. }
  76258. if (!this._radiusBounceTransition) {
  76259. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  76260. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  76261. }
  76262. // Prevent zoom until bounce has completed
  76263. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  76264. this._attachedCamera.wheelPrecision = Infinity;
  76265. this._attachedCamera.inertialRadiusOffset = 0;
  76266. // Animate to the radius limit
  76267. this.stopAllAnimations();
  76268. this._radiusIsAnimating = true;
  76269. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  76270. if (animatable) {
  76271. this._animatables.push(animatable);
  76272. }
  76273. };
  76274. /**
  76275. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  76276. */
  76277. BouncingBehavior.prototype._clearAnimationLocks = function () {
  76278. this._radiusIsAnimating = false;
  76279. if (this._attachedCamera) {
  76280. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  76281. }
  76282. };
  76283. /**
  76284. * Stops and removes all animations that have been applied to the camera
  76285. */
  76286. BouncingBehavior.prototype.stopAllAnimations = function () {
  76287. if (this._attachedCamera) {
  76288. this._attachedCamera.animations = [];
  76289. }
  76290. while (this._animatables.length) {
  76291. this._animatables[0].onAnimationEnd = null;
  76292. this._animatables[0].stop();
  76293. this._animatables.shift();
  76294. }
  76295. };
  76296. /**
  76297. * The easing function used by animations
  76298. */
  76299. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  76300. /**
  76301. * The easing mode used by animations
  76302. */
  76303. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  76304. return BouncingBehavior;
  76305. }());
  76306. BABYLON.BouncingBehavior = BouncingBehavior;
  76307. })(BABYLON || (BABYLON = {}));
  76308. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  76309. var BABYLON;
  76310. (function (BABYLON) {
  76311. var AutoRotationBehavior = /** @class */ (function () {
  76312. function AutoRotationBehavior() {
  76313. this._zoomStopsAnimation = false;
  76314. this._idleRotationSpeed = 0.05;
  76315. this._idleRotationWaitTime = 2000;
  76316. this._idleRotationSpinupTime = 2000;
  76317. this._isPointerDown = false;
  76318. this._lastFrameTime = null;
  76319. this._lastInteractionTime = -Infinity;
  76320. this._cameraRotationSpeed = 0;
  76321. this._lastFrameRadius = 0;
  76322. }
  76323. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  76324. get: function () {
  76325. return "AutoRotation";
  76326. },
  76327. enumerable: true,
  76328. configurable: true
  76329. });
  76330. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  76331. /**
  76332. * Gets the flag that indicates if user zooming should stop animation.
  76333. */
  76334. get: function () {
  76335. return this._zoomStopsAnimation;
  76336. },
  76337. /**
  76338. * Sets the flag that indicates if user zooming should stop animation.
  76339. */
  76340. set: function (flag) {
  76341. this._zoomStopsAnimation = flag;
  76342. },
  76343. enumerable: true,
  76344. configurable: true
  76345. });
  76346. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  76347. /**
  76348. * Gets the default speed at which the camera rotates around the model.
  76349. */
  76350. get: function () {
  76351. return this._idleRotationSpeed;
  76352. },
  76353. /**
  76354. * Sets the default speed at which the camera rotates around the model.
  76355. */
  76356. set: function (speed) {
  76357. this._idleRotationSpeed = speed;
  76358. },
  76359. enumerable: true,
  76360. configurable: true
  76361. });
  76362. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  76363. /**
  76364. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  76365. */
  76366. get: function () {
  76367. return this._idleRotationWaitTime;
  76368. },
  76369. /**
  76370. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  76371. */
  76372. set: function (time) {
  76373. this._idleRotationWaitTime = time;
  76374. },
  76375. enumerable: true,
  76376. configurable: true
  76377. });
  76378. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  76379. /**
  76380. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  76381. */
  76382. get: function () {
  76383. return this._idleRotationSpinupTime;
  76384. },
  76385. /**
  76386. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  76387. */
  76388. set: function (time) {
  76389. this._idleRotationSpinupTime = time;
  76390. },
  76391. enumerable: true,
  76392. configurable: true
  76393. });
  76394. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  76395. /**
  76396. * Gets a value indicating if the camera is currently rotating because of this behavior
  76397. */
  76398. get: function () {
  76399. return Math.abs(this._cameraRotationSpeed) > 0;
  76400. },
  76401. enumerable: true,
  76402. configurable: true
  76403. });
  76404. AutoRotationBehavior.prototype.init = function () {
  76405. // Do notihng
  76406. };
  76407. AutoRotationBehavior.prototype.attach = function (camera) {
  76408. var _this = this;
  76409. this._attachedCamera = camera;
  76410. var scene = this._attachedCamera.getScene();
  76411. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  76412. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76413. _this._isPointerDown = true;
  76414. return;
  76415. }
  76416. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  76417. _this._isPointerDown = false;
  76418. }
  76419. });
  76420. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76421. var now = BABYLON.Tools.Now;
  76422. var dt = 0;
  76423. if (_this._lastFrameTime != null) {
  76424. dt = now - _this._lastFrameTime;
  76425. }
  76426. _this._lastFrameTime = now;
  76427. // Stop the animation if there is user interaction and the animation should stop for this interaction
  76428. _this._applyUserInteraction();
  76429. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  76430. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  76431. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  76432. // Step camera rotation by rotation speed
  76433. if (_this._attachedCamera) {
  76434. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  76435. }
  76436. });
  76437. };
  76438. AutoRotationBehavior.prototype.detach = function () {
  76439. if (!this._attachedCamera) {
  76440. return;
  76441. }
  76442. var scene = this._attachedCamera.getScene();
  76443. if (this._onPrePointerObservableObserver) {
  76444. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  76445. }
  76446. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76447. this._attachedCamera = null;
  76448. };
  76449. /**
  76450. * Returns true if user is scrolling.
  76451. * @return true if user is scrolling.
  76452. */
  76453. AutoRotationBehavior.prototype._userIsZooming = function () {
  76454. if (!this._attachedCamera) {
  76455. return false;
  76456. }
  76457. return this._attachedCamera.inertialRadiusOffset !== 0;
  76458. };
  76459. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  76460. if (!this._attachedCamera) {
  76461. return false;
  76462. }
  76463. var zoomHasHitLimit = false;
  76464. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  76465. zoomHasHitLimit = true;
  76466. }
  76467. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  76468. this._lastFrameRadius = this._attachedCamera.radius;
  76469. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  76470. };
  76471. /**
  76472. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  76473. */
  76474. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  76475. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  76476. this._lastInteractionTime = BABYLON.Tools.Now;
  76477. }
  76478. };
  76479. // Tools
  76480. AutoRotationBehavior.prototype._userIsMoving = function () {
  76481. if (!this._attachedCamera) {
  76482. return false;
  76483. }
  76484. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76485. this._attachedCamera.inertialBetaOffset !== 0 ||
  76486. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76487. this._attachedCamera.inertialPanningX !== 0 ||
  76488. this._attachedCamera.inertialPanningY !== 0 ||
  76489. this._isPointerDown;
  76490. };
  76491. return AutoRotationBehavior;
  76492. }());
  76493. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  76494. })(BABYLON || (BABYLON = {}));
  76495. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  76496. var BABYLON;
  76497. (function (BABYLON) {
  76498. var NullEngineOptions = /** @class */ (function () {
  76499. function NullEngineOptions() {
  76500. this.renderWidth = 512;
  76501. this.renderHeight = 256;
  76502. this.textureSize = 512;
  76503. }
  76504. return NullEngineOptions;
  76505. }());
  76506. BABYLON.NullEngineOptions = NullEngineOptions;
  76507. /**
  76508. * The null engine class provides support for headless version of babylon.js.
  76509. * This can be used in server side scenario or for testing purposes
  76510. */
  76511. var NullEngine = /** @class */ (function (_super) {
  76512. __extends(NullEngine, _super);
  76513. function NullEngine(options) {
  76514. if (options === void 0) { options = new NullEngineOptions(); }
  76515. var _this = _super.call(this, null) || this;
  76516. _this._options = options;
  76517. // Init caps
  76518. // We consider we are on a webgl1 capable device
  76519. _this._caps = new BABYLON.EngineCapabilities();
  76520. _this._caps.maxTexturesImageUnits = 16;
  76521. _this._caps.maxVertexTextureImageUnits = 16;
  76522. _this._caps.maxTextureSize = 512;
  76523. _this._caps.maxCubemapTextureSize = 512;
  76524. _this._caps.maxRenderTextureSize = 512;
  76525. _this._caps.maxVertexAttribs = 16;
  76526. _this._caps.maxVaryingVectors = 16;
  76527. _this._caps.maxFragmentUniformVectors = 16;
  76528. _this._caps.maxVertexUniformVectors = 16;
  76529. // Extensions
  76530. _this._caps.standardDerivatives = false;
  76531. _this._caps.astc = null;
  76532. _this._caps.s3tc = null;
  76533. _this._caps.pvrtc = null;
  76534. _this._caps.etc1 = null;
  76535. _this._caps.etc2 = null;
  76536. _this._caps.textureAnisotropicFilterExtension = null;
  76537. _this._caps.maxAnisotropy = 0;
  76538. _this._caps.uintIndices = false;
  76539. _this._caps.fragmentDepthSupported = false;
  76540. _this._caps.highPrecisionShaderSupported = true;
  76541. _this._caps.colorBufferFloat = false;
  76542. _this._caps.textureFloat = false;
  76543. _this._caps.textureFloatLinearFiltering = false;
  76544. _this._caps.textureFloatRender = false;
  76545. _this._caps.textureHalfFloat = false;
  76546. _this._caps.textureHalfFloatLinearFiltering = false;
  76547. _this._caps.textureHalfFloatRender = false;
  76548. _this._caps.textureLOD = false;
  76549. _this._caps.drawBuffersExtension = false;
  76550. _this._caps.depthTextureExtension = false;
  76551. _this._caps.vertexArrayObject = false;
  76552. _this._caps.instancedArrays = false;
  76553. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  76554. // Wrappers
  76555. if (typeof URL === "undefined") {
  76556. URL = {
  76557. createObjectURL: function () { },
  76558. revokeObjectURL: function () { }
  76559. };
  76560. }
  76561. if (typeof Blob === "undefined") {
  76562. Blob = function () { };
  76563. }
  76564. return _this;
  76565. }
  76566. NullEngine.prototype.createVertexBuffer = function (vertices) {
  76567. return {
  76568. capacity: 0,
  76569. references: 1,
  76570. is32Bits: false
  76571. };
  76572. };
  76573. NullEngine.prototype.createIndexBuffer = function (indices) {
  76574. return {
  76575. capacity: 0,
  76576. references: 1,
  76577. is32Bits: false
  76578. };
  76579. };
  76580. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  76581. if (stencil === void 0) { stencil = false; }
  76582. };
  76583. NullEngine.prototype.getRenderWidth = function (useScreen) {
  76584. if (useScreen === void 0) { useScreen = false; }
  76585. if (!useScreen && this._currentRenderTarget) {
  76586. return this._currentRenderTarget.width;
  76587. }
  76588. return this._options.renderWidth;
  76589. };
  76590. NullEngine.prototype.getRenderHeight = function (useScreen) {
  76591. if (useScreen === void 0) { useScreen = false; }
  76592. if (!useScreen && this._currentRenderTarget) {
  76593. return this._currentRenderTarget.height;
  76594. }
  76595. return this._options.renderHeight;
  76596. };
  76597. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  76598. this._cachedViewport = viewport;
  76599. };
  76600. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  76601. return {
  76602. transformFeedback: null,
  76603. __SPECTOR_rebuildProgram: null
  76604. };
  76605. };
  76606. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  76607. return [];
  76608. };
  76609. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  76610. return [];
  76611. };
  76612. NullEngine.prototype.bindSamplers = function (effect) {
  76613. this._currentEffect = null;
  76614. };
  76615. NullEngine.prototype.enableEffect = function (effect) {
  76616. this._currentEffect = effect;
  76617. if (effect.onBind) {
  76618. effect.onBind(effect);
  76619. }
  76620. effect.onBindObservable.notifyObservers(effect);
  76621. };
  76622. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  76623. if (zOffset === void 0) { zOffset = 0; }
  76624. if (reverseSide === void 0) { reverseSide = false; }
  76625. };
  76626. NullEngine.prototype.setIntArray = function (uniform, array) {
  76627. };
  76628. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  76629. };
  76630. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  76631. };
  76632. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  76633. };
  76634. NullEngine.prototype.setFloatArray = function (uniform, array) {
  76635. };
  76636. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  76637. };
  76638. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  76639. };
  76640. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  76641. };
  76642. NullEngine.prototype.setArray = function (uniform, array) {
  76643. };
  76644. NullEngine.prototype.setArray2 = function (uniform, array) {
  76645. };
  76646. NullEngine.prototype.setArray3 = function (uniform, array) {
  76647. };
  76648. NullEngine.prototype.setArray4 = function (uniform, array) {
  76649. };
  76650. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  76651. };
  76652. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  76653. };
  76654. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  76655. };
  76656. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  76657. };
  76658. NullEngine.prototype.setFloat = function (uniform, value) {
  76659. };
  76660. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  76661. };
  76662. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  76663. };
  76664. NullEngine.prototype.setBool = function (uniform, bool) {
  76665. };
  76666. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  76667. };
  76668. NullEngine.prototype.setColor3 = function (uniform, color3) {
  76669. };
  76670. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  76671. };
  76672. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  76673. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  76674. if (this._alphaMode === mode) {
  76675. return;
  76676. }
  76677. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  76678. if (!noDepthWriteChange) {
  76679. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  76680. }
  76681. this._alphaMode = mode;
  76682. };
  76683. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  76684. };
  76685. NullEngine.prototype.wipeCaches = function (bruteForce) {
  76686. if (this.preventCacheWipeBetweenFrames) {
  76687. return;
  76688. }
  76689. this.resetTextureCache();
  76690. this._currentEffect = null;
  76691. if (bruteForce) {
  76692. this._currentProgram = null;
  76693. this._stencilState.reset();
  76694. this._depthCullingState.reset();
  76695. this.setDepthFunctionToLessOrEqual();
  76696. this._alphaState.reset();
  76697. }
  76698. this._cachedVertexBuffers = null;
  76699. this._cachedIndexBuffer = null;
  76700. this._cachedEffectForVertexBuffers = null;
  76701. };
  76702. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  76703. };
  76704. NullEngine.prototype._createTexture = function () {
  76705. return {};
  76706. };
  76707. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  76708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76709. if (onLoad === void 0) { onLoad = null; }
  76710. if (onError === void 0) { onError = null; }
  76711. if (buffer === void 0) { buffer = null; }
  76712. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  76713. var url = String(urlArg);
  76714. texture.url = url;
  76715. texture.generateMipMaps = !noMipmap;
  76716. texture.samplingMode = samplingMode;
  76717. texture.invertY = invertY;
  76718. texture.baseWidth = this._options.textureSize;
  76719. texture.baseHeight = this._options.textureSize;
  76720. texture.width = this._options.textureSize;
  76721. texture.height = this._options.textureSize;
  76722. if (format) {
  76723. texture.format = format;
  76724. }
  76725. texture.isReady = true;
  76726. if (onLoad) {
  76727. onLoad();
  76728. }
  76729. return texture;
  76730. };
  76731. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  76732. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  76733. if (options !== undefined && typeof options === "object") {
  76734. fullOptions.generateMipMaps = options.generateMipMaps;
  76735. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  76736. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  76737. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  76738. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  76739. }
  76740. else {
  76741. fullOptions.generateMipMaps = options;
  76742. fullOptions.generateDepthBuffer = true;
  76743. fullOptions.generateStencilBuffer = false;
  76744. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76745. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  76746. }
  76747. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  76748. var width = size.width || size;
  76749. var height = size.height || size;
  76750. texture._depthStencilBuffer = {};
  76751. texture._framebuffer = {};
  76752. texture.baseWidth = width;
  76753. texture.baseHeight = height;
  76754. texture.width = width;
  76755. texture.height = height;
  76756. texture.isReady = true;
  76757. texture.samples = 1;
  76758. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  76759. texture.samplingMode = fullOptions.samplingMode;
  76760. texture.type = fullOptions.type;
  76761. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  76762. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  76763. return texture;
  76764. };
  76765. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  76766. texture.samplingMode = samplingMode;
  76767. };
  76768. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  76769. if (this._currentRenderTarget) {
  76770. this.unBindFramebuffer(this._currentRenderTarget);
  76771. }
  76772. this._currentRenderTarget = texture;
  76773. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  76774. if (this._cachedViewport && !forceFullscreenViewport) {
  76775. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  76776. }
  76777. };
  76778. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  76779. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  76780. this._currentRenderTarget = null;
  76781. if (onBeforeUnbind) {
  76782. if (texture._MSAAFramebuffer) {
  76783. this._currentFramebuffer = texture._framebuffer;
  76784. }
  76785. onBeforeUnbind();
  76786. }
  76787. this._currentFramebuffer = null;
  76788. };
  76789. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  76790. var vbo = {
  76791. capacity: 1,
  76792. references: 1,
  76793. is32Bits: false
  76794. };
  76795. return vbo;
  76796. };
  76797. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  76798. if (offset === void 0) { offset = 0; }
  76799. };
  76800. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  76801. };
  76802. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  76803. if (this._boundTexturesCache[this._activeTextureChannel] !== texture) {
  76804. this._boundTexturesCache[this._activeTextureChannel] = texture;
  76805. }
  76806. };
  76807. NullEngine.prototype._bindTexture = function (channel, texture) {
  76808. if (channel < 0) {
  76809. return;
  76810. }
  76811. this._bindTextureDirectly(0, texture);
  76812. };
  76813. NullEngine.prototype._releaseBuffer = function (buffer) {
  76814. buffer.references--;
  76815. if (buffer.references === 0) {
  76816. return true;
  76817. }
  76818. return false;
  76819. };
  76820. return NullEngine;
  76821. }(BABYLON.Engine));
  76822. BABYLON.NullEngine = NullEngine;
  76823. })(BABYLON || (BABYLON = {}));
  76824. //# sourceMappingURL=babylon.nullEngine.js.map
  76825. var BABYLON;
  76826. (function (BABYLON) {
  76827. /**
  76828. * This class can be used to get instrumentation data from a Babylon engine
  76829. */
  76830. var EngineInstrumentation = /** @class */ (function () {
  76831. function EngineInstrumentation(engine) {
  76832. this.engine = engine;
  76833. this._captureGPUFrameTime = false;
  76834. this._gpuFrameTime = new BABYLON.PerfCounter();
  76835. this._captureShaderCompilationTime = false;
  76836. this._shaderCompilationTime = new BABYLON.PerfCounter();
  76837. // Observers
  76838. this._onBeginFrameObserver = null;
  76839. this._onEndFrameObserver = null;
  76840. this._onBeforeShaderCompilationObserver = null;
  76841. this._onAfterShaderCompilationObserver = null;
  76842. }
  76843. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  76844. // Properties
  76845. /**
  76846. * Gets the perf counter used for GPU frame time
  76847. */
  76848. get: function () {
  76849. return this._gpuFrameTime;
  76850. },
  76851. enumerable: true,
  76852. configurable: true
  76853. });
  76854. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  76855. /**
  76856. * Gets the GPU frame time capture status
  76857. */
  76858. get: function () {
  76859. return this._captureGPUFrameTime;
  76860. },
  76861. /**
  76862. * Enable or disable the GPU frame time capture
  76863. */
  76864. set: function (value) {
  76865. var _this = this;
  76866. if (value === this._captureGPUFrameTime) {
  76867. return;
  76868. }
  76869. this._captureGPUFrameTime = value;
  76870. if (value) {
  76871. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  76872. if (!_this._gpuFrameTimeToken) {
  76873. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  76874. }
  76875. });
  76876. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  76877. if (!_this._gpuFrameTimeToken) {
  76878. return;
  76879. }
  76880. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  76881. if (time > -1) {
  76882. _this._gpuFrameTimeToken = null;
  76883. _this._gpuFrameTime.fetchNewFrame();
  76884. _this._gpuFrameTime.addCount(time, true);
  76885. }
  76886. });
  76887. }
  76888. else {
  76889. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76890. this._onBeginFrameObserver = null;
  76891. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76892. this._onEndFrameObserver = null;
  76893. }
  76894. },
  76895. enumerable: true,
  76896. configurable: true
  76897. });
  76898. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  76899. /**
  76900. * Gets the perf counter used for shader compilation time
  76901. */
  76902. get: function () {
  76903. return this._shaderCompilationTime;
  76904. },
  76905. enumerable: true,
  76906. configurable: true
  76907. });
  76908. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  76909. /**
  76910. * Gets the shader compilation time capture status
  76911. */
  76912. get: function () {
  76913. return this._captureShaderCompilationTime;
  76914. },
  76915. /**
  76916. * Enable or disable the shader compilation time capture
  76917. */
  76918. set: function (value) {
  76919. var _this = this;
  76920. if (value === this._captureShaderCompilationTime) {
  76921. return;
  76922. }
  76923. this._captureShaderCompilationTime = value;
  76924. if (value) {
  76925. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  76926. _this._shaderCompilationTime.fetchNewFrame();
  76927. _this._shaderCompilationTime.beginMonitoring();
  76928. });
  76929. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  76930. _this._shaderCompilationTime.endMonitoring();
  76931. });
  76932. }
  76933. else {
  76934. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76935. this._onBeforeShaderCompilationObserver = null;
  76936. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76937. this._onAfterShaderCompilationObserver = null;
  76938. }
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. EngineInstrumentation.prototype.dispose = function () {
  76944. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76945. this._onBeginFrameObserver = null;
  76946. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76947. this._onEndFrameObserver = null;
  76948. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76949. this._onBeforeShaderCompilationObserver = null;
  76950. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76951. this._onAfterShaderCompilationObserver = null;
  76952. this.engine = null;
  76953. };
  76954. return EngineInstrumentation;
  76955. }());
  76956. BABYLON.EngineInstrumentation = EngineInstrumentation;
  76957. })(BABYLON || (BABYLON = {}));
  76958. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  76959. var BABYLON;
  76960. (function (BABYLON) {
  76961. /**
  76962. * This class can be used to get instrumentation data from a Babylon engine
  76963. */
  76964. var SceneInstrumentation = /** @class */ (function () {
  76965. function SceneInstrumentation(scene) {
  76966. var _this = this;
  76967. this.scene = scene;
  76968. this._captureActiveMeshesEvaluationTime = false;
  76969. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  76970. this._captureRenderTargetsRenderTime = false;
  76971. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  76972. this._captureFrameTime = false;
  76973. this._frameTime = new BABYLON.PerfCounter();
  76974. this._captureRenderTime = false;
  76975. this._renderTime = new BABYLON.PerfCounter();
  76976. this._captureInterFrameTime = false;
  76977. this._interFrameTime = new BABYLON.PerfCounter();
  76978. this._captureParticlesRenderTime = false;
  76979. this._particlesRenderTime = new BABYLON.PerfCounter();
  76980. this._captureSpritesRenderTime = false;
  76981. this._spritesRenderTime = new BABYLON.PerfCounter();
  76982. this._capturePhysicsTime = false;
  76983. this._physicsTime = new BABYLON.PerfCounter();
  76984. this._captureAnimationsTime = false;
  76985. this._animationsTime = new BABYLON.PerfCounter();
  76986. // Observers
  76987. this._onBeforeActiveMeshesEvaluationObserver = null;
  76988. this._onAfterActiveMeshesEvaluationObserver = null;
  76989. this._onBeforeRenderTargetsRenderObserver = null;
  76990. this._onAfterRenderTargetsRenderObserver = null;
  76991. this._onAfterRenderObserver = null;
  76992. this._onBeforeDrawPhaseObserver = null;
  76993. this._onAfterDrawPhaseObserver = null;
  76994. this._onBeforeAnimationsObserver = null;
  76995. this._onBeforeParticlesRenderingObserver = null;
  76996. this._onAfterParticlesRenderingObserver = null;
  76997. this._onBeforeSpritesRenderingObserver = null;
  76998. this._onAfterSpritesRenderingObserver = null;
  76999. this._onBeforePhysicsObserver = null;
  77000. this._onAfterPhysicsObserver = null;
  77001. this._onAfterAnimationsObserver = null;
  77002. // Before render
  77003. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  77004. if (_this._captureActiveMeshesEvaluationTime) {
  77005. _this._activeMeshesEvaluationTime.fetchNewFrame();
  77006. }
  77007. if (_this._captureRenderTargetsRenderTime) {
  77008. _this._renderTargetsRenderTime.fetchNewFrame();
  77009. }
  77010. if (_this._captureFrameTime) {
  77011. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  77012. _this._frameTime.beginMonitoring();
  77013. }
  77014. if (_this._captureInterFrameTime) {
  77015. _this._interFrameTime.endMonitoring();
  77016. }
  77017. if (_this._captureParticlesRenderTime) {
  77018. _this._particlesRenderTime.fetchNewFrame();
  77019. }
  77020. if (_this._captureSpritesRenderTime) {
  77021. _this._spritesRenderTime.fetchNewFrame();
  77022. }
  77023. if (_this._captureAnimationsTime) {
  77024. _this._animationsTime.beginMonitoring();
  77025. }
  77026. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  77027. });
  77028. // After render
  77029. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  77030. if (_this._captureFrameTime) {
  77031. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  77032. _this._frameTime.endMonitoring();
  77033. }
  77034. if (_this._captureRenderTime) {
  77035. _this._renderTime.endMonitoring(false);
  77036. }
  77037. if (_this._captureInterFrameTime) {
  77038. _this._interFrameTime.beginMonitoring();
  77039. }
  77040. });
  77041. }
  77042. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  77043. // Properties
  77044. /**
  77045. * Gets the perf counter used for active meshes evaluation time
  77046. */
  77047. get: function () {
  77048. return this._activeMeshesEvaluationTime;
  77049. },
  77050. enumerable: true,
  77051. configurable: true
  77052. });
  77053. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  77054. /**
  77055. * Gets the active meshes evaluation time capture status
  77056. */
  77057. get: function () {
  77058. return this._captureActiveMeshesEvaluationTime;
  77059. },
  77060. /**
  77061. * Enable or disable the active meshes evaluation time capture
  77062. */
  77063. set: function (value) {
  77064. var _this = this;
  77065. if (value === this._captureActiveMeshesEvaluationTime) {
  77066. return;
  77067. }
  77068. this._captureActiveMeshesEvaluationTime = value;
  77069. if (value) {
  77070. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  77071. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  77072. _this._activeMeshesEvaluationTime.beginMonitoring();
  77073. });
  77074. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  77075. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  77076. _this._activeMeshesEvaluationTime.endMonitoring();
  77077. });
  77078. }
  77079. else {
  77080. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  77081. this._onBeforeActiveMeshesEvaluationObserver = null;
  77082. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  77083. this._onAfterActiveMeshesEvaluationObserver = null;
  77084. }
  77085. },
  77086. enumerable: true,
  77087. configurable: true
  77088. });
  77089. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  77090. /**
  77091. * Gets the perf counter used for render targets render time
  77092. */
  77093. get: function () {
  77094. return this._renderTargetsRenderTime;
  77095. },
  77096. enumerable: true,
  77097. configurable: true
  77098. });
  77099. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  77100. /**
  77101. * Gets the render targets render time capture status
  77102. */
  77103. get: function () {
  77104. return this._captureRenderTargetsRenderTime;
  77105. },
  77106. /**
  77107. * Enable or disable the render targets render time capture
  77108. */
  77109. set: function (value) {
  77110. var _this = this;
  77111. if (value === this._captureRenderTargetsRenderTime) {
  77112. return;
  77113. }
  77114. this._captureRenderTargetsRenderTime = value;
  77115. if (value) {
  77116. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  77117. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  77118. _this._renderTargetsRenderTime.beginMonitoring();
  77119. });
  77120. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  77121. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  77122. _this._renderTargetsRenderTime.endMonitoring(false);
  77123. });
  77124. }
  77125. else {
  77126. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  77127. this._onBeforeRenderTargetsRenderObserver = null;
  77128. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  77129. this._onAfterRenderTargetsRenderObserver = null;
  77130. }
  77131. },
  77132. enumerable: true,
  77133. configurable: true
  77134. });
  77135. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  77136. /**
  77137. * Gets the perf counter used for particles render time
  77138. */
  77139. get: function () {
  77140. return this._particlesRenderTime;
  77141. },
  77142. enumerable: true,
  77143. configurable: true
  77144. });
  77145. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  77146. /**
  77147. * Gets the particles render time capture status
  77148. */
  77149. get: function () {
  77150. return this._captureParticlesRenderTime;
  77151. },
  77152. /**
  77153. * Enable or disable the particles render time capture
  77154. */
  77155. set: function (value) {
  77156. var _this = this;
  77157. if (value === this._captureParticlesRenderTime) {
  77158. return;
  77159. }
  77160. this._captureParticlesRenderTime = value;
  77161. if (value) {
  77162. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  77163. BABYLON.Tools.StartPerformanceCounter("Particles");
  77164. _this._particlesRenderTime.beginMonitoring();
  77165. });
  77166. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  77167. BABYLON.Tools.EndPerformanceCounter("Particles");
  77168. _this._particlesRenderTime.endMonitoring(false);
  77169. });
  77170. }
  77171. else {
  77172. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77173. this._onBeforeParticlesRenderingObserver = null;
  77174. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77175. this._onAfterParticlesRenderingObserver = null;
  77176. }
  77177. },
  77178. enumerable: true,
  77179. configurable: true
  77180. });
  77181. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  77182. /**
  77183. * Gets the perf counter used for sprites render time
  77184. */
  77185. get: function () {
  77186. return this._spritesRenderTime;
  77187. },
  77188. enumerable: true,
  77189. configurable: true
  77190. });
  77191. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  77192. /**
  77193. * Gets the sprites render time capture status
  77194. */
  77195. get: function () {
  77196. return this._captureSpritesRenderTime;
  77197. },
  77198. /**
  77199. * Enable or disable the sprites render time capture
  77200. */
  77201. set: function (value) {
  77202. var _this = this;
  77203. if (value === this._captureSpritesRenderTime) {
  77204. return;
  77205. }
  77206. this._captureSpritesRenderTime = value;
  77207. if (value) {
  77208. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  77209. BABYLON.Tools.StartPerformanceCounter("Sprites");
  77210. _this._spritesRenderTime.beginMonitoring();
  77211. });
  77212. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  77213. BABYLON.Tools.EndPerformanceCounter("Sprites");
  77214. _this._spritesRenderTime.endMonitoring(false);
  77215. });
  77216. }
  77217. else {
  77218. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77219. this._onBeforeSpritesRenderingObserver = null;
  77220. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77221. this._onAfterSpritesRenderingObserver = null;
  77222. }
  77223. },
  77224. enumerable: true,
  77225. configurable: true
  77226. });
  77227. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  77228. /**
  77229. * Gets the perf counter used for physics time
  77230. */
  77231. get: function () {
  77232. return this._physicsTime;
  77233. },
  77234. enumerable: true,
  77235. configurable: true
  77236. });
  77237. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  77238. /**
  77239. * Gets the physics time capture status
  77240. */
  77241. get: function () {
  77242. return this._capturePhysicsTime;
  77243. },
  77244. /**
  77245. * Enable or disable the physics time capture
  77246. */
  77247. set: function (value) {
  77248. var _this = this;
  77249. if (value === this._capturePhysicsTime) {
  77250. return;
  77251. }
  77252. this._capturePhysicsTime = value;
  77253. if (value) {
  77254. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  77255. BABYLON.Tools.StartPerformanceCounter("Physics");
  77256. _this._physicsTime.beginMonitoring();
  77257. });
  77258. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  77259. BABYLON.Tools.EndPerformanceCounter("Physics");
  77260. _this._physicsTime.endMonitoring();
  77261. });
  77262. }
  77263. else {
  77264. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77265. this._onBeforePhysicsObserver = null;
  77266. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77267. this._onAfterPhysicsObserver = null;
  77268. }
  77269. },
  77270. enumerable: true,
  77271. configurable: true
  77272. });
  77273. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  77274. /**
  77275. * Gets the perf counter used for animations time
  77276. */
  77277. get: function () {
  77278. return this._animationsTime;
  77279. },
  77280. enumerable: true,
  77281. configurable: true
  77282. });
  77283. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  77284. /**
  77285. * Gets the animations time capture status
  77286. */
  77287. get: function () {
  77288. return this._captureAnimationsTime;
  77289. },
  77290. /**
  77291. * Enable or disable the animations time capture
  77292. */
  77293. set: function (value) {
  77294. var _this = this;
  77295. if (value === this._captureAnimationsTime) {
  77296. return;
  77297. }
  77298. this._captureAnimationsTime = value;
  77299. if (value) {
  77300. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  77301. _this._animationsTime.endMonitoring();
  77302. });
  77303. }
  77304. else {
  77305. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77306. this._onAfterAnimationsObserver = null;
  77307. }
  77308. },
  77309. enumerable: true,
  77310. configurable: true
  77311. });
  77312. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  77313. /**
  77314. * Gets the perf counter used for frame time capture
  77315. */
  77316. get: function () {
  77317. return this._frameTime;
  77318. },
  77319. enumerable: true,
  77320. configurable: true
  77321. });
  77322. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  77323. /**
  77324. * Gets the frame time capture status
  77325. */
  77326. get: function () {
  77327. return this._captureFrameTime;
  77328. },
  77329. /**
  77330. * Enable or disable the frame time capture
  77331. */
  77332. set: function (value) {
  77333. this._captureFrameTime = value;
  77334. },
  77335. enumerable: true,
  77336. configurable: true
  77337. });
  77338. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  77339. /**
  77340. * Gets the perf counter used for inter-frames time capture
  77341. */
  77342. get: function () {
  77343. return this._interFrameTime;
  77344. },
  77345. enumerable: true,
  77346. configurable: true
  77347. });
  77348. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  77349. /**
  77350. * Gets the inter-frames time capture status
  77351. */
  77352. get: function () {
  77353. return this._captureInterFrameTime;
  77354. },
  77355. /**
  77356. * Enable or disable the inter-frames time capture
  77357. */
  77358. set: function (value) {
  77359. this._captureInterFrameTime = value;
  77360. },
  77361. enumerable: true,
  77362. configurable: true
  77363. });
  77364. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  77365. /**
  77366. * Gets the perf counter used for render time capture
  77367. */
  77368. get: function () {
  77369. return this._renderTime;
  77370. },
  77371. enumerable: true,
  77372. configurable: true
  77373. });
  77374. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  77375. /**
  77376. * Gets the render time capture status
  77377. */
  77378. get: function () {
  77379. return this._captureRenderTime;
  77380. },
  77381. /**
  77382. * Enable or disable the render time capture
  77383. */
  77384. set: function (value) {
  77385. var _this = this;
  77386. if (value === this._captureRenderTime) {
  77387. return;
  77388. }
  77389. this._captureRenderTime = value;
  77390. if (value) {
  77391. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  77392. _this._renderTime.beginMonitoring();
  77393. BABYLON.Tools.StartPerformanceCounter("Main render");
  77394. });
  77395. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  77396. _this._renderTime.endMonitoring(false);
  77397. BABYLON.Tools.EndPerformanceCounter("Main render");
  77398. });
  77399. }
  77400. else {
  77401. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77402. this._onBeforeDrawPhaseObserver = null;
  77403. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77404. this._onAfterDrawPhaseObserver = null;
  77405. }
  77406. },
  77407. enumerable: true,
  77408. configurable: true
  77409. });
  77410. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  77411. /**
  77412. * Gets the perf counter used for frame time capture
  77413. */
  77414. get: function () {
  77415. return this.scene.getEngine()._drawCalls;
  77416. },
  77417. enumerable: true,
  77418. configurable: true
  77419. });
  77420. SceneInstrumentation.prototype.dispose = function () {
  77421. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  77422. this._onAfterRenderObserver = null;
  77423. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  77424. this._onBeforeActiveMeshesEvaluationObserver = null;
  77425. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  77426. this._onAfterActiveMeshesEvaluationObserver = null;
  77427. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  77428. this._onBeforeRenderTargetsRenderObserver = null;
  77429. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  77430. this._onAfterRenderTargetsRenderObserver = null;
  77431. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  77432. this._onBeforeAnimationsObserver = null;
  77433. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77434. this._onBeforeParticlesRenderingObserver = null;
  77435. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77436. this._onAfterParticlesRenderingObserver = null;
  77437. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77438. this._onBeforeSpritesRenderingObserver = null;
  77439. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77440. this._onAfterSpritesRenderingObserver = null;
  77441. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77442. this._onBeforeDrawPhaseObserver = null;
  77443. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77444. this._onAfterDrawPhaseObserver = null;
  77445. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77446. this._onBeforePhysicsObserver = null;
  77447. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77448. this._onAfterPhysicsObserver = null;
  77449. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77450. this._onAfterAnimationsObserver = null;
  77451. this.scene = null;
  77452. };
  77453. return SceneInstrumentation;
  77454. }());
  77455. BABYLON.SceneInstrumentation = SceneInstrumentation;
  77456. })(BABYLON || (BABYLON = {}));
  77457. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  77458. var BABYLON;
  77459. (function (BABYLON) {
  77460. var _TimeToken = /** @class */ (function () {
  77461. function _TimeToken() {
  77462. this._timeElapsedQueryEnded = false;
  77463. }
  77464. return _TimeToken;
  77465. }());
  77466. BABYLON._TimeToken = _TimeToken;
  77467. })(BABYLON || (BABYLON = {}));
  77468. //# sourceMappingURL=babylon.timeToken.js.map
  77469. var BABYLON;
  77470. (function (BABYLON) {
  77471. /**
  77472. * Background material defines definition.
  77473. */
  77474. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  77475. __extends(BackgroundMaterialDefines, _super);
  77476. /**
  77477. * Constructor of the defines.
  77478. */
  77479. function BackgroundMaterialDefines() {
  77480. var _this = _super.call(this) || this;
  77481. /**
  77482. * True if the diffuse texture is in use.
  77483. */
  77484. _this.DIFFUSE = false;
  77485. /**
  77486. * The direct UV channel to use.
  77487. */
  77488. _this.DIFFUSEDIRECTUV = 0;
  77489. /**
  77490. * True if the diffuse texture is in gamma space.
  77491. */
  77492. _this.GAMMADIFFUSE = false;
  77493. /**
  77494. * True if the diffuse texture has opacity in the alpha channel.
  77495. */
  77496. _this.DIFFUSEHASALPHA = false;
  77497. /**
  77498. * True if you want the material to fade to transparent at grazing angle.
  77499. */
  77500. _this.OPACITYFRESNEL = false;
  77501. /**
  77502. * True if an extra blur needs to be added in the reflection.
  77503. */
  77504. _this.REFLECTIONBLUR = false;
  77505. /**
  77506. * True if you want the material to fade to reflection at grazing angle.
  77507. */
  77508. _this.REFLECTIONFRESNEL = false;
  77509. /**
  77510. * True if you want the material to falloff as far as you move away from the scene center.
  77511. */
  77512. _this.REFLECTIONFALLOFF = false;
  77513. /**
  77514. * False if the current Webgl implementation does not support the texture lod extension.
  77515. */
  77516. _this.TEXTURELODSUPPORT = false;
  77517. /**
  77518. * True to ensure the data are premultiplied.
  77519. */
  77520. _this.PREMULTIPLYALPHA = false;
  77521. /**
  77522. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  77523. */
  77524. _this.USERGBCOLOR = false;
  77525. /**
  77526. * True to add noise in order to reduce the banding effect.
  77527. */
  77528. _this.NOISE = false;
  77529. // Image Processing Configuration.
  77530. _this.IMAGEPROCESSING = false;
  77531. _this.VIGNETTE = false;
  77532. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  77533. _this.VIGNETTEBLENDMODEOPAQUE = false;
  77534. _this.TONEMAPPING = false;
  77535. _this.CONTRAST = false;
  77536. _this.COLORCURVES = false;
  77537. _this.COLORGRADING = false;
  77538. _this.COLORGRADING3D = false;
  77539. _this.SAMPLER3DGREENDEPTH = false;
  77540. _this.SAMPLER3DBGRMAP = false;
  77541. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  77542. _this.EXPOSURE = false;
  77543. // Reflection.
  77544. _this.REFLECTION = false;
  77545. _this.REFLECTIONMAP_3D = false;
  77546. _this.REFLECTIONMAP_SPHERICAL = false;
  77547. _this.REFLECTIONMAP_PLANAR = false;
  77548. _this.REFLECTIONMAP_CUBIC = false;
  77549. _this.REFLECTIONMAP_PROJECTION = false;
  77550. _this.REFLECTIONMAP_SKYBOX = false;
  77551. _this.REFLECTIONMAP_EXPLICIT = false;
  77552. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77553. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77554. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77555. _this.INVERTCUBICMAP = false;
  77556. _this.REFLECTIONMAP_OPPOSITEZ = false;
  77557. _this.LODINREFLECTIONALPHA = false;
  77558. _this.GAMMAREFLECTION = false;
  77559. // Default BJS.
  77560. _this.MAINUV1 = false;
  77561. _this.MAINUV2 = false;
  77562. _this.UV1 = false;
  77563. _this.UV2 = false;
  77564. _this.CLIPPLANE = false;
  77565. _this.POINTSIZE = false;
  77566. _this.FOG = false;
  77567. _this.NORMAL = false;
  77568. _this.NUM_BONE_INFLUENCERS = 0;
  77569. _this.BonesPerMesh = 0;
  77570. _this.INSTANCES = false;
  77571. _this.SHADOWFLOAT = false;
  77572. _this.rebuild();
  77573. return _this;
  77574. }
  77575. return BackgroundMaterialDefines;
  77576. }(BABYLON.MaterialDefines));
  77577. /**
  77578. * Background material used to create an efficient environement around your scene.
  77579. */
  77580. var BackgroundMaterial = /** @class */ (function (_super) {
  77581. __extends(BackgroundMaterial, _super);
  77582. /**
  77583. * constructor
  77584. * @param name The name of the material
  77585. * @param scene The scene to add the material to
  77586. */
  77587. function BackgroundMaterial(name, scene) {
  77588. var _this = _super.call(this, name, scene) || this;
  77589. _this.primaryColor = BABYLON.Color3.White();
  77590. _this.primaryLevel = 1;
  77591. _this.secondaryColor = BABYLON.Color3.Gray();
  77592. _this.secondaryLevel = 1;
  77593. _this.tertiaryColor = BABYLON.Color3.Black();
  77594. _this.tertiaryLevel = 1;
  77595. _this.reflectionTexture = null;
  77596. _this.reflectionBlur = 0;
  77597. _this.diffuseTexture = null;
  77598. /**
  77599. * Specify the list of lights casting shadow on the material.
  77600. * All scene shadow lights will be included if null.
  77601. */
  77602. _this._shadowLights = null;
  77603. _this.shadowLights = null;
  77604. _this.shadowBlurScale = 1;
  77605. _this.shadowLevel = 0;
  77606. _this.sceneCenter = BABYLON.Vector3.Zero();
  77607. _this.opacityFresnel = true;
  77608. _this.reflectionFresnel = false;
  77609. _this.reflectionFalloffDistance = 0.0;
  77610. _this.reflectionAmount = 1.0;
  77611. _this.reflectionReflectance0 = 0.05;
  77612. _this.reflectionReflectance90 = 0.5;
  77613. _this.useRGBColor = true;
  77614. _this.enableNoise = false;
  77615. /**
  77616. * Number of Simultaneous lights allowed on the material.
  77617. */
  77618. _this._maxSimultaneousLights = 4;
  77619. _this.maxSimultaneousLights = 4;
  77620. /**
  77621. * Keep track of the image processing observer to allow dispose and replace.
  77622. */
  77623. _this._imageProcessingObserver = null;
  77624. // Temp values kept as cache in the material.
  77625. _this._renderTargets = new BABYLON.SmartArray(16);
  77626. _this._reflectionControls = BABYLON.Vector4.Zero();
  77627. // Setup the default processing configuration to the scene.
  77628. _this._attachImageProcessingConfiguration(null);
  77629. _this.getRenderTargetTextures = function () {
  77630. _this._renderTargets.reset();
  77631. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  77632. _this._renderTargets.push(_this._diffuseTexture);
  77633. }
  77634. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  77635. _this._renderTargets.push(_this._reflectionTexture);
  77636. }
  77637. return _this._renderTargets;
  77638. };
  77639. return _this;
  77640. }
  77641. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  77642. /**
  77643. * Sets the reflection reflectance fresnel values according to the default standard
  77644. * empirically know to work well :-)
  77645. */
  77646. set: function (value) {
  77647. var reflectionWeight = value;
  77648. if (reflectionWeight < 0.5) {
  77649. reflectionWeight = reflectionWeight * 2.0;
  77650. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  77651. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  77652. }
  77653. else {
  77654. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  77655. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  77656. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  77657. }
  77658. },
  77659. enumerable: true,
  77660. configurable: true
  77661. });
  77662. /**
  77663. * Attaches a new image processing configuration to the PBR Material.
  77664. * @param configuration (if null the scene configuration will be use)
  77665. */
  77666. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  77667. var _this = this;
  77668. if (configuration === this._imageProcessingConfiguration) {
  77669. return;
  77670. }
  77671. // Detaches observer.
  77672. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77673. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77674. }
  77675. // Pick the scene configuration if needed.
  77676. if (!configuration) {
  77677. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  77678. }
  77679. else {
  77680. this._imageProcessingConfiguration = configuration;
  77681. }
  77682. // Attaches observer.
  77683. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77684. _this._markAllSubMeshesAsImageProcessingDirty();
  77685. });
  77686. };
  77687. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  77688. /**
  77689. * Gets the image processing configuration used either in this material.
  77690. */
  77691. get: function () {
  77692. return this._imageProcessingConfiguration;
  77693. },
  77694. /**
  77695. * Sets the Default image processing configuration used either in the this material.
  77696. *
  77697. * If sets to null, the scene one is in use.
  77698. */
  77699. set: function (value) {
  77700. this._attachImageProcessingConfiguration(value);
  77701. // Ensure the effect will be rebuilt.
  77702. this._markAllSubMeshesAsTexturesDirty();
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  77708. /**
  77709. * Gets wether the color curves effect is enabled.
  77710. */
  77711. get: function () {
  77712. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77713. },
  77714. /**
  77715. * Sets wether the color curves effect is enabled.
  77716. */
  77717. set: function (value) {
  77718. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77719. },
  77720. enumerable: true,
  77721. configurable: true
  77722. });
  77723. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  77724. /**
  77725. * Gets wether the color grading effect is enabled.
  77726. */
  77727. get: function () {
  77728. return this.imageProcessingConfiguration.colorGradingEnabled;
  77729. },
  77730. /**
  77731. * Gets wether the color grading effect is enabled.
  77732. */
  77733. set: function (value) {
  77734. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77735. },
  77736. enumerable: true,
  77737. configurable: true
  77738. });
  77739. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  77740. /**
  77741. * Gets wether tonemapping is enabled or not.
  77742. */
  77743. get: function () {
  77744. return this._imageProcessingConfiguration.toneMappingEnabled;
  77745. },
  77746. /**
  77747. * Sets wether tonemapping is enabled or not
  77748. */
  77749. set: function (value) {
  77750. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77751. },
  77752. enumerable: true,
  77753. configurable: true
  77754. });
  77755. ;
  77756. ;
  77757. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  77758. /**
  77759. * The camera exposure used on this material.
  77760. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  77761. * This corresponds to a photographic exposure.
  77762. */
  77763. get: function () {
  77764. return this._imageProcessingConfiguration.exposure;
  77765. },
  77766. /**
  77767. * The camera exposure used on this material.
  77768. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  77769. * This corresponds to a photographic exposure.
  77770. */
  77771. set: function (value) {
  77772. this._imageProcessingConfiguration.exposure = value;
  77773. },
  77774. enumerable: true,
  77775. configurable: true
  77776. });
  77777. ;
  77778. ;
  77779. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  77780. /**
  77781. * Gets The camera contrast used on this material.
  77782. */
  77783. get: function () {
  77784. return this._imageProcessingConfiguration.contrast;
  77785. },
  77786. /**
  77787. * Sets The camera contrast used on this material.
  77788. */
  77789. set: function (value) {
  77790. this._imageProcessingConfiguration.contrast = value;
  77791. },
  77792. enumerable: true,
  77793. configurable: true
  77794. });
  77795. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  77796. /**
  77797. * Gets the Color Grading 2D Lookup Texture.
  77798. */
  77799. get: function () {
  77800. return this._imageProcessingConfiguration.colorGradingTexture;
  77801. },
  77802. /**
  77803. * Sets the Color Grading 2D Lookup Texture.
  77804. */
  77805. set: function (value) {
  77806. this.imageProcessingConfiguration.colorGradingTexture = value;
  77807. },
  77808. enumerable: true,
  77809. configurable: true
  77810. });
  77811. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  77812. /**
  77813. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77814. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77815. * 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;
  77816. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77817. */
  77818. get: function () {
  77819. return this.imageProcessingConfiguration.colorCurves;
  77820. },
  77821. /**
  77822. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77823. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77824. * 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;
  77825. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77826. */
  77827. set: function (value) {
  77828. this.imageProcessingConfiguration.colorCurves = value;
  77829. },
  77830. enumerable: true,
  77831. configurable: true
  77832. });
  77833. /**
  77834. * The entire material has been created in order to prevent overdraw.
  77835. * @returns false
  77836. */
  77837. BackgroundMaterial.prototype.needAlphaTesting = function () {
  77838. return true;
  77839. };
  77840. /**
  77841. * The entire material has been created in order to prevent overdraw.
  77842. * @returns true if blending is enable
  77843. */
  77844. BackgroundMaterial.prototype.needAlphaBlending = function () {
  77845. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  77846. };
  77847. /**
  77848. * Checks wether the material is ready to be rendered for a given mesh.
  77849. * @param mesh The mesh to render
  77850. * @param subMesh The submesh to check against
  77851. * @param useInstances Specify wether or not the material is used with instances
  77852. */
  77853. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77854. var _this = this;
  77855. if (useInstances === void 0) { useInstances = false; }
  77856. if (subMesh.effect && this.isFrozen) {
  77857. if (this._wasPreviouslyReady) {
  77858. return true;
  77859. }
  77860. }
  77861. if (!subMesh._materialDefines) {
  77862. subMesh._materialDefines = new BackgroundMaterialDefines();
  77863. }
  77864. var scene = this.getScene();
  77865. var defines = subMesh._materialDefines;
  77866. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  77867. if (defines._renderId === scene.getRenderId()) {
  77868. return true;
  77869. }
  77870. }
  77871. var engine = scene.getEngine();
  77872. // Lights
  77873. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  77874. defines._needNormals = true;
  77875. // Textures
  77876. if (defines._areTexturesDirty) {
  77877. defines._needUVs = false;
  77878. if (scene.texturesEnabled) {
  77879. if (scene.getEngine().getCaps().textureLOD) {
  77880. defines.TEXTURELODSUPPORT = true;
  77881. }
  77882. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77883. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  77884. return false;
  77885. }
  77886. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  77887. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  77888. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  77889. defines.OPACITYFRESNEL = this._opacityFresnel;
  77890. }
  77891. else {
  77892. defines.DIFFUSE = false;
  77893. defines.DIFFUSEHASALPHA = false;
  77894. defines.GAMMADIFFUSE = false;
  77895. defines.OPACITYFRESNEL = false;
  77896. }
  77897. var reflectionTexture = this._reflectionTexture;
  77898. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77899. if (!reflectionTexture.isReadyOrNotBlocking()) {
  77900. return false;
  77901. }
  77902. defines.REFLECTION = true;
  77903. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  77904. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  77905. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  77906. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  77907. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  77908. defines.INVERTCUBICMAP = true;
  77909. }
  77910. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  77911. switch (reflectionTexture.coordinatesMode) {
  77912. case BABYLON.Texture.CUBIC_MODE:
  77913. case BABYLON.Texture.INVCUBIC_MODE:
  77914. defines.REFLECTIONMAP_CUBIC = true;
  77915. break;
  77916. case BABYLON.Texture.EXPLICIT_MODE:
  77917. defines.REFLECTIONMAP_EXPLICIT = true;
  77918. break;
  77919. case BABYLON.Texture.PLANAR_MODE:
  77920. defines.REFLECTIONMAP_PLANAR = true;
  77921. break;
  77922. case BABYLON.Texture.PROJECTION_MODE:
  77923. defines.REFLECTIONMAP_PROJECTION = true;
  77924. break;
  77925. case BABYLON.Texture.SKYBOX_MODE:
  77926. defines.REFLECTIONMAP_SKYBOX = true;
  77927. break;
  77928. case BABYLON.Texture.SPHERICAL_MODE:
  77929. defines.REFLECTIONMAP_SPHERICAL = true;
  77930. break;
  77931. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  77932. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  77933. break;
  77934. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  77935. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  77936. break;
  77937. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  77938. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  77939. break;
  77940. }
  77941. if (this.reflectionFresnel) {
  77942. defines.REFLECTIONFRESNEL = true;
  77943. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  77944. this._reflectionControls.x = this.reflectionAmount;
  77945. this._reflectionControls.y = this.reflectionReflectance0;
  77946. this._reflectionControls.z = this.reflectionReflectance90;
  77947. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  77948. }
  77949. else {
  77950. defines.REFLECTIONFRESNEL = false;
  77951. defines.REFLECTIONFALLOFF = false;
  77952. }
  77953. }
  77954. else {
  77955. defines.REFLECTION = false;
  77956. defines.REFLECTIONFALLOFF = false;
  77957. defines.REFLECTIONBLUR = false;
  77958. defines.REFLECTIONMAP_3D = false;
  77959. defines.REFLECTIONMAP_SPHERICAL = false;
  77960. defines.REFLECTIONMAP_PLANAR = false;
  77961. defines.REFLECTIONMAP_CUBIC = false;
  77962. defines.REFLECTIONMAP_PROJECTION = false;
  77963. defines.REFLECTIONMAP_SKYBOX = false;
  77964. defines.REFLECTIONMAP_EXPLICIT = false;
  77965. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77966. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77967. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77968. defines.INVERTCUBICMAP = false;
  77969. defines.REFLECTIONMAP_OPPOSITEZ = false;
  77970. defines.LODINREFLECTIONALPHA = false;
  77971. defines.GAMMAREFLECTION = false;
  77972. }
  77973. }
  77974. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  77975. defines.USERGBCOLOR = this._useRGBColor;
  77976. defines.NOISE = this._enableNoise;
  77977. }
  77978. if (defines._areImageProcessingDirty) {
  77979. if (!this._imageProcessingConfiguration.isReady()) {
  77980. return false;
  77981. }
  77982. this._imageProcessingConfiguration.prepareDefines(defines);
  77983. }
  77984. // Misc.
  77985. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  77986. // Values that need to be evaluated on every frame
  77987. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  77988. // Attribs
  77989. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  77990. if (mesh) {
  77991. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77992. mesh.createNormals(true);
  77993. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  77994. }
  77995. }
  77996. }
  77997. // Get correct effect
  77998. if (defines.isDirty) {
  77999. defines.markAsProcessed();
  78000. scene.resetCachedMaterial();
  78001. // Fallbacks
  78002. var fallbacks = new BABYLON.EffectFallbacks();
  78003. if (defines.FOG) {
  78004. fallbacks.addFallback(0, "FOG");
  78005. }
  78006. if (defines.POINTSIZE) {
  78007. fallbacks.addFallback(1, "POINTSIZE");
  78008. }
  78009. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  78010. if (defines.NUM_BONE_INFLUENCERS > 0) {
  78011. fallbacks.addCPUSkinningFallback(0, mesh);
  78012. }
  78013. //Attributes
  78014. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78015. if (defines.NORMAL) {
  78016. attribs.push(BABYLON.VertexBuffer.NormalKind);
  78017. }
  78018. if (defines.UV1) {
  78019. attribs.push(BABYLON.VertexBuffer.UVKind);
  78020. }
  78021. if (defines.UV2) {
  78022. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78023. }
  78024. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  78025. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  78026. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  78027. "vFogInfos", "vFogColor", "pointSize",
  78028. "vClipPlane", "mBones",
  78029. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  78030. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  78031. "shadowLevel", "alpha",
  78032. "vBackgroundCenter", "vReflectionControl",
  78033. "vDiffuseInfos", "diffuseMatrix",
  78034. ];
  78035. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  78036. var uniformBuffers = ["Material", "Scene"];
  78037. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  78038. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  78039. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  78040. uniformsNames: uniforms,
  78041. uniformBuffersNames: uniformBuffers,
  78042. samplers: samplers,
  78043. defines: defines,
  78044. maxSimultaneousLights: this._maxSimultaneousLights
  78045. });
  78046. var onCompiled = function (effect) {
  78047. if (_this.onCompiled) {
  78048. _this.onCompiled(effect);
  78049. }
  78050. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  78051. };
  78052. var join = defines.toString();
  78053. subMesh.setEffect(scene.getEngine().createEffect("background", {
  78054. attributes: attribs,
  78055. uniformsNames: uniforms,
  78056. uniformBuffersNames: uniformBuffers,
  78057. samplers: samplers,
  78058. defines: join,
  78059. fallbacks: fallbacks,
  78060. onCompiled: onCompiled,
  78061. onError: this.onError,
  78062. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  78063. }, engine), defines);
  78064. this.buildUniformLayout();
  78065. }
  78066. if (!subMesh.effect || !subMesh.effect.isReady()) {
  78067. return false;
  78068. }
  78069. defines._renderId = scene.getRenderId();
  78070. this._wasPreviouslyReady = true;
  78071. return true;
  78072. };
  78073. /**
  78074. * Build the uniform buffer used in the material.
  78075. */
  78076. BackgroundMaterial.prototype.buildUniformLayout = function () {
  78077. // Order is important !
  78078. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  78079. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  78080. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  78081. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  78082. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  78083. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  78084. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  78085. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  78086. this._uniformBuffer.addUniform("pointSize", 1);
  78087. this._uniformBuffer.addUniform("shadowLevel", 1);
  78088. this._uniformBuffer.addUniform("alpha", 1);
  78089. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  78090. this._uniformBuffer.addUniform("vReflectionControl", 4);
  78091. this._uniformBuffer.create();
  78092. };
  78093. /**
  78094. * Unbind the material.
  78095. */
  78096. BackgroundMaterial.prototype.unbind = function () {
  78097. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  78098. this._uniformBuffer.setTexture("diffuseSampler", null);
  78099. }
  78100. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  78101. this._uniformBuffer.setTexture("reflectionSampler", null);
  78102. }
  78103. _super.prototype.unbind.call(this);
  78104. };
  78105. /**
  78106. * Bind only the world matrix to the material.
  78107. * @param world The world matrix to bind.
  78108. */
  78109. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  78110. this._activeEffect.setMatrix("world", world);
  78111. };
  78112. /**
  78113. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  78114. * @param world The world matrix to bind.
  78115. * @param subMesh The submesh to bind for.
  78116. */
  78117. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  78118. var scene = this.getScene();
  78119. var defines = subMesh._materialDefines;
  78120. if (!defines) {
  78121. return;
  78122. }
  78123. var effect = subMesh.effect;
  78124. if (!effect) {
  78125. return;
  78126. }
  78127. this._activeEffect = effect;
  78128. // Matrices
  78129. this.bindOnlyWorldMatrix(world);
  78130. // Bones
  78131. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  78132. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  78133. if (mustRebind) {
  78134. this._uniformBuffer.bindToEffect(effect, "Material");
  78135. this.bindViewProjection(effect);
  78136. var reflectionTexture = this._reflectionTexture;
  78137. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  78138. // Texture uniforms
  78139. if (scene.texturesEnabled) {
  78140. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78141. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  78142. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  78143. }
  78144. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78145. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  78146. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  78147. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  78148. }
  78149. }
  78150. if (this.shadowLevel > 0) {
  78151. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  78152. }
  78153. this._uniformBuffer.updateFloat("alpha", this.alpha);
  78154. // Point size
  78155. if (this.pointsCloud) {
  78156. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  78157. }
  78158. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  78159. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  78160. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  78161. }
  78162. // Textures
  78163. if (scene.texturesEnabled) {
  78164. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78165. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  78166. }
  78167. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78168. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  78169. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  78170. }
  78171. else if (!defines.REFLECTIONBLUR) {
  78172. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  78173. }
  78174. else {
  78175. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  78176. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  78177. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  78178. }
  78179. if (defines.REFLECTIONFRESNEL) {
  78180. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  78181. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  78182. }
  78183. }
  78184. }
  78185. // Clip plane
  78186. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  78187. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  78188. }
  78189. if (mustRebind || !this.isFrozen) {
  78190. if (scene.lightsEnabled) {
  78191. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  78192. }
  78193. // View
  78194. this.bindView(effect);
  78195. // Fog
  78196. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  78197. // image processing
  78198. this._imageProcessingConfiguration.bind(this._activeEffect);
  78199. }
  78200. this._uniformBuffer.update();
  78201. this._afterBind(mesh);
  78202. };
  78203. /**
  78204. * Dispose the material.
  78205. * @forceDisposeEffect Force disposal of the associated effect.
  78206. * @forceDisposeTextures Force disposal of the associated textures.
  78207. */
  78208. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78209. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  78210. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  78211. if (forceDisposeTextures) {
  78212. if (this.diffuseTexture) {
  78213. this.diffuseTexture.dispose();
  78214. }
  78215. if (this.reflectionTexture) {
  78216. this.reflectionTexture.dispose();
  78217. }
  78218. }
  78219. this._renderTargets.dispose();
  78220. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78221. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78222. }
  78223. _super.prototype.dispose.call(this, forceDisposeEffect);
  78224. };
  78225. /**
  78226. * Clones the material.
  78227. * @name The cloned name.
  78228. * @returns The cloned material.
  78229. */
  78230. BackgroundMaterial.prototype.clone = function (name) {
  78231. var _this = this;
  78232. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  78233. };
  78234. /**
  78235. * Serializes the current material to its JSON representation.
  78236. * @returns The JSON representation.
  78237. */
  78238. BackgroundMaterial.prototype.serialize = function () {
  78239. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78240. serializationObject.customType = "BABYLON.BackgroundMaterial";
  78241. return serializationObject;
  78242. };
  78243. /**
  78244. * Gets the class name of the material
  78245. * @returns "BackgroundMaterial"
  78246. */
  78247. BackgroundMaterial.prototype.getClassName = function () {
  78248. return "BackgroundMaterial";
  78249. };
  78250. /**
  78251. * Parse a JSON input to create back a background material.
  78252. * @param source
  78253. * @param scene
  78254. * @param rootUrl
  78255. * @returns the instantiated BackgroundMaterial.
  78256. */
  78257. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  78258. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  78259. };
  78260. /**
  78261. * Standard reflectance value at parallel view angle.
  78262. */
  78263. BackgroundMaterial.standardReflectance0 = 0.05;
  78264. /**
  78265. * Standard reflectance value at grazing angle.
  78266. */
  78267. BackgroundMaterial.standardReflectance90 = 0.5;
  78268. __decorate([
  78269. BABYLON.serializeAsColor3()
  78270. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  78271. __decorate([
  78272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78273. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  78274. __decorate([
  78275. BABYLON.serialize()
  78276. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  78277. __decorate([
  78278. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78279. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  78280. __decorate([
  78281. BABYLON.serializeAsColor3()
  78282. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  78283. __decorate([
  78284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78285. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  78286. __decorate([
  78287. BABYLON.serialize()
  78288. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  78289. __decorate([
  78290. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78291. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  78292. __decorate([
  78293. BABYLON.serializeAsColor3()
  78294. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  78295. __decorate([
  78296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78297. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  78298. __decorate([
  78299. BABYLON.serialize()
  78300. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  78301. __decorate([
  78302. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78303. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  78304. __decorate([
  78305. BABYLON.serializeAsTexture()
  78306. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  78307. __decorate([
  78308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78309. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  78310. __decorate([
  78311. BABYLON.serialize()
  78312. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  78313. __decorate([
  78314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78315. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  78316. __decorate([
  78317. BABYLON.serializeAsTexture()
  78318. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  78319. __decorate([
  78320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78321. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  78322. __decorate([
  78323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78324. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  78325. __decorate([
  78326. BABYLON.serialize()
  78327. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  78328. __decorate([
  78329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78330. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  78331. __decorate([
  78332. BABYLON.serialize()
  78333. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  78334. __decorate([
  78335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78336. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  78337. __decorate([
  78338. BABYLON.serializeAsVector3()
  78339. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  78340. __decorate([
  78341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78342. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  78343. __decorate([
  78344. BABYLON.serialize()
  78345. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  78346. __decorate([
  78347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78348. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  78349. __decorate([
  78350. BABYLON.serialize()
  78351. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  78352. __decorate([
  78353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78354. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  78355. __decorate([
  78356. BABYLON.serialize()
  78357. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  78358. __decorate([
  78359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78360. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  78361. __decorate([
  78362. BABYLON.serialize()
  78363. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  78364. __decorate([
  78365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78366. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  78367. __decorate([
  78368. BABYLON.serialize()
  78369. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  78370. __decorate([
  78371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78372. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  78373. __decorate([
  78374. BABYLON.serialize()
  78375. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  78376. __decorate([
  78377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78378. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  78379. __decorate([
  78380. BABYLON.serialize()
  78381. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  78382. __decorate([
  78383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78384. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  78385. __decorate([
  78386. BABYLON.serialize()
  78387. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  78388. __decorate([
  78389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78390. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  78391. __decorate([
  78392. BABYLON.serialize()
  78393. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  78394. __decorate([
  78395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78396. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  78397. __decorate([
  78398. BABYLON.serializeAsImageProcessingConfiguration()
  78399. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  78400. return BackgroundMaterial;
  78401. }(BABYLON.PushMaterial));
  78402. BABYLON.BackgroundMaterial = BackgroundMaterial;
  78403. })(BABYLON || (BABYLON = {}));
  78404. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  78405. var __assign = (this && this.__assign) || Object.assign || function(t) {
  78406. for (var s, i = 1, n = arguments.length; i < n; i++) {
  78407. s = arguments[i];
  78408. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  78409. t[p] = s[p];
  78410. }
  78411. return t;
  78412. };
  78413. var BABYLON;
  78414. (function (BABYLON) {
  78415. /**
  78416. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  78417. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  78418. * It also helps with the default setup of your imageProcessing configuration.
  78419. */
  78420. var EnvironmentHelper = /** @class */ (function () {
  78421. /**
  78422. * constructor
  78423. * @param options
  78424. * @param scene The scene to add the material to
  78425. */
  78426. function EnvironmentHelper(options, scene) {
  78427. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  78428. this._scene = scene;
  78429. this._setupBackground();
  78430. this._setupImageProcessing();
  78431. }
  78432. /**
  78433. * Creates the default options for the helper.
  78434. */
  78435. EnvironmentHelper._getDefaultOptions = function () {
  78436. return {
  78437. createGround: true,
  78438. groundSize: 15,
  78439. groundTexture: this._groundTextureCDNUrl,
  78440. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78441. groundOpacity: 0.9,
  78442. enableGroundShadow: true,
  78443. groundShadowLevel: 0.5,
  78444. enableGroundMirror: false,
  78445. groundMirrorSizeRatio: 0.3,
  78446. groundMirrorBlurKernel: 64,
  78447. groundMirrorAmount: 1,
  78448. groundMirrorFresnelWeight: 1,
  78449. groundMirrorFallOffDistance: 0,
  78450. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  78451. createSkybox: true,
  78452. skyboxSize: 20,
  78453. skyboxTexture: this._skyboxTextureCDNUrl,
  78454. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78455. backgroundYRotation: 0,
  78456. sizeAuto: true,
  78457. rootPosition: BABYLON.Vector3.Zero(),
  78458. setupImageProcessing: true,
  78459. environmentTexture: this._environmentTextureCDNUrl,
  78460. cameraExposure: 0.8,
  78461. cameraContrast: 1.2,
  78462. toneMappingEnabled: true,
  78463. };
  78464. };
  78465. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  78466. /**
  78467. * Gets the root mesh created by the helper.
  78468. */
  78469. get: function () {
  78470. return this._rootMesh;
  78471. },
  78472. enumerable: true,
  78473. configurable: true
  78474. });
  78475. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  78476. /**
  78477. * Gets the skybox created by the helper.
  78478. */
  78479. get: function () {
  78480. return this._skybox;
  78481. },
  78482. enumerable: true,
  78483. configurable: true
  78484. });
  78485. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  78486. /**
  78487. * Gets the skybox texture created by the helper.
  78488. */
  78489. get: function () {
  78490. return this._skyboxTexture;
  78491. },
  78492. enumerable: true,
  78493. configurable: true
  78494. });
  78495. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  78496. /**
  78497. * Gets the skybox material created by the helper.
  78498. */
  78499. get: function () {
  78500. return this._skyboxMaterial;
  78501. },
  78502. enumerable: true,
  78503. configurable: true
  78504. });
  78505. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  78506. /**
  78507. * Gets the ground mesh created by the helper.
  78508. */
  78509. get: function () {
  78510. return this._ground;
  78511. },
  78512. enumerable: true,
  78513. configurable: true
  78514. });
  78515. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  78516. /**
  78517. * Gets the ground texture created by the helper.
  78518. */
  78519. get: function () {
  78520. return this._groundTexture;
  78521. },
  78522. enumerable: true,
  78523. configurable: true
  78524. });
  78525. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  78526. /**
  78527. * Gets the ground mirror created by the helper.
  78528. */
  78529. get: function () {
  78530. return this._groundMirror;
  78531. },
  78532. enumerable: true,
  78533. configurable: true
  78534. });
  78535. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  78536. /**
  78537. * Gets the ground mirror render list to helps pushing the meshes
  78538. * you wish in the ground reflection.
  78539. */
  78540. get: function () {
  78541. if (this._groundMirror) {
  78542. return this._groundMirror.renderList;
  78543. }
  78544. return null;
  78545. },
  78546. enumerable: true,
  78547. configurable: true
  78548. });
  78549. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  78550. /**
  78551. * Gets the ground material created by the helper.
  78552. */
  78553. get: function () {
  78554. return this._groundMaterial;
  78555. },
  78556. enumerable: true,
  78557. configurable: true
  78558. });
  78559. /**
  78560. * Updates the background according to the new options
  78561. * @param options
  78562. */
  78563. EnvironmentHelper.prototype.updateOptions = function (options) {
  78564. var newOptions = __assign({}, this._options, options);
  78565. if (this._ground && !newOptions.createGround) {
  78566. this._ground.dispose();
  78567. this._ground = null;
  78568. }
  78569. if (this._groundMaterial && !newOptions.createGround) {
  78570. this._groundMaterial.dispose();
  78571. this._groundMaterial = null;
  78572. }
  78573. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  78574. this._groundTexture.dispose();
  78575. this._groundTexture = null;
  78576. }
  78577. if (this._skybox && !newOptions.createSkybox) {
  78578. this._skybox.dispose();
  78579. this._skybox = null;
  78580. }
  78581. if (this._skyboxMaterial && !newOptions.createSkybox) {
  78582. this._skyboxMaterial.dispose();
  78583. this._skyboxMaterial = null;
  78584. }
  78585. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  78586. this._skyboxTexture.dispose();
  78587. this._skyboxTexture = null;
  78588. }
  78589. if (this._groundMirror && !newOptions.enableGroundMirror) {
  78590. this._groundMirror.dispose();
  78591. this._groundMirror = null;
  78592. }
  78593. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  78594. this._scene.environmentTexture.dispose();
  78595. }
  78596. this._options = newOptions;
  78597. this._setupBackground();
  78598. this._setupImageProcessing();
  78599. };
  78600. /**
  78601. * Sets the primary color of all the available elements.
  78602. * @param color
  78603. */
  78604. EnvironmentHelper.prototype.setMainColor = function (color) {
  78605. if (this.groundMaterial) {
  78606. this.groundMaterial.primaryColor = color;
  78607. }
  78608. if (this.skyboxMaterial) {
  78609. this.skyboxMaterial.primaryColor = color;
  78610. }
  78611. if (this.groundMirror) {
  78612. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  78613. }
  78614. };
  78615. /**
  78616. * Setup the image processing according to the specified options.
  78617. */
  78618. EnvironmentHelper.prototype._setupImageProcessing = function () {
  78619. if (this._options.setupImageProcessing) {
  78620. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  78621. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  78622. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  78623. this._setupEnvironmentTexture();
  78624. }
  78625. };
  78626. /**
  78627. * Setup the environment texture according to the specified options.
  78628. */
  78629. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  78630. if (this._scene.environmentTexture) {
  78631. return;
  78632. }
  78633. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  78634. this._scene.environmentTexture = this._options.environmentTexture;
  78635. return;
  78636. }
  78637. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  78638. this._scene.environmentTexture = environmentTexture;
  78639. };
  78640. /**
  78641. * Setup the background according to the specified options.
  78642. */
  78643. EnvironmentHelper.prototype._setupBackground = function () {
  78644. if (!this._rootMesh) {
  78645. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  78646. }
  78647. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  78648. var sceneSize = this._getSceneSize();
  78649. if (this._options.createGround) {
  78650. this._setupGround(sceneSize);
  78651. this._setupGroundMaterial();
  78652. this._setupGroundDiffuseTexture();
  78653. if (this._options.enableGroundMirror) {
  78654. this._setupGroundMirrorTexture(sceneSize);
  78655. }
  78656. this._setupMirrorInGroundMaterial();
  78657. }
  78658. if (this._options.createSkybox) {
  78659. this._setupSkybox(sceneSize);
  78660. this._setupSkyboxMaterial();
  78661. this._setupSkyboxReflectionTexture();
  78662. }
  78663. this._rootMesh.position.x = sceneSize.rootPosition.x;
  78664. this._rootMesh.position.z = sceneSize.rootPosition.z;
  78665. this._rootMesh.position.y = sceneSize.rootPosition.y;
  78666. };
  78667. /**
  78668. * Get the scene sizes according to the setup.
  78669. */
  78670. EnvironmentHelper.prototype._getSceneSize = function () {
  78671. var groundSize = this._options.groundSize;
  78672. var skyboxSize = this._options.skyboxSize;
  78673. var rootPosition = this._options.rootPosition;
  78674. var sceneExtends = this._scene.getWorldExtends();
  78675. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  78676. var bias = 0.0001;
  78677. if (this._options.sizeAuto) {
  78678. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  78679. this._scene.activeCamera.upperRadiusLimit) {
  78680. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  78681. }
  78682. if (this._scene.activeCamera) {
  78683. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  78684. }
  78685. var sceneDiagonalLenght = sceneDiagonal.length();
  78686. if (sceneDiagonalLenght > groundSize) {
  78687. groundSize = sceneDiagonalLenght * 2;
  78688. }
  78689. // 10 % bigger.
  78690. groundSize *= 1.1;
  78691. skyboxSize *= 1.5;
  78692. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  78693. rootPosition.y = sceneExtends.min.y - bias;
  78694. }
  78695. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  78696. };
  78697. /**
  78698. * Setup the ground according to the specified options.
  78699. */
  78700. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  78701. var _this = this;
  78702. if (!this._ground) {
  78703. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  78704. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  78705. this._ground.parent = this._rootMesh;
  78706. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  78707. }
  78708. this._ground.receiveShadows = this._options.enableGroundShadow;
  78709. };
  78710. /**
  78711. * Setup the ground material according to the specified options.
  78712. */
  78713. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  78714. if (!this._groundMaterial) {
  78715. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  78716. }
  78717. this._groundMaterial.alpha = this._options.groundOpacity;
  78718. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  78719. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  78720. this._groundMaterial.primaryLevel = 1;
  78721. this._groundMaterial.primaryColor = this._options.groundColor;
  78722. this._groundMaterial.secondaryLevel = 0;
  78723. this._groundMaterial.tertiaryLevel = 0;
  78724. this._groundMaterial.useRGBColor = false;
  78725. this._groundMaterial.enableNoise = true;
  78726. if (this._ground) {
  78727. this._ground.material = this._groundMaterial;
  78728. }
  78729. };
  78730. /**
  78731. * Setup the ground diffuse texture according to the specified options.
  78732. */
  78733. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  78734. if (!this._groundMaterial) {
  78735. return;
  78736. }
  78737. if (this._groundTexture) {
  78738. return;
  78739. }
  78740. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  78741. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  78742. return;
  78743. }
  78744. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  78745. diffuseTexture.gammaSpace = false;
  78746. diffuseTexture.hasAlpha = true;
  78747. this._groundMaterial.diffuseTexture = diffuseTexture;
  78748. };
  78749. /**
  78750. * Setup the ground mirror texture according to the specified options.
  78751. */
  78752. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  78753. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78754. if (!this._groundMirror) {
  78755. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  78756. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  78757. this._groundMirror.anisotropicFilteringLevel = 1;
  78758. this._groundMirror.wrapU = wrapping;
  78759. this._groundMirror.wrapV = wrapping;
  78760. this._groundMirror.gammaSpace = false;
  78761. if (this._groundMirror.renderList) {
  78762. for (var i = 0; i < this._scene.meshes.length; i++) {
  78763. var mesh = this._scene.meshes[i];
  78764. if (mesh !== this._ground &&
  78765. mesh !== this._skybox &&
  78766. mesh !== this._rootMesh) {
  78767. this._groundMirror.renderList.push(mesh);
  78768. }
  78769. }
  78770. }
  78771. }
  78772. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  78773. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  78774. };
  78775. /**
  78776. * Setup the ground to receive the mirror texture.
  78777. */
  78778. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  78779. if (this._groundMaterial) {
  78780. this._groundMaterial.reflectionTexture = this._groundMirror;
  78781. this._groundMaterial.reflectionFresnel = true;
  78782. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  78783. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  78784. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  78785. }
  78786. };
  78787. /**
  78788. * Setup the skybox according to the specified options.
  78789. */
  78790. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  78791. var _this = this;
  78792. if (!this._skybox) {
  78793. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  78794. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  78795. }
  78796. this._skybox.parent = this._rootMesh;
  78797. };
  78798. /**
  78799. * Setup the skybox material according to the specified options.
  78800. */
  78801. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  78802. if (!this._skybox) {
  78803. return;
  78804. }
  78805. if (!this._skyboxMaterial) {
  78806. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  78807. }
  78808. this._skyboxMaterial.useRGBColor = false;
  78809. this._skyboxMaterial.primaryLevel = 1;
  78810. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  78811. this._skyboxMaterial.secondaryLevel = 0;
  78812. this._skyboxMaterial.tertiaryLevel = 0;
  78813. this._skyboxMaterial.enableNoise = true;
  78814. this._skybox.material = this._skyboxMaterial;
  78815. };
  78816. /**
  78817. * Setup the skybox reflection texture according to the specified options.
  78818. */
  78819. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  78820. if (!this._skyboxMaterial) {
  78821. return;
  78822. }
  78823. if (this._skyboxTexture) {
  78824. return;
  78825. }
  78826. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  78827. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  78828. return;
  78829. }
  78830. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  78831. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  78832. this._skyboxTexture.gammaSpace = false;
  78833. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  78834. };
  78835. /**
  78836. * Dispose all the elements created by the Helper.
  78837. */
  78838. EnvironmentHelper.prototype.dispose = function () {
  78839. if (this._groundMaterial) {
  78840. this._groundMaterial.dispose(true, true);
  78841. }
  78842. if (this._skyboxMaterial) {
  78843. this._skyboxMaterial.dispose(true, true);
  78844. }
  78845. this._rootMesh.dispose(false);
  78846. };
  78847. /**
  78848. * Default ground texture URL.
  78849. */
  78850. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  78851. /**
  78852. * Default skybox texture URL.
  78853. */
  78854. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  78855. /**
  78856. * Default environment texture URL.
  78857. */
  78858. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  78859. return EnvironmentHelper;
  78860. }());
  78861. BABYLON.EnvironmentHelper = EnvironmentHelper;
  78862. })(BABYLON || (BABYLON = {}));
  78863. //# sourceMappingURL=babylon.environmentHelper.js.map
  78864. 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 RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\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","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\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  78865. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\nreturn color;\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\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float 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};"};
  78866. (function universalModuleDefinition(root, factory) {
  78867. var f = factory();
  78868. if (root && root["BABYLON"]) {
  78869. return;
  78870. }
  78871. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  78872. globalObject["BABYLON"] = f;
  78873. if(true)
  78874. module.exports = f;
  78875. else if(typeof define === 'function' && define.amd)
  78876. define(["BABYLON"], factory);
  78877. else if(typeof exports === 'object')
  78878. exports["BABYLON"] = f;
  78879. else {
  78880. root["BABYLON"] = f;
  78881. }
  78882. })(this, function() {
  78883. return BABYLON;
  78884. });
  78885. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  78886. /***/ }),
  78887. /* 1 */
  78888. /***/ (function(module, exports) {
  78889. var g;
  78890. // This works in non-strict mode
  78891. g = (function() {
  78892. return this;
  78893. })();
  78894. try {
  78895. // This works if eval is allowed (see CSP)
  78896. g = g || Function("return this")() || (1,eval)("this");
  78897. } catch(e) {
  78898. // This works if the window reference is available
  78899. if(typeof window === "object")
  78900. g = window;
  78901. }
  78902. // g can still be undefined, but nothing to do about it...
  78903. // We return undefined, instead of nothing here, so it's
  78904. // easier to handle this case. if(!global) { ...}
  78905. module.exports = g;
  78906. /***/ }),
  78907. /* 2 */
  78908. /***/ (function(module, exports, __webpack_require__) {
  78909. "use strict";
  78910. Object.defineProperty(exports, "__esModule", { value: true });
  78911. var babylonjs_1 = __webpack_require__(0);
  78912. var helper_1 = __webpack_require__(3);
  78913. var HTMLMapper = (function () {
  78914. function HTMLMapper() {
  78915. }
  78916. HTMLMapper.prototype.map = function (element) {
  78917. var config = {};
  78918. var _loop_1 = function (attrIdx) {
  78919. var attr = element.attributes.item(attrIdx);
  78920. var split = attr.nodeName.split('.');
  78921. split.reduce(function (currentConfig, key, idx) {
  78922. var camelKey = helper_1.kebabToCamel(key);
  78923. if (idx === split.length - 1) {
  78924. var val = attr.nodeValue;
  78925. if (val === "true") {
  78926. val = true;
  78927. }
  78928. else if (val === "false") {
  78929. val = false;
  78930. }
  78931. else {
  78932. var number = parseFloat(val);
  78933. if (!isNaN(number)) {
  78934. val = number;
  78935. }
  78936. }
  78937. currentConfig[camelKey] = val;
  78938. }
  78939. else {
  78940. currentConfig[camelKey] = currentConfig[camelKey] || {};
  78941. }
  78942. return currentConfig[camelKey];
  78943. }, config);
  78944. };
  78945. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  78946. _loop_1(attrIdx);
  78947. }
  78948. return config;
  78949. };
  78950. return HTMLMapper;
  78951. }());
  78952. var JSONMapper = (function () {
  78953. function JSONMapper() {
  78954. }
  78955. JSONMapper.prototype.map = function (rawSource) {
  78956. return JSON.parse(rawSource);
  78957. };
  78958. return JSONMapper;
  78959. }());
  78960. var DOMMapper = (function () {
  78961. function DOMMapper() {
  78962. }
  78963. DOMMapper.prototype.map = function (baseElement) {
  78964. var htmlMapper = new HTMLMapper();
  78965. var config = htmlMapper.map(baseElement);
  78966. var traverseChildren = function (element, partConfig) {
  78967. var children = element.children;
  78968. if (children.length) {
  78969. for (var i = 0; i < children.length; ++i) {
  78970. var item = children.item(i);
  78971. var configMapped = htmlMapper.map(item);
  78972. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  78973. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  78974. partConfig[key] = [];
  78975. }
  78976. else {
  78977. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  78978. partConfig.push(configMapped);
  78979. }
  78980. else if (partConfig[key]) {
  78981. element.setAttribute('array', 'true');
  78982. var oldItem = partConfig[key];
  78983. partConfig = [oldItem, configMapped];
  78984. }
  78985. else {
  78986. partConfig[key] = configMapped;
  78987. }
  78988. }
  78989. traverseChildren(item, partConfig[key] || configMapped);
  78990. }
  78991. }
  78992. return partConfig;
  78993. };
  78994. traverseChildren(baseElement, config);
  78995. return config;
  78996. };
  78997. return DOMMapper;
  78998. }());
  78999. var MapperManager = (function () {
  79000. function MapperManager() {
  79001. this.mappers = {
  79002. "html": new HTMLMapper(),
  79003. "json": new JSONMapper(),
  79004. "dom": new DOMMapper()
  79005. };
  79006. }
  79007. MapperManager.prototype.getMapper = function (type) {
  79008. if (!this.mappers[type]) {
  79009. babylonjs_1.Tools.Error("No mapper defined for " + type);
  79010. }
  79011. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  79012. };
  79013. MapperManager.prototype.registerMapper = function (type, mapper) {
  79014. this.mappers[type] = mapper;
  79015. };
  79016. MapperManager.DefaultMapper = 'json';
  79017. return MapperManager;
  79018. }());
  79019. exports.MapperManager = MapperManager;
  79020. exports.mapperManager = new MapperManager();
  79021. exports.default = exports.mapperManager;
  79022. /***/ }),
  79023. /* 3 */
  79024. /***/ (function(module, exports, __webpack_require__) {
  79025. "use strict";
  79026. Object.defineProperty(exports, "__esModule", { value: true });
  79027. function isUrl(urlToCheck) {
  79028. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  79029. return true;
  79030. }
  79031. return false;
  79032. }
  79033. exports.isUrl = isUrl;
  79034. function loadFile(url) {
  79035. return new Promise(function (resolve, reject) {
  79036. var xhr = new XMLHttpRequest();
  79037. xhr.open('GET', url);
  79038. xhr.send();
  79039. xhr.onreadystatechange = function () {
  79040. var DONE = 4;
  79041. var OK = 200;
  79042. if (xhr.readyState === DONE) {
  79043. if (xhr.status === OK) {
  79044. resolve(xhr.responseText);
  79045. }
  79046. }
  79047. else {
  79048. console.log('Error: ' + xhr.status, url);
  79049. reject('Error: ' + xhr.status);
  79050. }
  79051. };
  79052. });
  79053. }
  79054. exports.loadFile = loadFile;
  79055. function kebabToCamel(s) {
  79056. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  79057. }
  79058. exports.kebabToCamel = kebabToCamel;
  79059. function camelToKebab(str) {
  79060. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  79061. }
  79062. exports.camelToKebab = camelToKebab;
  79063. /***/ }),
  79064. /* 4 */
  79065. /***/ (function(module, exports, __webpack_require__) {
  79066. "use strict";
  79067. Object.defineProperty(exports, "__esModule", { value: true });
  79068. var babylonjs_1 = __webpack_require__(0);
  79069. var ViewerManager = (function () {
  79070. function ViewerManager() {
  79071. this.viewers = {};
  79072. this.onViewerAddedObservable = new babylonjs_1.Observable();
  79073. }
  79074. ViewerManager.prototype.addViewer = function (viewer) {
  79075. this.viewers[viewer.getBaseId()] = viewer;
  79076. this._onViewerAdded(viewer);
  79077. };
  79078. ViewerManager.prototype.getViewerById = function (id) {
  79079. return this.viewers[id];
  79080. };
  79081. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  79082. for (var id in this.viewers) {
  79083. if (this.viewers[id].containerElement === element) {
  79084. return this.getViewerById(id);
  79085. }
  79086. }
  79087. };
  79088. ViewerManager.prototype.getViewerPromiseById = function (id) {
  79089. var _this = this;
  79090. return new Promise(function (resolve, reject) {
  79091. var localViewer = _this.getViewerById(id);
  79092. if (localViewer) {
  79093. return resolve(localViewer);
  79094. }
  79095. var viewerFunction = function (viewer) {
  79096. if (viewer.getBaseId() === id) {
  79097. resolve(viewer);
  79098. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  79099. }
  79100. };
  79101. _this.onViewerAddedObservable.add(viewerFunction);
  79102. });
  79103. };
  79104. ViewerManager.prototype._onViewerAdded = function (viewer) {
  79105. this.onViewerAdded && this.onViewerAdded(viewer);
  79106. this.onViewerAddedObservable.notifyObservers(viewer);
  79107. };
  79108. return ViewerManager;
  79109. }());
  79110. exports.viewerManager = new ViewerManager();
  79111. /***/ }),
  79112. /* 5 */
  79113. /***/ (function(module, exports, __webpack_require__) {
  79114. "use strict";
  79115. var __extends = (this && this.__extends) || (function () {
  79116. var extendStatics = Object.setPrototypeOf ||
  79117. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  79118. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  79119. return function (d, b) {
  79120. extendStatics(d, b);
  79121. function __() { this.constructor = d; }
  79122. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  79123. };
  79124. })();
  79125. Object.defineProperty(exports, "__esModule", { value: true });
  79126. var viewer_1 = __webpack_require__(6);
  79127. var babylonjs_1 = __webpack_require__(0);
  79128. var DefaultViewer = (function (_super) {
  79129. __extends(DefaultViewer, _super);
  79130. function DefaultViewer(containerElement, initialConfiguration) {
  79131. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  79132. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  79133. _this.containerElement = containerElement;
  79134. _this.onModelLoaded = function (meshes) {
  79135. _this.setModelMetaData();
  79136. setTimeout(function () {
  79137. _this.hideLoadingScreen();
  79138. }, 500);
  79139. _this.scene.createDefaultCameraOrLight(true, true, true);
  79140. _this.camera = _this.scene.activeCamera;
  79141. meshes[0].rotation.y += Math.PI;
  79142. _this.setupCamera(meshes);
  79143. _this.setupLights(meshes);
  79144. return _this.initEnvironment(meshes);
  79145. };
  79146. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  79147. return _this;
  79148. }
  79149. DefaultViewer.prototype.initScene = function () {
  79150. var _this = this;
  79151. return _super.prototype.initScene.call(this).then(function () {
  79152. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  79153. return _this.scene;
  79154. });
  79155. };
  79156. DefaultViewer.prototype.onTemplatesLoaded = function () {
  79157. var _this = this;
  79158. this.showLoadingScreen();
  79159. var viewerElement = this.templateManager.getTemplate('viewer');
  79160. var navbar = this.templateManager.getTemplate('navBar');
  79161. if (viewerElement && navbar) {
  79162. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  79163. var navbarShown_1 = true;
  79164. var timeoutCancel_1;
  79165. var triggerNavbar = function (show, evt) {
  79166. if (show === void 0) { show = false; }
  79167. if (!navbar || evt.button > 0)
  79168. return;
  79169. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  79170. if (show === navbarShown_1)
  79171. return;
  79172. if (show) {
  79173. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  79174. navbarShown_1 = show;
  79175. }
  79176. else {
  79177. var visibilityTimeout = 2000;
  79178. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  79179. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  79180. }
  79181. timeoutCancel_1 = setTimeout(function () {
  79182. if (navbar) {
  79183. navbar.parent.style.bottom = '-' + navbarHeight_1;
  79184. }
  79185. navbarShown_1 = show;
  79186. }, visibilityTimeout);
  79187. }
  79188. };
  79189. viewerElement.parent.addEventListener('pointerout', triggerNavbar.bind(this, false));
  79190. viewerElement.parent.addEventListener('pointerdown', triggerNavbar.bind(this, true));
  79191. viewerElement.parent.addEventListener('pointerup', triggerNavbar.bind(this, false));
  79192. navbar.parent.addEventListener('pointerover', triggerNavbar.bind(this, true));
  79193. this.registerNavbarButtons();
  79194. }
  79195. var closeButton = document.getElementById('close-button');
  79196. if (closeButton) {
  79197. closeButton.addEventListener('pointerdown', function () {
  79198. _this.hideOverlayScreen();
  79199. });
  79200. }
  79201. return _super.prototype.onTemplatesLoaded.call(this);
  79202. };
  79203. DefaultViewer.prototype.registerNavbarButtons = function () {
  79204. var _this = this;
  79205. var isFullscreen = false;
  79206. var navbar = this.templateManager.getTemplate('navBar');
  79207. var viewerTemplate = this.templateManager.getTemplate('viewer');
  79208. if (!navbar || !viewerTemplate)
  79209. return;
  79210. var viewerElement = viewerTemplate.parent;
  79211. navbar.onEventTriggered.add(function (data) {
  79212. switch (data.event.type) {
  79213. case 'pointerdown':
  79214. var event_1 = data.event;
  79215. if (event_1.button === 0) {
  79216. switch (data.selector) {
  79217. case '#fullscreen-button':
  79218. if (!isFullscreen) {
  79219. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  79220. requestFullScreen.call(viewerElement);
  79221. }
  79222. else {
  79223. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  79224. exitFullscreen.call(document);
  79225. }
  79226. isFullscreen = !isFullscreen;
  79227. break;
  79228. case '#help-button':
  79229. _this.showOverlayScreen('help');
  79230. break;
  79231. }
  79232. }
  79233. break;
  79234. }
  79235. });
  79236. };
  79237. DefaultViewer.prototype.prepareContainerElement = function () {
  79238. this.containerElement.style.position = 'relative';
  79239. this.containerElement.style.display = 'flex';
  79240. };
  79241. DefaultViewer.prototype.loadModel = function (model) {
  79242. var _this = this;
  79243. if (model === void 0) { model = this.configuration.model; }
  79244. this.showLoadingScreen();
  79245. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  79246. console.log(error);
  79247. _this.hideLoadingScreen();
  79248. _this.showOverlayScreen('error');
  79249. return _this.scene;
  79250. });
  79251. };
  79252. DefaultViewer.prototype.setModelMetaData = function () {
  79253. var navbar = this.templateManager.getTemplate('navBar');
  79254. if (!navbar)
  79255. return;
  79256. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  79257. if (metadataContainer && typeof this.configuration.model === 'object') {
  79258. if (this.configuration.model.title) {
  79259. var element = metadataContainer.querySelector('span.model-title');
  79260. if (element) {
  79261. element.innerHTML = this.configuration.model.title;
  79262. }
  79263. }
  79264. if (this.configuration.model.subtitle) {
  79265. var element = metadataContainer.querySelector('span.model-subtitle');
  79266. if (element) {
  79267. element.innerHTML = this.configuration.model.subtitle;
  79268. }
  79269. }
  79270. if (this.configuration.model.thumbnail) {
  79271. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + this.configuration.model.thumbnail + "')";
  79272. }
  79273. }
  79274. };
  79275. DefaultViewer.prototype.initEnvironment = function (focusMeshes) {
  79276. if (focusMeshes === void 0) { focusMeshes = []; }
  79277. if (this.configuration.skybox) {
  79278. var texture = void 0;
  79279. if (this.configuration.skybox.cubeTexture) {
  79280. if (typeof this.configuration.skybox.cubeTexture.url === 'string') {
  79281. texture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(this.configuration.skybox.cubeTexture.url, this.scene);
  79282. }
  79283. else {
  79284. texture = babylonjs_1.CubeTexture.CreateFromImages(this.configuration.skybox.cubeTexture.url, this.scene, this.configuration.skybox.cubeTexture.noMipMap);
  79285. }
  79286. }
  79287. if (texture) {
  79288. this.extendClassWithConfig(texture, this.configuration.skybox.cubeTexture);
  79289. var scale = this.configuration.skybox.scale || this.scene.activeCamera && (this.scene.activeCamera.maxZ - this.scene.activeCamera.minZ) / 2 || 1;
  79290. var box = this.scene.createDefaultSkybox(texture, this.configuration.skybox.pbr, scale, this.configuration.skybox.blur);
  79291. if (this.configuration.skybox.material && this.configuration.skybox.material.imageProcessingConfiguration && box) {
  79292. box.material.imageProcessingConfiguration = new babylonjs_1.ImageProcessingConfiguration();
  79293. }
  79294. this.extendClassWithConfig(box, this.configuration.skybox);
  79295. box && focusMeshes.push(box);
  79296. }
  79297. }
  79298. if (this.configuration.ground) {
  79299. var groundConfig = (typeof this.configuration.ground === 'boolean') ? {} : this.configuration.ground;
  79300. var groundSize = groundConfig.size || (this.configuration.skybox && this.configuration.skybox.scale) || 3000;
  79301. var ground = babylonjs_1.Mesh.CreatePlane("BackgroundPlane", groundSize, this.scene);
  79302. var backgroundMaterial = new babylonjs_1.BackgroundMaterial('groundmat', this.scene);
  79303. ground.rotation.x = Math.PI / 2;
  79304. ground.receiveShadows = groundConfig.receiveShadows || false;
  79305. backgroundMaterial.alpha = 0.9;
  79306. backgroundMaterial.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  79307. backgroundMaterial.shadowLevel = 0.5;
  79308. backgroundMaterial.primaryLevel = 1;
  79309. backgroundMaterial.primaryColor = new babylonjs_1.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3);
  79310. backgroundMaterial.secondaryLevel = 0;
  79311. backgroundMaterial.tertiaryLevel = 0;
  79312. backgroundMaterial.useRGBColor = false;
  79313. backgroundMaterial.enableNoise = true;
  79314. if (groundConfig.material) {
  79315. this.extendClassWithConfig(ground, ground.material);
  79316. }
  79317. ground.material = backgroundMaterial;
  79318. if (this.configuration.ground === true || groundConfig.shadowOnly) {
  79319. ground.receiveShadows = true;
  79320. var diffuseTexture = new babylonjs_1.Texture("https://assets.babylonjs.com/environments/backgroundGround.png", this.scene);
  79321. diffuseTexture.gammaSpace = false;
  79322. diffuseTexture.hasAlpha = true;
  79323. backgroundMaterial.diffuseTexture = diffuseTexture;
  79324. }
  79325. else if (groundConfig.mirror) {
  79326. var mirror = new babylonjs_1.MirrorTexture("mirror", 512, this.scene);
  79327. mirror.mirrorPlane = new babylonjs_1.Plane(0, -1, 0, 0);
  79328. mirror.renderList = mirror.renderList || [];
  79329. focusMeshes.length && focusMeshes.forEach(function (m) {
  79330. m && mirror.renderList && mirror.renderList.push(m);
  79331. });
  79332. backgroundMaterial.reflectionTexture = mirror;
  79333. }
  79334. else {
  79335. if (groundConfig.material) {
  79336. if (groundConfig.material.diffuseTexture) {
  79337. var diffuseTexture = new babylonjs_1.Texture(groundConfig.material.diffuseTexture, this.scene);
  79338. backgroundMaterial.diffuseTexture = diffuseTexture;
  79339. }
  79340. }
  79341. }
  79342. if (this.configuration.ground === true) {
  79343. ground.receiveShadows = true;
  79344. if (ground.material)
  79345. ground.material.alpha = 0.4;
  79346. }
  79347. this.extendClassWithConfig(ground, groundConfig);
  79348. }
  79349. return Promise.resolve(this.scene);
  79350. };
  79351. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  79352. var _this = this;
  79353. var template = this.templateManager.getTemplate('overlay');
  79354. if (!template)
  79355. return Promise.reject('Overlay template not found');
  79356. return template.show((function (template) {
  79357. var canvasRect = _this.containerElement.getBoundingClientRect();
  79358. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  79359. template.parent.style.display = 'flex';
  79360. template.parent.style.width = canvasRect.width + "px";
  79361. template.parent.style.height = canvasRect.height + "px";
  79362. template.parent.style.opacity = "1";
  79363. var subTemplate = _this.templateManager.getTemplate(subScreen);
  79364. if (!subTemplate) {
  79365. return Promise.reject(subScreen + ' template not found');
  79366. }
  79367. return subTemplate.show((function (template) {
  79368. template.parent.style.display = 'flex';
  79369. return Promise.resolve(template);
  79370. }));
  79371. }));
  79372. };
  79373. DefaultViewer.prototype.hideOverlayScreen = function () {
  79374. var template = this.templateManager.getTemplate('overlay');
  79375. if (!template)
  79376. return Promise.reject('Overlay template not found');
  79377. return template.hide((function (template) {
  79378. template.parent.style.opacity = "0";
  79379. var onTransitionEnd = function () {
  79380. template.parent.removeEventListener("transitionend", onTransitionEnd);
  79381. template.parent.style.display = 'none';
  79382. };
  79383. template.parent.addEventListener("transitionend", onTransitionEnd);
  79384. var overlays = template.parent.querySelectorAll('.overlay');
  79385. if (overlays) {
  79386. for (var i = 0; i < overlays.length; ++i) {
  79387. var htmlElement = overlays.item(i);
  79388. htmlElement.style.display = 'none';
  79389. }
  79390. }
  79391. return Promise.resolve(template);
  79392. }));
  79393. };
  79394. DefaultViewer.prototype.showLoadingScreen = function () {
  79395. var _this = this;
  79396. var template = this.templateManager.getTemplate('loadingScreen');
  79397. if (!template)
  79398. return Promise.reject('oading Screen template not found');
  79399. return template.show((function (template) {
  79400. var canvasRect = _this.containerElement.getBoundingClientRect();
  79401. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  79402. template.parent.style.display = 'flex';
  79403. template.parent.style.width = canvasRect.width + "px";
  79404. template.parent.style.height = canvasRect.height + "px";
  79405. template.parent.style.opacity = "1";
  79406. template.parent.style.backgroundColor = "black";
  79407. return Promise.resolve(template);
  79408. }));
  79409. };
  79410. DefaultViewer.prototype.hideLoadingScreen = function () {
  79411. var template = this.templateManager.getTemplate('loadingScreen');
  79412. if (!template)
  79413. return Promise.reject('oading Screen template not found');
  79414. return template.hide((function (template) {
  79415. template.parent.style.opacity = "0";
  79416. var onTransitionEnd = function () {
  79417. template.parent.removeEventListener("transitionend", onTransitionEnd);
  79418. template.parent.style.display = 'none';
  79419. };
  79420. template.parent.addEventListener("transitionend", onTransitionEnd);
  79421. return Promise.resolve(template);
  79422. }));
  79423. };
  79424. DefaultViewer.prototype.setupLights = function (focusMeshes) {
  79425. var _this = this;
  79426. if (focusMeshes === void 0) { focusMeshes = []; }
  79427. var sceneConfig = this.configuration.scene || { defaultLight: true };
  79428. if (!sceneConfig.defaultLight && (this.configuration.lights && Object.keys(this.configuration.lights).length)) {
  79429. this.scene.lights.forEach(function (l) {
  79430. l.dispose();
  79431. });
  79432. Object.keys(this.configuration.lights).forEach(function (name, idx) {
  79433. var lightConfig = _this.configuration.lights && _this.configuration.lights[name] || { name: name, type: 0 };
  79434. lightConfig.name = name;
  79435. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  79436. if (!constructor)
  79437. return;
  79438. var light = constructor();
  79439. if (light.isEnabled() !== !lightConfig.disabled) {
  79440. light.setEnabled(!lightConfig.disabled);
  79441. }
  79442. _this.extendClassWithConfig(light, lightConfig);
  79443. if (light instanceof babylonjs_1.ShadowLight) {
  79444. if (lightConfig.shadowEnabled) {
  79445. var shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  79446. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  79447. var shadownMap = shadowGenerator.getShadowMap();
  79448. if (!shadownMap)
  79449. return;
  79450. var renderList = shadownMap.renderList;
  79451. for (var index = 0; index < focusMeshes.length; index++) {
  79452. renderList && renderList.push(focusMeshes[index]);
  79453. }
  79454. }
  79455. }
  79456. });
  79457. }
  79458. };
  79459. DefaultViewer.prototype.setupCamera = function (focusMeshes) {
  79460. if (focusMeshes === void 0) { focusMeshes = []; }
  79461. var cameraConfig = this.configuration.camera || {};
  79462. var sceneConfig = this.configuration.scene || { autoRotate: false, defaultCamera: true };
  79463. if (!this.configuration.camera && sceneConfig.defaultCamera) {
  79464. if (sceneConfig.autoRotate) {
  79465. this.camera.useAutoRotationBehavior = true;
  79466. }
  79467. return;
  79468. }
  79469. if (cameraConfig.position) {
  79470. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  79471. }
  79472. if (cameraConfig.rotation) {
  79473. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  79474. }
  79475. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  79476. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  79477. if (cameraConfig.behaviors) {
  79478. for (var name_1 in cameraConfig.behaviors) {
  79479. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  79480. }
  79481. }
  79482. ;
  79483. if (sceneConfig.autoRotate) {
  79484. this.camera.useAutoRotationBehavior = true;
  79485. }
  79486. };
  79487. DefaultViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  79488. var behavior;
  79489. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  79490. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  79491. switch (type) {
  79492. case 0:
  79493. behavior = new babylonjs_1.AutoRotationBehavior();
  79494. break;
  79495. case 1:
  79496. behavior = new babylonjs_1.BouncingBehavior();
  79497. break;
  79498. case 2:
  79499. behavior = new babylonjs_1.FramingBehavior();
  79500. break;
  79501. default:
  79502. behavior = null;
  79503. break;
  79504. }
  79505. if (behavior) {
  79506. if (typeof behaviorConfig === "object") {
  79507. this.extendClassWithConfig(behavior, behaviorConfig);
  79508. }
  79509. this.camera.addBehavior(behavior);
  79510. }
  79511. switch (type) {
  79512. case 0:
  79513. break;
  79514. case 1:
  79515. break;
  79516. case 2:
  79517. if (config.zoomOnBoundingInfo) {
  79518. var meshes = payload;
  79519. var bounding = meshes[0].getHierarchyBoundingVectors();
  79520. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  79521. }
  79522. break;
  79523. }
  79524. };
  79525. DefaultViewer.prototype.extendClassWithConfig = function (object, config) {
  79526. var _this = this;
  79527. if (!config)
  79528. return;
  79529. Object.keys(config).forEach(function (key) {
  79530. if (key in object && typeof object[key] !== 'function') {
  79531. if (typeof object[key] === 'function')
  79532. return;
  79533. if (typeof object[key] === 'object') {
  79534. _this.extendClassWithConfig(object[key], config[key]);
  79535. }
  79536. else {
  79537. object[key] = config[key];
  79538. }
  79539. }
  79540. });
  79541. };
  79542. return DefaultViewer;
  79543. }(viewer_1.AbstractViewer));
  79544. exports.DefaultViewer = DefaultViewer;
  79545. /***/ }),
  79546. /* 6 */
  79547. /***/ (function(module, exports, __webpack_require__) {
  79548. "use strict";
  79549. Object.defineProperty(exports, "__esModule", { value: true });
  79550. var viewerManager_1 = __webpack_require__(4);
  79551. var templateManager_1 = __webpack_require__(17);
  79552. var loader_1 = __webpack_require__(19);
  79553. var babylonjs_1 = __webpack_require__(0);
  79554. var promiseObservable_1 = __webpack_require__(28);
  79555. var AbstractViewer = (function () {
  79556. function AbstractViewer(containerElement, initialConfiguration) {
  79557. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  79558. var _this = this;
  79559. this.containerElement = containerElement;
  79560. if (containerElement.id) {
  79561. this.baseId = containerElement.id;
  79562. }
  79563. else {
  79564. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  79565. }
  79566. this.onSceneInitObservable = new promiseObservable_1.PromiseObservable();
  79567. this.onEngineInitObservable = new promiseObservable_1.PromiseObservable();
  79568. this.onModelLoadedObservable = new promiseObservable_1.PromiseObservable();
  79569. viewerManager_1.viewerManager.addViewer(this);
  79570. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  79571. this.prepareContainerElement();
  79572. loader_1.default.loadConfiguration(initialConfiguration).then(function (configuration) {
  79573. _this.configuration = configuration;
  79574. if (_this.configuration.observers) {
  79575. if (_this.configuration.observers.onEngineInit) {
  79576. _this.onEngineInitObservable.add(window[_this.configuration.observers.onEngineInit]);
  79577. }
  79578. if (_this.configuration.observers.onSceneInit) {
  79579. _this.onSceneInitObservable.add(window[_this.configuration.observers.onSceneInit]);
  79580. }
  79581. if (_this.configuration.observers.onModelLoaded) {
  79582. _this.onModelLoadedObservable.add(window[_this.configuration.observers.onModelLoaded]);
  79583. }
  79584. }
  79585. var templateConfiguration = _this.configuration.templates || {};
  79586. _this.templateManager.initTemplate(templateConfiguration);
  79587. _this.templateManager.onAllLoaded.add(function () {
  79588. _this.onTemplatesLoaded();
  79589. });
  79590. });
  79591. }
  79592. AbstractViewer.prototype.getBaseId = function () {
  79593. return this.baseId;
  79594. };
  79595. AbstractViewer.prototype.onTemplatesLoaded = function () {
  79596. var _this = this;
  79597. return this.initEngine().then(function () {
  79598. return _this.loadModel();
  79599. }).then(function () {
  79600. return _this;
  79601. });
  79602. };
  79603. AbstractViewer.prototype.initEngine = function () {
  79604. var _this = this;
  79605. var canvasElement = this.templateManager.getCanvas();
  79606. if (!canvasElement) {
  79607. return Promise.reject('Canvas element not found!');
  79608. }
  79609. var config = this.configuration.engine || {};
  79610. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing);
  79611. babylonjs_1.Database.IDBStorageEnabled = false;
  79612. window.addEventListener('resize', function () {
  79613. _this.engine.resize();
  79614. });
  79615. this.engine.runRenderLoop(function () {
  79616. _this.scene && _this.scene.render();
  79617. });
  79618. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  79619. this.engine.setHardwareScalingLevel(scale);
  79620. return this.onEngineInitObservable.notifyWithPromise(this.engine).then(function () {
  79621. return _this.engine;
  79622. });
  79623. };
  79624. AbstractViewer.prototype.initScene = function () {
  79625. var _this = this;
  79626. if (this.scene) {
  79627. this.scene.dispose();
  79628. }
  79629. this.scene = new babylonjs_1.Scene(this.engine);
  79630. this.scene.createDefaultCameraOrLight(true, true, true);
  79631. if (this.configuration.scene && this.configuration.scene.debug) {
  79632. this.scene.debugLayer.show();
  79633. }
  79634. return this.onSceneInitObservable.notifyWithPromise(this.scene).then(function () {
  79635. return _this.scene;
  79636. });
  79637. };
  79638. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  79639. var _this = this;
  79640. if (model === void 0) { model = this.configuration.model; }
  79641. if (clearScene === void 0) { clearScene = true; }
  79642. var modelUrl = (typeof model === 'string') ? model : model.url;
  79643. var parts = modelUrl.split('/');
  79644. var filename = parts.pop();
  79645. var base = parts.join('/') + '/';
  79646. var plugin = (typeof model === 'string') ? undefined : model.loader;
  79647. return Promise.resolve().then(function () {
  79648. if (!_this.scene || clearScene)
  79649. return _this.initScene();
  79650. else
  79651. return _this.scene;
  79652. }).then(function () {
  79653. return new Promise(function (resolve, reject) {
  79654. babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  79655. resolve(meshes);
  79656. }, undefined, function (e, m, exception) {
  79657. console.log(m, exception);
  79658. reject(m);
  79659. }, plugin);
  79660. });
  79661. }).then(function (meshes) {
  79662. return _this.onModelLoadedObservable.notifyWithPromise(meshes).then(function () {
  79663. return _this.scene;
  79664. });
  79665. });
  79666. };
  79667. return AbstractViewer;
  79668. }());
  79669. exports.AbstractViewer = AbstractViewer;
  79670. /***/ }),
  79671. /* 7 */
  79672. /***/ (function(module, exports) {
  79673. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  79674. /***/ }),
  79675. /* 8 */
  79676. /***/ (function(module, exports) {
  79677. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  79678. /***/ }),
  79679. /* 9 */
  79680. /***/ (function(module, exports) {
  79681. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  79682. /***/ }),
  79683. /* 10 */
  79684. /***/ (function(module, exports) {
  79685. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  79686. /***/ }),
  79687. /* 11 */
  79688. /***/ (function(module, exports) {
  79689. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  79690. /***/ }),
  79691. /* 12 */
  79692. /***/ (function(module, exports) {
  79693. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  79694. /***/ }),
  79695. /* 13 */
  79696. /***/ (function(module, exports) {
  79697. module.exports = "Error loading the model";
  79698. /***/ }),
  79699. /* 14 */
  79700. /***/ (function(module, exports, __webpack_require__) {
  79701. "use strict";
  79702. /* WEBPACK VAR INJECTION */(function(global) {
  79703. Object.defineProperty(exports, "__esModule", { value: true });
  79704. var mappers_1 = __webpack_require__(2);
  79705. exports.mapperManager = mappers_1.mapperManager;
  79706. var viewerManager_1 = __webpack_require__(4);
  79707. exports.viewerManager = viewerManager_1.viewerManager;
  79708. var defaultViewer_1 = __webpack_require__(5);
  79709. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  79710. var viewer_1 = __webpack_require__(6);
  79711. exports.AbstractViewer = viewer_1.AbstractViewer;
  79712. __webpack_require__(0);
  79713. __webpack_require__(29);
  79714. __webpack_require__(30);
  79715. var initializer_1 = __webpack_require__(31);
  79716. exports.InitTags = initializer_1.InitTags;
  79717. global.Promise = typeof Promise === 'undefined' ? __webpack_require__(32).Promise : Promise;
  79718. exports.disableInit = false;
  79719. document.addEventListener("DOMContentLoaded", function (event) {
  79720. if (exports.disableInit)
  79721. return;
  79722. initializer_1.InitTags();
  79723. });
  79724. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  79725. /***/ }),
  79726. /* 15 */
  79727. /***/ (function(module, exports, __webpack_require__) {
  79728. var require;var require;/*
  79729. * Copyright (c) 2015 cannon.js Authors
  79730. *
  79731. * Permission is hereby granted, free of charge, to any person
  79732. * obtaining a copy of this software and associated documentation
  79733. * files (the "Software"), to deal in the Software without
  79734. * restriction, including without limitation the rights to use, copy,
  79735. * modify, merge, publish, distribute, sublicense, and/or sell copies
  79736. * of the Software, and to permit persons to whom the Software is
  79737. * furnished to do so, subject to the following conditions:
  79738. *
  79739. * The above copyright notice and this permission notice shall be
  79740. * included in all copies or substantial portions of the Software.
  79741. *
  79742. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  79743. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  79744. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  79745. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  79746. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  79747. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  79748. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  79749. */
  79750. !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){
  79751. module.exports={
  79752. "name": "cannon",
  79753. "version": "0.6.2",
  79754. "description": "A lightweight 3D physics engine written in JavaScript.",
  79755. "homepage": "https://github.com/schteppe/cannon.js",
  79756. "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
  79757. "keywords": [
  79758. "cannon.js",
  79759. "cannon",
  79760. "physics",
  79761. "engine",
  79762. "3d"
  79763. ],
  79764. "main": "./build/cannon.js",
  79765. "engines": {
  79766. "node": "*"
  79767. },
  79768. "repository": {
  79769. "type": "git",
  79770. "url": "https://github.com/schteppe/cannon.js.git"
  79771. },
  79772. "bugs": {
  79773. "url": "https://github.com/schteppe/cannon.js/issues"
  79774. },
  79775. "licenses": [
  79776. {
  79777. "type": "MIT"
  79778. }
  79779. ],
  79780. "devDependencies": {
  79781. "jshint": "latest",
  79782. "uglify-js": "latest",
  79783. "nodeunit": "^0.9.0",
  79784. "grunt": "~0.4.0",
  79785. "grunt-contrib-jshint": "~0.1.1",
  79786. "grunt-contrib-nodeunit": "^0.4.1",
  79787. "grunt-contrib-concat": "~0.1.3",
  79788. "grunt-contrib-uglify": "^0.5.1",
  79789. "grunt-browserify": "^2.1.4",
  79790. "grunt-contrib-yuidoc": "^0.5.2",
  79791. "browserify": "*"
  79792. },
  79793. "dependencies": {}
  79794. }
  79795. },{}],2:[function(_dereq_,module,exports){
  79796. // Export classes
  79797. module.exports = {
  79798. version : _dereq_('../package.json').version,
  79799. AABB : _dereq_('./collision/AABB'),
  79800. ArrayCollisionMatrix : _dereq_('./collision/ArrayCollisionMatrix'),
  79801. Body : _dereq_('./objects/Body'),
  79802. Box : _dereq_('./shapes/Box'),
  79803. Broadphase : _dereq_('./collision/Broadphase'),
  79804. Constraint : _dereq_('./constraints/Constraint'),
  79805. ContactEquation : _dereq_('./equations/ContactEquation'),
  79806. Narrowphase : _dereq_('./world/Narrowphase'),
  79807. ConeTwistConstraint : _dereq_('./constraints/ConeTwistConstraint'),
  79808. ContactMaterial : _dereq_('./material/ContactMaterial'),
  79809. ConvexPolyhedron : _dereq_('./shapes/ConvexPolyhedron'),
  79810. Cylinder : _dereq_('./shapes/Cylinder'),
  79811. DistanceConstraint : _dereq_('./constraints/DistanceConstraint'),
  79812. Equation : _dereq_('./equations/Equation'),
  79813. EventTarget : _dereq_('./utils/EventTarget'),
  79814. FrictionEquation : _dereq_('./equations/FrictionEquation'),
  79815. GSSolver : _dereq_('./solver/GSSolver'),
  79816. GridBroadphase : _dereq_('./collision/GridBroadphase'),
  79817. Heightfield : _dereq_('./shapes/Heightfield'),
  79818. HingeConstraint : _dereq_('./constraints/HingeConstraint'),
  79819. LockConstraint : _dereq_('./constraints/LockConstraint'),
  79820. Mat3 : _dereq_('./math/Mat3'),
  79821. Material : _dereq_('./material/Material'),
  79822. NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'),
  79823. ObjectCollisionMatrix : _dereq_('./collision/ObjectCollisionMatrix'),
  79824. Pool : _dereq_('./utils/Pool'),
  79825. Particle : _dereq_('./shapes/Particle'),
  79826. Plane : _dereq_('./shapes/Plane'),
  79827. PointToPointConstraint : _dereq_('./constraints/PointToPointConstraint'),
  79828. Quaternion : _dereq_('./math/Quaternion'),
  79829. Ray : _dereq_('./collision/Ray'),
  79830. RaycastVehicle : _dereq_('./objects/RaycastVehicle'),
  79831. RaycastResult : _dereq_('./collision/RaycastResult'),
  79832. RigidVehicle : _dereq_('./objects/RigidVehicle'),
  79833. RotationalEquation : _dereq_('./equations/RotationalEquation'),
  79834. RotationalMotorEquation : _dereq_('./equations/RotationalMotorEquation'),
  79835. SAPBroadphase : _dereq_('./collision/SAPBroadphase'),
  79836. SPHSystem : _dereq_('./objects/SPHSystem'),
  79837. Shape : _dereq_('./shapes/Shape'),
  79838. Solver : _dereq_('./solver/Solver'),
  79839. Sphere : _dereq_('./shapes/Sphere'),
  79840. SplitSolver : _dereq_('./solver/SplitSolver'),
  79841. Spring : _dereq_('./objects/Spring'),
  79842. Trimesh : _dereq_('./shapes/Trimesh'),
  79843. Vec3 : _dereq_('./math/Vec3'),
  79844. Vec3Pool : _dereq_('./utils/Vec3Pool'),
  79845. World : _dereq_('./world/World'),
  79846. };
  79847. },{"../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){
  79848. var Vec3 = _dereq_('../math/Vec3');
  79849. var Utils = _dereq_('../utils/Utils');
  79850. module.exports = AABB;
  79851. /**
  79852. * Axis aligned bounding box class.
  79853. * @class AABB
  79854. * @constructor
  79855. * @param {Object} [options]
  79856. * @param {Vec3} [options.upperBound]
  79857. * @param {Vec3} [options.lowerBound]
  79858. */
  79859. function AABB(options){
  79860. options = options || {};
  79861. /**
  79862. * The lower bound of the bounding box.
  79863. * @property lowerBound
  79864. * @type {Vec3}
  79865. */
  79866. this.lowerBound = new Vec3();
  79867. if(options.lowerBound){
  79868. this.lowerBound.copy(options.lowerBound);
  79869. }
  79870. /**
  79871. * The upper bound of the bounding box.
  79872. * @property upperBound
  79873. * @type {Vec3}
  79874. */
  79875. this.upperBound = new Vec3();
  79876. if(options.upperBound){
  79877. this.upperBound.copy(options.upperBound);
  79878. }
  79879. }
  79880. var tmp = new Vec3();
  79881. /**
  79882. * Set the AABB bounds from a set of points.
  79883. * @method setFromPoints
  79884. * @param {Array} points An array of Vec3's.
  79885. * @param {Vec3} position
  79886. * @param {Quaternion} quaternion
  79887. * @param {number} skinSize
  79888. * @return {AABB} The self object
  79889. */
  79890. AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
  79891. var l = this.lowerBound,
  79892. u = this.upperBound,
  79893. q = quaternion;
  79894. // Set to the first point
  79895. l.copy(points[0]);
  79896. if(q){
  79897. q.vmult(l, l);
  79898. }
  79899. u.copy(l);
  79900. for(var i = 1; i<points.length; i++){
  79901. var p = points[i];
  79902. if(q){
  79903. q.vmult(p, tmp);
  79904. p = tmp;
  79905. }
  79906. if(p.x > u.x){ u.x = p.x; }
  79907. if(p.x < l.x){ l.x = p.x; }
  79908. if(p.y > u.y){ u.y = p.y; }
  79909. if(p.y < l.y){ l.y = p.y; }
  79910. if(p.z > u.z){ u.z = p.z; }
  79911. if(p.z < l.z){ l.z = p.z; }
  79912. }
  79913. // Add offset
  79914. if (position) {
  79915. position.vadd(l, l);
  79916. position.vadd(u, u);
  79917. }
  79918. if(skinSize){
  79919. l.x -= skinSize;
  79920. l.y -= skinSize;
  79921. l.z -= skinSize;
  79922. u.x += skinSize;
  79923. u.y += skinSize;
  79924. u.z += skinSize;
  79925. }
  79926. return this;
  79927. };
  79928. /**
  79929. * Copy bounds from an AABB to this AABB
  79930. * @method copy
  79931. * @param {AABB} aabb Source to copy from
  79932. * @return {AABB} The this object, for chainability
  79933. */
  79934. AABB.prototype.copy = function(aabb){
  79935. this.lowerBound.copy(aabb.lowerBound);
  79936. this.upperBound.copy(aabb.upperBound);
  79937. return this;
  79938. };
  79939. /**
  79940. * Clone an AABB
  79941. * @method clone
  79942. */
  79943. AABB.prototype.clone = function(){
  79944. return new AABB().copy(this);
  79945. };
  79946. /**
  79947. * Extend this AABB so that it covers the given AABB too.
  79948. * @method extend
  79949. * @param {AABB} aabb
  79950. */
  79951. AABB.prototype.extend = function(aabb){
  79952. // Extend lower bound
  79953. var l = aabb.lowerBound.x;
  79954. if(this.lowerBound.x > l){
  79955. this.lowerBound.x = l;
  79956. }
  79957. // Upper
  79958. var u = aabb.upperBound.x;
  79959. if(this.upperBound.x < u){
  79960. this.upperBound.x = u;
  79961. }
  79962. // Extend lower bound
  79963. var l = aabb.lowerBound.y;
  79964. if(this.lowerBound.y > l){
  79965. this.lowerBound.y = l;
  79966. }
  79967. // Upper
  79968. var u = aabb.upperBound.y;
  79969. if(this.upperBound.y < u){
  79970. this.upperBound.y = u;
  79971. }
  79972. // Extend lower bound
  79973. var l = aabb.lowerBound.z;
  79974. if(this.lowerBound.z > l){
  79975. this.lowerBound.z = l;
  79976. }
  79977. // Upper
  79978. var u = aabb.upperBound.z;
  79979. if(this.upperBound.z < u){
  79980. this.upperBound.z = u;
  79981. }
  79982. };
  79983. /**
  79984. * Returns true if the given AABB overlaps this AABB.
  79985. * @method overlaps
  79986. * @param {AABB} aabb
  79987. * @return {Boolean}
  79988. */
  79989. AABB.prototype.overlaps = function(aabb){
  79990. var l1 = this.lowerBound,
  79991. u1 = this.upperBound,
  79992. l2 = aabb.lowerBound,
  79993. u2 = aabb.upperBound;
  79994. // l2 u2
  79995. // |---------|
  79996. // |--------|
  79997. // l1 u1
  79998. return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) &&
  79999. ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) &&
  80000. ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
  80001. };
  80002. /**
  80003. * Returns true if the given AABB is fully contained in this AABB.
  80004. * @method contains
  80005. * @param {AABB} aabb
  80006. * @return {Boolean}
  80007. */
  80008. AABB.prototype.contains = function(aabb){
  80009. var l1 = this.lowerBound,
  80010. u1 = this.upperBound,
  80011. l2 = aabb.lowerBound,
  80012. u2 = aabb.upperBound;
  80013. // l2 u2
  80014. // |---------|
  80015. // |---------------|
  80016. // l1 u1
  80017. return (
  80018. (l1.x <= l2.x && u1.x >= u2.x) &&
  80019. (l1.y <= l2.y && u1.y >= u2.y) &&
  80020. (l1.z <= l2.z && u1.z >= u2.z)
  80021. );
  80022. };
  80023. /**
  80024. * @method getCorners
  80025. * @param {Vec3} a
  80026. * @param {Vec3} b
  80027. * @param {Vec3} c
  80028. * @param {Vec3} d
  80029. * @param {Vec3} e
  80030. * @param {Vec3} f
  80031. * @param {Vec3} g
  80032. * @param {Vec3} h
  80033. */
  80034. AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
  80035. var l = this.lowerBound,
  80036. u = this.upperBound;
  80037. a.copy(l);
  80038. b.set( u.x, l.y, l.z );
  80039. c.set( u.x, u.y, l.z );
  80040. d.set( l.x, u.y, u.z );
  80041. e.set( u.x, l.y, l.z );
  80042. f.set( l.x, u.y, l.z );
  80043. g.set( l.x, l.y, u.z );
  80044. h.copy(u);
  80045. };
  80046. var transformIntoFrame_corners = [
  80047. new Vec3(),
  80048. new Vec3(),
  80049. new Vec3(),
  80050. new Vec3(),
  80051. new Vec3(),
  80052. new Vec3(),
  80053. new Vec3(),
  80054. new Vec3()
  80055. ];
  80056. /**
  80057. * Get the representation of an AABB in another frame.
  80058. * @method toLocalFrame
  80059. * @param {Transform} frame
  80060. * @param {AABB} target
  80061. * @return {AABB} The "target" AABB object.
  80062. */
  80063. AABB.prototype.toLocalFrame = function(frame, target){
  80064. var corners = transformIntoFrame_corners;
  80065. var a = corners[0];
  80066. var b = corners[1];
  80067. var c = corners[2];
  80068. var d = corners[3];
  80069. var e = corners[4];
  80070. var f = corners[5];
  80071. var g = corners[6];
  80072. var h = corners[7];
  80073. // Get corners in current frame
  80074. this.getCorners(a, b, c, d, e, f, g, h);
  80075. // Transform them to new local frame
  80076. for(var i=0; i !== 8; i++){
  80077. var corner = corners[i];
  80078. frame.pointToLocal(corner, corner);
  80079. }
  80080. return target.setFromPoints(corners);
  80081. };
  80082. /**
  80083. * Get the representation of an AABB in the global frame.
  80084. * @method toWorldFrame
  80085. * @param {Transform} frame
  80086. * @param {AABB} target
  80087. * @return {AABB} The "target" AABB object.
  80088. */
  80089. AABB.prototype.toWorldFrame = function(frame, target){
  80090. var corners = transformIntoFrame_corners;
  80091. var a = corners[0];
  80092. var b = corners[1];
  80093. var c = corners[2];
  80094. var d = corners[3];
  80095. var e = corners[4];
  80096. var f = corners[5];
  80097. var g = corners[6];
  80098. var h = corners[7];
  80099. // Get corners in current frame
  80100. this.getCorners(a, b, c, d, e, f, g, h);
  80101. // Transform them to new local frame
  80102. for(var i=0; i !== 8; i++){
  80103. var corner = corners[i];
  80104. frame.pointToWorld(corner, corner);
  80105. }
  80106. return target.setFromPoints(corners);
  80107. };
  80108. },{"../math/Vec3":30,"../utils/Utils":53}],4:[function(_dereq_,module,exports){
  80109. module.exports = ArrayCollisionMatrix;
  80110. /**
  80111. * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  80112. * @class ArrayCollisionMatrix
  80113. * @constructor
  80114. */
  80115. function ArrayCollisionMatrix() {
  80116. /**
  80117. * The matrix storage
  80118. * @property matrix
  80119. * @type {Array}
  80120. */
  80121. this.matrix = [];
  80122. }
  80123. /**
  80124. * Get an element
  80125. * @method get
  80126. * @param {Number} i
  80127. * @param {Number} j
  80128. * @return {Number}
  80129. */
  80130. ArrayCollisionMatrix.prototype.get = function(i, j) {
  80131. i = i.index;
  80132. j = j.index;
  80133. if (j > i) {
  80134. var temp = j;
  80135. j = i;
  80136. i = temp;
  80137. }
  80138. return this.matrix[(i*(i + 1)>>1) + j-1];
  80139. };
  80140. /**
  80141. * Set an element
  80142. * @method set
  80143. * @param {Number} i
  80144. * @param {Number} j
  80145. * @param {Number} value
  80146. */
  80147. ArrayCollisionMatrix.prototype.set = function(i, j, value) {
  80148. i = i.index;
  80149. j = j.index;
  80150. if (j > i) {
  80151. var temp = j;
  80152. j = i;
  80153. i = temp;
  80154. }
  80155. this.matrix[(i*(i + 1)>>1) + j-1] = value ? 1 : 0;
  80156. };
  80157. /**
  80158. * Sets all elements to zero
  80159. * @method reset
  80160. */
  80161. ArrayCollisionMatrix.prototype.reset = function() {
  80162. for (var i=0, l=this.matrix.length; i!==l; i++) {
  80163. this.matrix[i]=0;
  80164. }
  80165. };
  80166. /**
  80167. * Sets the max number of objects
  80168. * @method setNumObjects
  80169. * @param {Number} n
  80170. */
  80171. ArrayCollisionMatrix.prototype.setNumObjects = function(n) {
  80172. this.matrix.length = n*(n-1)>>1;
  80173. };
  80174. },{}],5:[function(_dereq_,module,exports){
  80175. var Body = _dereq_('../objects/Body');
  80176. var Vec3 = _dereq_('../math/Vec3');
  80177. var Quaternion = _dereq_('../math/Quaternion');
  80178. var Shape = _dereq_('../shapes/Shape');
  80179. var Plane = _dereq_('../shapes/Plane');
  80180. module.exports = Broadphase;
  80181. /**
  80182. * Base class for broadphase implementations
  80183. * @class Broadphase
  80184. * @constructor
  80185. * @author schteppe
  80186. */
  80187. function Broadphase(){
  80188. /**
  80189. * The world to search for collisions in.
  80190. * @property world
  80191. * @type {World}
  80192. */
  80193. this.world = null;
  80194. /**
  80195. * If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres.
  80196. * @property useBoundingBoxes
  80197. * @type {Boolean}
  80198. */
  80199. this.useBoundingBoxes = false;
  80200. /**
  80201. * Set to true if the objects in the world moved.
  80202. * @property {Boolean} dirty
  80203. */
  80204. this.dirty = true;
  80205. }
  80206. /**
  80207. * Get the collision pairs from the world
  80208. * @method collisionPairs
  80209. * @param {World} world The world to search in
  80210. * @param {Array} p1 Empty array to be filled with body objects
  80211. * @param {Array} p2 Empty array to be filled with body objects
  80212. */
  80213. Broadphase.prototype.collisionPairs = function(world,p1,p2){
  80214. throw new Error("collisionPairs not implemented for this BroadPhase class!");
  80215. };
  80216. /**
  80217. * Check if a body pair needs to be intersection tested at all.
  80218. * @method needBroadphaseCollision
  80219. * @param {Body} bodyA
  80220. * @param {Body} bodyB
  80221. * @return {bool}
  80222. */
  80223. var Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC = Body.STATIC | Body.KINEMATIC;
  80224. Broadphase.prototype.needBroadphaseCollision = function(bodyA,bodyB){
  80225. // Check collision filter masks
  80226. if( (bodyA.collisionFilterGroup & bodyB.collisionFilterMask)===0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask)===0){
  80227. return false;
  80228. }
  80229. // Check types
  80230. if(((bodyA.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyA.sleepState === Body.SLEEPING) &&
  80231. ((bodyB.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyB.sleepState === Body.SLEEPING)) {
  80232. // Both bodies are static, kinematic or sleeping. Skip.
  80233. return false;
  80234. }
  80235. return true;
  80236. };
  80237. /**
  80238. * Check if the bounding volumes of two bodies intersect.
  80239. * @method intersectionTest
  80240. * @param {Body} bodyA
  80241. * @param {Body} bodyB
  80242. * @param {array} pairs1
  80243. * @param {array} pairs2
  80244. */
  80245. Broadphase.prototype.intersectionTest = function(bodyA, bodyB, pairs1, pairs2){
  80246. if(this.useBoundingBoxes){
  80247. this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2);
  80248. } else {
  80249. this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2);
  80250. }
  80251. };
  80252. /**
  80253. * Check if the bounding spheres of two bodies are intersecting.
  80254. * @method doBoundingSphereBroadphase
  80255. * @param {Body} bodyA
  80256. * @param {Body} bodyB
  80257. * @param {Array} pairs1 bodyA is appended to this array if intersection
  80258. * @param {Array} pairs2 bodyB is appended to this array if intersection
  80259. */
  80260. var Broadphase_collisionPairs_r = new Vec3(), // Temp objects
  80261. Broadphase_collisionPairs_normal = new Vec3(),
  80262. Broadphase_collisionPairs_quat = new Quaternion(),
  80263. Broadphase_collisionPairs_relpos = new Vec3();
  80264. Broadphase.prototype.doBoundingSphereBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  80265. var r = Broadphase_collisionPairs_r;
  80266. bodyB.position.vsub(bodyA.position,r);
  80267. var boundingRadiusSum2 = Math.pow(bodyA.boundingRadius + bodyB.boundingRadius, 2);
  80268. var norm2 = r.norm2();
  80269. if(norm2 < boundingRadiusSum2){
  80270. pairs1.push(bodyA);
  80271. pairs2.push(bodyB);
  80272. }
  80273. };
  80274. /**
  80275. * Check if the bounding boxes of two bodies are intersecting.
  80276. * @method doBoundingBoxBroadphase
  80277. * @param {Body} bodyA
  80278. * @param {Body} bodyB
  80279. * @param {Array} pairs1
  80280. * @param {Array} pairs2
  80281. */
  80282. Broadphase.prototype.doBoundingBoxBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  80283. if(bodyA.aabbNeedsUpdate){
  80284. bodyA.computeAABB();
  80285. }
  80286. if(bodyB.aabbNeedsUpdate){
  80287. bodyB.computeAABB();
  80288. }
  80289. // Check AABB / AABB
  80290. if(bodyA.aabb.overlaps(bodyB.aabb)){
  80291. pairs1.push(bodyA);
  80292. pairs2.push(bodyB);
  80293. }
  80294. };
  80295. /**
  80296. * Removes duplicate pairs from the pair arrays.
  80297. * @method makePairsUnique
  80298. * @param {Array} pairs1
  80299. * @param {Array} pairs2
  80300. */
  80301. var Broadphase_makePairsUnique_temp = { keys:[] },
  80302. Broadphase_makePairsUnique_p1 = [],
  80303. Broadphase_makePairsUnique_p2 = [];
  80304. Broadphase.prototype.makePairsUnique = function(pairs1,pairs2){
  80305. var t = Broadphase_makePairsUnique_temp,
  80306. p1 = Broadphase_makePairsUnique_p1,
  80307. p2 = Broadphase_makePairsUnique_p2,
  80308. N = pairs1.length;
  80309. for(var i=0; i!==N; i++){
  80310. p1[i] = pairs1[i];
  80311. p2[i] = pairs2[i];
  80312. }
  80313. pairs1.length = 0;
  80314. pairs2.length = 0;
  80315. for(var i=0; i!==N; i++){
  80316. var id1 = p1[i].id,
  80317. id2 = p2[i].id;
  80318. var key = id1 < id2 ? id1+","+id2 : id2+","+id1;
  80319. t[key] = i;
  80320. t.keys.push(key);
  80321. }
  80322. for(var i=0; i!==t.keys.length; i++){
  80323. var key = t.keys.pop(),
  80324. pairIndex = t[key];
  80325. pairs1.push(p1[pairIndex]);
  80326. pairs2.push(p2[pairIndex]);
  80327. delete t[key];
  80328. }
  80329. };
  80330. /**
  80331. * To be implemented by subcasses
  80332. * @method setWorld
  80333. * @param {World} world
  80334. */
  80335. Broadphase.prototype.setWorld = function(world){
  80336. };
  80337. /**
  80338. * Check if the bounding spheres of two bodies overlap.
  80339. * @method boundingSphereCheck
  80340. * @param {Body} bodyA
  80341. * @param {Body} bodyB
  80342. * @return {boolean}
  80343. */
  80344. var bsc_dist = new Vec3();
  80345. Broadphase.boundingSphereCheck = function(bodyA,bodyB){
  80346. var dist = bsc_dist;
  80347. bodyA.position.vsub(bodyB.position,dist);
  80348. return Math.pow(bodyA.shape.boundingSphereRadius + bodyB.shape.boundingSphereRadius,2) > dist.norm2();
  80349. };
  80350. /**
  80351. * Returns all the bodies within the AABB.
  80352. * @method aabbQuery
  80353. * @param {World} world
  80354. * @param {AABB} aabb
  80355. * @param {array} result An array to store resulting bodies in.
  80356. * @return {array}
  80357. */
  80358. Broadphase.prototype.aabbQuery = function(world, aabb, result){
  80359. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  80360. return [];
  80361. };
  80362. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Plane":42,"../shapes/Shape":43}],6:[function(_dereq_,module,exports){
  80363. module.exports = GridBroadphase;
  80364. var Broadphase = _dereq_('./Broadphase');
  80365. var Vec3 = _dereq_('../math/Vec3');
  80366. var Shape = _dereq_('../shapes/Shape');
  80367. /**
  80368. * Axis aligned uniform grid broadphase.
  80369. * @class GridBroadphase
  80370. * @constructor
  80371. * @extends Broadphase
  80372. * @todo Needs support for more than just planes and spheres.
  80373. * @param {Vec3} aabbMin
  80374. * @param {Vec3} aabbMax
  80375. * @param {Number} nx Number of boxes along x
  80376. * @param {Number} ny Number of boxes along y
  80377. * @param {Number} nz Number of boxes along z
  80378. */
  80379. function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){
  80380. Broadphase.apply(this);
  80381. this.nx = nx || 10;
  80382. this.ny = ny || 10;
  80383. this.nz = nz || 10;
  80384. this.aabbMin = aabbMin || new Vec3(100,100,100);
  80385. this.aabbMax = aabbMax || new Vec3(-100,-100,-100);
  80386. var nbins = this.nx * this.ny * this.nz;
  80387. if (nbins <= 0) {
  80388. throw "GridBroadphase: Each dimension's n must be >0";
  80389. }
  80390. this.bins = [];
  80391. this.binLengths = []; //Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  80392. this.bins.length = nbins;
  80393. this.binLengths.length = nbins;
  80394. for (var i=0;i<nbins;i++) {
  80395. this.bins[i]=[];
  80396. this.binLengths[i]=0;
  80397. }
  80398. }
  80399. GridBroadphase.prototype = new Broadphase();
  80400. GridBroadphase.prototype.constructor = GridBroadphase;
  80401. /**
  80402. * Get all the collision pairs in the physics world
  80403. * @method collisionPairs
  80404. * @param {World} world
  80405. * @param {Array} pairs1
  80406. * @param {Array} pairs2
  80407. */
  80408. var GridBroadphase_collisionPairs_d = new Vec3();
  80409. var GridBroadphase_collisionPairs_binPos = new Vec3();
  80410. GridBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  80411. var N = world.numObjects(),
  80412. bodies = world.bodies;
  80413. var max = this.aabbMax,
  80414. min = this.aabbMin,
  80415. nx = this.nx,
  80416. ny = this.ny,
  80417. nz = this.nz;
  80418. var xstep = ny*nz;
  80419. var ystep = nz;
  80420. var zstep = 1;
  80421. var xmax = max.x,
  80422. ymax = max.y,
  80423. zmax = max.z,
  80424. xmin = min.x,
  80425. ymin = min.y,
  80426. zmin = min.z;
  80427. var xmult = nx / (xmax-xmin),
  80428. ymult = ny / (ymax-ymin),
  80429. zmult = nz / (zmax-zmin);
  80430. var binsizeX = (xmax - xmin) / nx,
  80431. binsizeY = (ymax - ymin) / ny,
  80432. binsizeZ = (zmax - zmin) / nz;
  80433. var binRadius = Math.sqrt(binsizeX*binsizeX + binsizeY*binsizeY + binsizeZ*binsizeZ) * 0.5;
  80434. var types = Shape.types;
  80435. var SPHERE = types.SPHERE,
  80436. PLANE = types.PLANE,
  80437. BOX = types.BOX,
  80438. COMPOUND = types.COMPOUND,
  80439. CONVEXPOLYHEDRON = types.CONVEXPOLYHEDRON;
  80440. var bins=this.bins,
  80441. binLengths=this.binLengths,
  80442. Nbins=this.bins.length;
  80443. // Reset bins
  80444. for(var i=0; i!==Nbins; i++){
  80445. binLengths[i] = 0;
  80446. }
  80447. var ceil = Math.ceil;
  80448. var min = Math.min;
  80449. var max = Math.max;
  80450. function addBoxToBins(x0,y0,z0,x1,y1,z1,bi) {
  80451. var xoff0 = ((x0 - xmin) * xmult)|0,
  80452. yoff0 = ((y0 - ymin) * ymult)|0,
  80453. zoff0 = ((z0 - zmin) * zmult)|0,
  80454. xoff1 = ceil((x1 - xmin) * xmult),
  80455. yoff1 = ceil((y1 - ymin) * ymult),
  80456. zoff1 = ceil((z1 - zmin) * zmult);
  80457. if (xoff0 < 0) { xoff0 = 0; } else if (xoff0 >= nx) { xoff0 = nx - 1; }
  80458. if (yoff0 < 0) { yoff0 = 0; } else if (yoff0 >= ny) { yoff0 = ny - 1; }
  80459. if (zoff0 < 0) { zoff0 = 0; } else if (zoff0 >= nz) { zoff0 = nz - 1; }
  80460. if (xoff1 < 0) { xoff1 = 0; } else if (xoff1 >= nx) { xoff1 = nx - 1; }
  80461. if (yoff1 < 0) { yoff1 = 0; } else if (yoff1 >= ny) { yoff1 = ny - 1; }
  80462. if (zoff1 < 0) { zoff1 = 0; } else if (zoff1 >= nz) { zoff1 = nz - 1; }
  80463. xoff0 *= xstep;
  80464. yoff0 *= ystep;
  80465. zoff0 *= zstep;
  80466. xoff1 *= xstep;
  80467. yoff1 *= ystep;
  80468. zoff1 *= zstep;
  80469. for (var xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  80470. for (var yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  80471. for (var zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  80472. var idx = xoff+yoff+zoff;
  80473. bins[idx][binLengths[idx]++] = bi;
  80474. }
  80475. }
  80476. }
  80477. }
  80478. // Put all bodies into the bins
  80479. for(var i=0; i!==N; i++){
  80480. var bi = bodies[i];
  80481. var si = bi.shape;
  80482. switch(si.type){
  80483. case SPHERE:
  80484. // Put in bin
  80485. // check if overlap with other bins
  80486. var x = bi.position.x,
  80487. y = bi.position.y,
  80488. z = bi.position.z;
  80489. var r = si.radius;
  80490. addBoxToBins(x-r, y-r, z-r, x+r, y+r, z+r, bi);
  80491. break;
  80492. case PLANE:
  80493. if(si.worldNormalNeedsUpdate){
  80494. si.computeWorldNormal(bi.quaternion);
  80495. }
  80496. var planeNormal = si.worldNormal;
  80497. //Relative position from origin of plane object to the first bin
  80498. //Incremented as we iterate through the bins
  80499. var xreset = xmin + binsizeX*0.5 - bi.position.x,
  80500. yreset = ymin + binsizeY*0.5 - bi.position.y,
  80501. zreset = zmin + binsizeZ*0.5 - bi.position.z;
  80502. var d = GridBroadphase_collisionPairs_d;
  80503. d.set(xreset, yreset, zreset);
  80504. for (var xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  80505. for (var yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  80506. for (var zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  80507. if (d.dot(planeNormal) < binRadius) {
  80508. var idx = xoff + yoff + zoff;
  80509. bins[idx][binLengths[idx]++] = bi;
  80510. }
  80511. }
  80512. }
  80513. }
  80514. break;
  80515. default:
  80516. if (bi.aabbNeedsUpdate) {
  80517. bi.computeAABB();
  80518. }
  80519. addBoxToBins(
  80520. bi.aabb.lowerBound.x,
  80521. bi.aabb.lowerBound.y,
  80522. bi.aabb.lowerBound.z,
  80523. bi.aabb.upperBound.x,
  80524. bi.aabb.upperBound.y,
  80525. bi.aabb.upperBound.z,
  80526. bi);
  80527. break;
  80528. }
  80529. }
  80530. // Check each bin
  80531. for(var i=0; i!==Nbins; i++){
  80532. var binLength = binLengths[i];
  80533. //Skip bins with no potential collisions
  80534. if (binLength > 1) {
  80535. var bin = bins[i];
  80536. // Do N^2 broadphase inside
  80537. for(var xi=0; xi!==binLength; xi++){
  80538. var bi = bin[xi];
  80539. for(var yi=0; yi!==xi; yi++){
  80540. var bj = bin[yi];
  80541. if(this.needBroadphaseCollision(bi,bj)){
  80542. this.intersectionTest(bi,bj,pairs1,pairs2);
  80543. }
  80544. }
  80545. }
  80546. }
  80547. }
  80548. // for (var zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  80549. // console.log("layer "+zi);
  80550. // for (var yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  80551. // var row = '';
  80552. // for (var xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  80553. // var idx = xoff + yoff + zoff;
  80554. // row += ' ' + binLengths[idx];
  80555. // }
  80556. // console.log(row);
  80557. // }
  80558. // }
  80559. this.makePairsUnique(pairs1,pairs2);
  80560. };
  80561. },{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(_dereq_,module,exports){
  80562. module.exports = NaiveBroadphase;
  80563. var Broadphase = _dereq_('./Broadphase');
  80564. var AABB = _dereq_('./AABB');
  80565. /**
  80566. * Naive broadphase implementation, used in lack of better ones.
  80567. * @class NaiveBroadphase
  80568. * @constructor
  80569. * @description The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 (which is bad)
  80570. * @extends Broadphase
  80571. */
  80572. function NaiveBroadphase(){
  80573. Broadphase.apply(this);
  80574. }
  80575. NaiveBroadphase.prototype = new Broadphase();
  80576. NaiveBroadphase.prototype.constructor = NaiveBroadphase;
  80577. /**
  80578. * Get all the collision pairs in the physics world
  80579. * @method collisionPairs
  80580. * @param {World} world
  80581. * @param {Array} pairs1
  80582. * @param {Array} pairs2
  80583. */
  80584. NaiveBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  80585. var bodies = world.bodies,
  80586. n = bodies.length,
  80587. i,j,bi,bj;
  80588. // Naive N^2 ftw!
  80589. for(i=0; i!==n; i++){
  80590. for(j=0; j!==i; j++){
  80591. bi = bodies[i];
  80592. bj = bodies[j];
  80593. if(!this.needBroadphaseCollision(bi,bj)){
  80594. continue;
  80595. }
  80596. this.intersectionTest(bi,bj,pairs1,pairs2);
  80597. }
  80598. }
  80599. };
  80600. var tmpAABB = new AABB();
  80601. /**
  80602. * Returns all the bodies within an AABB.
  80603. * @method aabbQuery
  80604. * @param {World} world
  80605. * @param {AABB} aabb
  80606. * @param {array} result An array to store resulting bodies in.
  80607. * @return {array}
  80608. */
  80609. NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
  80610. result = result || [];
  80611. for(var i = 0; i < world.bodies.length; i++){
  80612. var b = world.bodies[i];
  80613. if(b.aabbNeedsUpdate){
  80614. b.computeAABB();
  80615. }
  80616. // Ugly hack until Body gets aabb
  80617. if(b.aabb.overlaps(aabb)){
  80618. result.push(b);
  80619. }
  80620. }
  80621. return result;
  80622. };
  80623. },{"./AABB":3,"./Broadphase":5}],8:[function(_dereq_,module,exports){
  80624. module.exports = ObjectCollisionMatrix;
  80625. /**
  80626. * Records what objects are colliding with each other
  80627. * @class ObjectCollisionMatrix
  80628. * @constructor
  80629. */
  80630. function ObjectCollisionMatrix() {
  80631. /**
  80632. * The matrix storage
  80633. * @property matrix
  80634. * @type {Object}
  80635. */
  80636. this.matrix = {};
  80637. }
  80638. /**
  80639. * @method get
  80640. * @param {Number} i
  80641. * @param {Number} j
  80642. * @return {Number}
  80643. */
  80644. ObjectCollisionMatrix.prototype.get = function(i, j) {
  80645. i = i.id;
  80646. j = j.id;
  80647. if (j > i) {
  80648. var temp = j;
  80649. j = i;
  80650. i = temp;
  80651. }
  80652. return i+'-'+j in this.matrix;
  80653. };
  80654. /**
  80655. * @method set
  80656. * @param {Number} i
  80657. * @param {Number} j
  80658. * @param {Number} value
  80659. */
  80660. ObjectCollisionMatrix.prototype.set = function(i, j, value) {
  80661. i = i.id;
  80662. j = j.id;
  80663. if (j > i) {
  80664. var temp = j;
  80665. j = i;
  80666. i = temp;
  80667. }
  80668. if (value) {
  80669. this.matrix[i+'-'+j] = true;
  80670. }
  80671. else {
  80672. delete this.matrix[i+'-'+j];
  80673. }
  80674. };
  80675. /**
  80676. * Empty the matrix
  80677. * @method reset
  80678. */
  80679. ObjectCollisionMatrix.prototype.reset = function() {
  80680. this.matrix = {};
  80681. };
  80682. /**
  80683. * Set max number of objects
  80684. * @method setNumObjects
  80685. * @param {Number} n
  80686. */
  80687. ObjectCollisionMatrix.prototype.setNumObjects = function(n) {
  80688. };
  80689. },{}],9:[function(_dereq_,module,exports){
  80690. module.exports = Ray;
  80691. var Vec3 = _dereq_('../math/Vec3');
  80692. var Quaternion = _dereq_('../math/Quaternion');
  80693. var Transform = _dereq_('../math/Transform');
  80694. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  80695. var Box = _dereq_('../shapes/Box');
  80696. var RaycastResult = _dereq_('../collision/RaycastResult');
  80697. var Shape = _dereq_('../shapes/Shape');
  80698. var AABB = _dereq_('../collision/AABB');
  80699. /**
  80700. * A line in 3D space that intersects bodies and return points.
  80701. * @class Ray
  80702. * @constructor
  80703. * @param {Vec3} from
  80704. * @param {Vec3} to
  80705. */
  80706. function Ray(from, to){
  80707. /**
  80708. * @property {Vec3} from
  80709. */
  80710. this.from = from ? from.clone() : new Vec3();
  80711. /**
  80712. * @property {Vec3} to
  80713. */
  80714. this.to = to ? to.clone() : new Vec3();
  80715. /**
  80716. * @private
  80717. * @property {Vec3} _direction
  80718. */
  80719. this._direction = new Vec3();
  80720. /**
  80721. * The precision of the ray. Used when checking parallelity etc.
  80722. * @property {Number} precision
  80723. */
  80724. this.precision = 0.0001;
  80725. /**
  80726. * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
  80727. * @property {Boolean} checkCollisionResponse
  80728. */
  80729. this.checkCollisionResponse = true;
  80730. /**
  80731. * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
  80732. * @property {Boolean} skipBackfaces
  80733. */
  80734. this.skipBackfaces = false;
  80735. /**
  80736. * @property {number} collisionFilterMask
  80737. * @default -1
  80738. */
  80739. this.collisionFilterMask = -1;
  80740. /**
  80741. * @property {number} collisionFilterGroup
  80742. * @default -1
  80743. */
  80744. this.collisionFilterGroup = -1;
  80745. /**
  80746. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  80747. * @property {number} mode
  80748. */
  80749. this.mode = Ray.ANY;
  80750. /**
  80751. * Current result object.
  80752. * @property {RaycastResult} result
  80753. */
  80754. this.result = new RaycastResult();
  80755. /**
  80756. * Will be set to true during intersectWorld() if the ray hit anything.
  80757. * @property {Boolean} hasHit
  80758. */
  80759. this.hasHit = false;
  80760. /**
  80761. * Current, user-provided result callback. Will be used if mode is Ray.ALL.
  80762. * @property {Function} callback
  80763. */
  80764. this.callback = function(result){};
  80765. }
  80766. Ray.prototype.constructor = Ray;
  80767. Ray.CLOSEST = 1;
  80768. Ray.ANY = 2;
  80769. Ray.ALL = 4;
  80770. var tmpAABB = new AABB();
  80771. var tmpArray = [];
  80772. /**
  80773. * Do itersection against all bodies in the given World.
  80774. * @method intersectWorld
  80775. * @param {World} world
  80776. * @param {object} options
  80777. * @return {Boolean} True if the ray hit anything, otherwise false.
  80778. */
  80779. Ray.prototype.intersectWorld = function (world, options) {
  80780. this.mode = options.mode || Ray.ANY;
  80781. this.result = options.result || new RaycastResult();
  80782. this.skipBackfaces = !!options.skipBackfaces;
  80783. this.collisionFilterMask = typeof(options.collisionFilterMask) !== 'undefined' ? options.collisionFilterMask : -1;
  80784. this.collisionFilterGroup = typeof(options.collisionFilterGroup) !== 'undefined' ? options.collisionFilterGroup : -1;
  80785. if(options.from){
  80786. this.from.copy(options.from);
  80787. }
  80788. if(options.to){
  80789. this.to.copy(options.to);
  80790. }
  80791. this.callback = options.callback || function(){};
  80792. this.hasHit = false;
  80793. this.result.reset();
  80794. this._updateDirection();
  80795. this.getAABB(tmpAABB);
  80796. tmpArray.length = 0;
  80797. world.broadphase.aabbQuery(world, tmpAABB, tmpArray);
  80798. this.intersectBodies(tmpArray);
  80799. return this.hasHit;
  80800. };
  80801. var v1 = new Vec3(),
  80802. v2 = new Vec3();
  80803. /*
  80804. * As per "Barycentric Technique" as named here http://www.blackpawn.com/texts/pointinpoly/default.html But without the division
  80805. */
  80806. Ray.pointInTriangle = pointInTriangle;
  80807. function pointInTriangle(p, a, b, c) {
  80808. c.vsub(a,v0);
  80809. b.vsub(a,v1);
  80810. p.vsub(a,v2);
  80811. var dot00 = v0.dot( v0 );
  80812. var dot01 = v0.dot( v1 );
  80813. var dot02 = v0.dot( v2 );
  80814. var dot11 = v1.dot( v1 );
  80815. var dot12 = v1.dot( v2 );
  80816. var u,v;
  80817. return ( (u = dot11 * dot02 - dot01 * dot12) >= 0 ) &&
  80818. ( (v = dot00 * dot12 - dot01 * dot02) >= 0 ) &&
  80819. ( u + v < ( dot00 * dot11 - dot01 * dot01 ) );
  80820. }
  80821. /**
  80822. * Shoot a ray at a body, get back information about the hit.
  80823. * @method intersectBody
  80824. * @private
  80825. * @param {Body} body
  80826. * @param {RaycastResult} [result] Deprecated - set the result property of the Ray instead.
  80827. */
  80828. var intersectBody_xi = new Vec3();
  80829. var intersectBody_qi = new Quaternion();
  80830. Ray.prototype.intersectBody = function (body, result) {
  80831. if(result){
  80832. this.result = result;
  80833. this._updateDirection();
  80834. }
  80835. var checkCollisionResponse = this.checkCollisionResponse;
  80836. if(checkCollisionResponse && !body.collisionResponse){
  80837. return;
  80838. }
  80839. if((this.collisionFilterGroup & body.collisionFilterMask)===0 || (body.collisionFilterGroup & this.collisionFilterMask)===0){
  80840. return;
  80841. }
  80842. var xi = intersectBody_xi;
  80843. var qi = intersectBody_qi;
  80844. for (var i = 0, N = body.shapes.length; i < N; i++) {
  80845. var shape = body.shapes[i];
  80846. if(checkCollisionResponse && !shape.collisionResponse){
  80847. continue; // Skip
  80848. }
  80849. body.quaternion.mult(body.shapeOrientations[i], qi);
  80850. body.quaternion.vmult(body.shapeOffsets[i], xi);
  80851. xi.vadd(body.position, xi);
  80852. this.intersectShape(
  80853. shape,
  80854. qi,
  80855. xi,
  80856. body
  80857. );
  80858. if(this.result._shouldStop){
  80859. break;
  80860. }
  80861. }
  80862. };
  80863. /**
  80864. * @method intersectBodies
  80865. * @param {Array} bodies An array of Body objects.
  80866. * @param {RaycastResult} [result] Deprecated
  80867. */
  80868. Ray.prototype.intersectBodies = function (bodies, result) {
  80869. if(result){
  80870. this.result = result;
  80871. this._updateDirection();
  80872. }
  80873. for ( var i = 0, l = bodies.length; !this.result._shouldStop && i < l; i ++ ) {
  80874. this.intersectBody(bodies[i]);
  80875. }
  80876. };
  80877. /**
  80878. * Updates the _direction vector.
  80879. * @private
  80880. * @method _updateDirection
  80881. */
  80882. Ray.prototype._updateDirection = function(){
  80883. this.to.vsub(this.from, this._direction);
  80884. this._direction.normalize();
  80885. };
  80886. /**
  80887. * @method intersectShape
  80888. * @private
  80889. * @param {Shape} shape
  80890. * @param {Quaternion} quat
  80891. * @param {Vec3} position
  80892. * @param {Body} body
  80893. */
  80894. Ray.prototype.intersectShape = function(shape, quat, position, body){
  80895. var from = this.from;
  80896. // Checking boundingSphere
  80897. var distance = distanceFromIntersection(from, this._direction, position);
  80898. if ( distance > shape.boundingSphereRadius ) {
  80899. return;
  80900. }
  80901. var intersectMethod = this[shape.type];
  80902. if(intersectMethod){
  80903. intersectMethod.call(this, shape, quat, position, body);
  80904. }
  80905. };
  80906. var vector = new Vec3();
  80907. var normal = new Vec3();
  80908. var intersectPoint = new Vec3();
  80909. var a = new Vec3();
  80910. var b = new Vec3();
  80911. var c = new Vec3();
  80912. var d = new Vec3();
  80913. var tmpRaycastResult = new RaycastResult();
  80914. /**
  80915. * @method intersectBox
  80916. * @private
  80917. * @param {Shape} shape
  80918. * @param {Quaternion} quat
  80919. * @param {Vec3} position
  80920. * @param {Body} body
  80921. */
  80922. Ray.prototype.intersectBox = function(shape, quat, position, body){
  80923. return this.intersectConvex(shape.convexPolyhedronRepresentation, quat, position, body);
  80924. };
  80925. Ray.prototype[Shape.types.BOX] = Ray.prototype.intersectBox;
  80926. /**
  80927. * @method intersectPlane
  80928. * @private
  80929. * @param {Shape} shape
  80930. * @param {Quaternion} quat
  80931. * @param {Vec3} position
  80932. * @param {Body} body
  80933. */
  80934. Ray.prototype.intersectPlane = function(shape, quat, position, body){
  80935. var from = this.from;
  80936. var to = this.to;
  80937. var direction = this._direction;
  80938. // Get plane normal
  80939. var worldNormal = new Vec3(0, 0, 1);
  80940. quat.vmult(worldNormal, worldNormal);
  80941. var len = new Vec3();
  80942. from.vsub(position, len);
  80943. var planeToFrom = len.dot(worldNormal);
  80944. to.vsub(position, len);
  80945. var planeToTo = len.dot(worldNormal);
  80946. if(planeToFrom * planeToTo > 0){
  80947. // "from" and "to" are on the same side of the plane... bail out
  80948. return;
  80949. }
  80950. if(from.distanceTo(to) < planeToFrom){
  80951. return;
  80952. }
  80953. var n_dot_dir = worldNormal.dot(direction);
  80954. if (Math.abs(n_dot_dir) < this.precision) {
  80955. // No intersection
  80956. return;
  80957. }
  80958. var planePointToFrom = new Vec3();
  80959. var dir_scaled_with_t = new Vec3();
  80960. var hitPointWorld = new Vec3();
  80961. from.vsub(position, planePointToFrom);
  80962. var t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  80963. direction.scale(t, dir_scaled_with_t);
  80964. from.vadd(dir_scaled_with_t, hitPointWorld);
  80965. this.reportIntersection(worldNormal, hitPointWorld, shape, body, -1);
  80966. };
  80967. Ray.prototype[Shape.types.PLANE] = Ray.prototype.intersectPlane;
  80968. /**
  80969. * Get the world AABB of the ray.
  80970. * @method getAABB
  80971. * @param {AABB} aabb
  80972. */
  80973. Ray.prototype.getAABB = function(result){
  80974. var to = this.to;
  80975. var from = this.from;
  80976. result.lowerBound.x = Math.min(to.x, from.x);
  80977. result.lowerBound.y = Math.min(to.y, from.y);
  80978. result.lowerBound.z = Math.min(to.z, from.z);
  80979. result.upperBound.x = Math.max(to.x, from.x);
  80980. result.upperBound.y = Math.max(to.y, from.y);
  80981. result.upperBound.z = Math.max(to.z, from.z);
  80982. };
  80983. var intersectConvexOptions = {
  80984. faceList: [0]
  80985. };
  80986. /**
  80987. * @method intersectHeightfield
  80988. * @private
  80989. * @param {Shape} shape
  80990. * @param {Quaternion} quat
  80991. * @param {Vec3} position
  80992. * @param {Body} body
  80993. */
  80994. Ray.prototype.intersectHeightfield = function(shape, quat, position, body){
  80995. var data = shape.data,
  80996. w = shape.elementSize,
  80997. worldPillarOffset = new Vec3();
  80998. // Convert the ray to local heightfield coordinates
  80999. var localRay = new Ray(this.from, this.to);
  81000. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  81001. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  81002. // Get the index of the data points to test against
  81003. var index = [];
  81004. var iMinX = null;
  81005. var iMinY = null;
  81006. var iMaxX = null;
  81007. var iMaxY = null;
  81008. var inside = shape.getIndexOfPosition(localRay.from.x, localRay.from.y, index, false);
  81009. if(inside){
  81010. iMinX = index[0];
  81011. iMinY = index[1];
  81012. iMaxX = index[0];
  81013. iMaxY = index[1];
  81014. }
  81015. inside = shape.getIndexOfPosition(localRay.to.x, localRay.to.y, index, false);
  81016. if(inside){
  81017. if (iMinX === null || index[0] < iMinX) { iMinX = index[0]; }
  81018. if (iMaxX === null || index[0] > iMaxX) { iMaxX = index[0]; }
  81019. if (iMinY === null || index[1] < iMinY) { iMinY = index[1]; }
  81020. if (iMaxY === null || index[1] > iMaxY) { iMaxY = index[1]; }
  81021. }
  81022. if(iMinX === null){
  81023. return;
  81024. }
  81025. var minMax = [];
  81026. shape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  81027. var min = minMax[0];
  81028. var max = minMax[1];
  81029. // // Bail out if the ray can't touch the bounding box
  81030. // // TODO
  81031. // var aabb = new AABB();
  81032. // this.getAABB(aabb);
  81033. // if(aabb.intersects()){
  81034. // return;
  81035. // }
  81036. for(var i = iMinX; i <= iMaxX; i++){
  81037. for(var j = iMinY; j <= iMaxY; j++){
  81038. if(this.result._shouldStop){
  81039. return;
  81040. }
  81041. // Lower triangle
  81042. shape.getConvexTrianglePillar(i, j, false);
  81043. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  81044. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  81045. if(this.result._shouldStop){
  81046. return;
  81047. }
  81048. // Upper triangle
  81049. shape.getConvexTrianglePillar(i, j, true);
  81050. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  81051. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  81052. }
  81053. }
  81054. };
  81055. Ray.prototype[Shape.types.HEIGHTFIELD] = Ray.prototype.intersectHeightfield;
  81056. var Ray_intersectSphere_intersectionPoint = new Vec3();
  81057. var Ray_intersectSphere_normal = new Vec3();
  81058. /**
  81059. * @method intersectSphere
  81060. * @private
  81061. * @param {Shape} shape
  81062. * @param {Quaternion} quat
  81063. * @param {Vec3} position
  81064. * @param {Body} body
  81065. */
  81066. Ray.prototype.intersectSphere = function(shape, quat, position, body){
  81067. var from = this.from,
  81068. to = this.to,
  81069. r = shape.radius;
  81070. var a = Math.pow(to.x - from.x, 2) + Math.pow(to.y - from.y, 2) + Math.pow(to.z - from.z, 2);
  81071. 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));
  81072. 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);
  81073. var delta = Math.pow(b, 2) - 4 * a * c;
  81074. var intersectionPoint = Ray_intersectSphere_intersectionPoint;
  81075. var normal = Ray_intersectSphere_normal;
  81076. if(delta < 0){
  81077. // No intersection
  81078. return;
  81079. } else if(delta === 0){
  81080. // single intersection point
  81081. from.lerp(to, delta, intersectionPoint);
  81082. intersectionPoint.vsub(position, normal);
  81083. normal.normalize();
  81084. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  81085. } else {
  81086. var d1 = (- b - Math.sqrt(delta)) / (2 * a);
  81087. var d2 = (- b + Math.sqrt(delta)) / (2 * a);
  81088. if(d1 >= 0 && d1 <= 1){
  81089. from.lerp(to, d1, intersectionPoint);
  81090. intersectionPoint.vsub(position, normal);
  81091. normal.normalize();
  81092. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  81093. }
  81094. if(this.result._shouldStop){
  81095. return;
  81096. }
  81097. if(d2 >= 0 && d2 <= 1){
  81098. from.lerp(to, d2, intersectionPoint);
  81099. intersectionPoint.vsub(position, normal);
  81100. normal.normalize();
  81101. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  81102. }
  81103. }
  81104. };
  81105. Ray.prototype[Shape.types.SPHERE] = Ray.prototype.intersectSphere;
  81106. var intersectConvex_normal = new Vec3();
  81107. var intersectConvex_minDistNormal = new Vec3();
  81108. var intersectConvex_minDistIntersect = new Vec3();
  81109. var intersectConvex_vector = new Vec3();
  81110. /**
  81111. * @method intersectConvex
  81112. * @private
  81113. * @param {Shape} shape
  81114. * @param {Quaternion} quat
  81115. * @param {Vec3} position
  81116. * @param {Body} body
  81117. * @param {object} [options]
  81118. * @param {array} [options.faceList]
  81119. */
  81120. Ray.prototype.intersectConvex = function intersectConvex(
  81121. shape,
  81122. quat,
  81123. position,
  81124. body,
  81125. options
  81126. ){
  81127. var minDistNormal = intersectConvex_minDistNormal;
  81128. var normal = intersectConvex_normal;
  81129. var vector = intersectConvex_vector;
  81130. var minDistIntersect = intersectConvex_minDistIntersect;
  81131. var faceList = (options && options.faceList) || null;
  81132. // Checking faces
  81133. var faces = shape.faces,
  81134. vertices = shape.vertices,
  81135. normals = shape.faceNormals;
  81136. var direction = this._direction;
  81137. var from = this.from;
  81138. var to = this.to;
  81139. var fromToDistance = from.distanceTo(to);
  81140. var minDist = -1;
  81141. var Nfaces = faceList ? faceList.length : faces.length;
  81142. var result = this.result;
  81143. for (var j = 0; !result._shouldStop && j < Nfaces; j++) {
  81144. var fi = faceList ? faceList[j] : j;
  81145. var face = faces[fi];
  81146. var faceNormal = normals[fi];
  81147. var q = quat;
  81148. var x = position;
  81149. // determine if ray intersects the plane of the face
  81150. // note: this works regardless of the direction of the face normal
  81151. // Get plane point in world coordinates...
  81152. vector.copy(vertices[face[0]]);
  81153. q.vmult(vector,vector);
  81154. vector.vadd(x,vector);
  81155. // ...but make it relative to the ray from. We'll fix this later.
  81156. vector.vsub(from,vector);
  81157. // Get plane normal
  81158. q.vmult(faceNormal,normal);
  81159. // If this dot product is negative, we have something interesting
  81160. var dot = direction.dot(normal);
  81161. // Bail out if ray and plane are parallel
  81162. if ( Math.abs( dot ) < this.precision ){
  81163. continue;
  81164. }
  81165. // calc distance to plane
  81166. var scalar = normal.dot(vector) / dot;
  81167. // if negative distance, then plane is behind ray
  81168. if (scalar < 0){
  81169. continue;
  81170. }
  81171. // if (dot < 0) {
  81172. // Intersection point is from + direction * scalar
  81173. direction.mult(scalar,intersectPoint);
  81174. intersectPoint.vadd(from,intersectPoint);
  81175. // a is the point we compare points b and c with.
  81176. a.copy(vertices[face[0]]);
  81177. q.vmult(a,a);
  81178. x.vadd(a,a);
  81179. for(var i = 1; !result._shouldStop && i < face.length - 1; i++){
  81180. // Transform 3 vertices to world coords
  81181. b.copy(vertices[face[i]]);
  81182. c.copy(vertices[face[i+1]]);
  81183. q.vmult(b,b);
  81184. q.vmult(c,c);
  81185. x.vadd(b,b);
  81186. x.vadd(c,c);
  81187. var distance = intersectPoint.distanceTo(from);
  81188. if(!(pointInTriangle(intersectPoint, a, b, c) || pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance){
  81189. continue;
  81190. }
  81191. this.reportIntersection(normal, intersectPoint, shape, body, fi);
  81192. }
  81193. // }
  81194. }
  81195. };
  81196. Ray.prototype[Shape.types.CONVEXPOLYHEDRON] = Ray.prototype.intersectConvex;
  81197. var intersectTrimesh_normal = new Vec3();
  81198. var intersectTrimesh_localDirection = new Vec3();
  81199. var intersectTrimesh_localFrom = new Vec3();
  81200. var intersectTrimesh_localTo = new Vec3();
  81201. var intersectTrimesh_worldNormal = new Vec3();
  81202. var intersectTrimesh_worldIntersectPoint = new Vec3();
  81203. var intersectTrimesh_localAABB = new AABB();
  81204. var intersectTrimesh_triangles = [];
  81205. var intersectTrimesh_treeTransform = new Transform();
  81206. /**
  81207. * @method intersectTrimesh
  81208. * @private
  81209. * @param {Shape} shape
  81210. * @param {Quaternion} quat
  81211. * @param {Vec3} position
  81212. * @param {Body} body
  81213. * @param {object} [options]
  81214. * @todo Optimize by transforming the world to local space first.
  81215. * @todo Use Octree lookup
  81216. */
  81217. Ray.prototype.intersectTrimesh = function intersectTrimesh(
  81218. mesh,
  81219. quat,
  81220. position,
  81221. body,
  81222. options
  81223. ){
  81224. var normal = intersectTrimesh_normal;
  81225. var triangles = intersectTrimesh_triangles;
  81226. var treeTransform = intersectTrimesh_treeTransform;
  81227. var minDistNormal = intersectConvex_minDistNormal;
  81228. var vector = intersectConvex_vector;
  81229. var minDistIntersect = intersectConvex_minDistIntersect;
  81230. var localAABB = intersectTrimesh_localAABB;
  81231. var localDirection = intersectTrimesh_localDirection;
  81232. var localFrom = intersectTrimesh_localFrom;
  81233. var localTo = intersectTrimesh_localTo;
  81234. var worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  81235. var worldNormal = intersectTrimesh_worldNormal;
  81236. var faceList = (options && options.faceList) || null;
  81237. // Checking faces
  81238. var indices = mesh.indices,
  81239. vertices = mesh.vertices,
  81240. normals = mesh.faceNormals;
  81241. var from = this.from;
  81242. var to = this.to;
  81243. var direction = this._direction;
  81244. var minDist = -1;
  81245. treeTransform.position.copy(position);
  81246. treeTransform.quaternion.copy(quat);
  81247. // Transform ray to local space!
  81248. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  81249. //body.vectorToLocalFrame(direction, localDirection);
  81250. Transform.pointToLocalFrame(position, quat, from, localFrom);
  81251. //body.pointToLocalFrame(from, localFrom);
  81252. Transform.pointToLocalFrame(position, quat, to, localTo);
  81253. //body.pointToLocalFrame(to, localTo);
  81254. var fromToDistanceSquared = localFrom.distanceSquared(localTo);
  81255. mesh.tree.rayQuery(this, treeTransform, triangles);
  81256. for (var i = 0, N = triangles.length; !this.result._shouldStop && i !== N; i++) {
  81257. var trianglesIndex = triangles[i];
  81258. mesh.getNormal(trianglesIndex, normal);
  81259. // determine if ray intersects the plane of the face
  81260. // note: this works regardless of the direction of the face normal
  81261. // Get plane point in world coordinates...
  81262. mesh.getVertex(indices[trianglesIndex * 3], a);
  81263. // ...but make it relative to the ray from. We'll fix this later.
  81264. a.vsub(localFrom,vector);
  81265. // Get plane normal
  81266. // quat.vmult(normal, normal);
  81267. // If this dot product is negative, we have something interesting
  81268. var dot = localDirection.dot(normal);
  81269. // Bail out if ray and plane are parallel
  81270. // if (Math.abs( dot ) < this.precision){
  81271. // continue;
  81272. // }
  81273. // calc distance to plane
  81274. var scalar = normal.dot(vector) / dot;
  81275. // if negative distance, then plane is behind ray
  81276. if (scalar < 0){
  81277. continue;
  81278. }
  81279. // Intersection point is from + direction * scalar
  81280. localDirection.scale(scalar,intersectPoint);
  81281. intersectPoint.vadd(localFrom,intersectPoint);
  81282. // Get triangle vertices
  81283. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  81284. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  81285. var squaredDistance = intersectPoint.distanceSquared(localFrom);
  81286. if(!(pointInTriangle(intersectPoint, b, a, c) || pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared){
  81287. continue;
  81288. }
  81289. // transform intersectpoint and normal to world
  81290. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  81291. //body.vectorToWorldFrame(normal, worldNormal);
  81292. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  81293. //body.pointToWorldFrame(intersectPoint, worldIntersectPoint);
  81294. this.reportIntersection(worldNormal, worldIntersectPoint, mesh, body, trianglesIndex);
  81295. }
  81296. triangles.length = 0;
  81297. };
  81298. Ray.prototype[Shape.types.TRIMESH] = Ray.prototype.intersectTrimesh;
  81299. /**
  81300. * @method reportIntersection
  81301. * @private
  81302. * @param {Vec3} normal
  81303. * @param {Vec3} hitPointWorld
  81304. * @param {Shape} shape
  81305. * @param {Body} body
  81306. * @return {boolean} True if the intersections should continue
  81307. */
  81308. Ray.prototype.reportIntersection = function(normal, hitPointWorld, shape, body, hitFaceIndex){
  81309. var from = this.from;
  81310. var to = this.to;
  81311. var distance = from.distanceTo(hitPointWorld);
  81312. var result = this.result;
  81313. // Skip back faces?
  81314. if(this.skipBackfaces && normal.dot(this._direction) > 0){
  81315. return;
  81316. }
  81317. result.hitFaceIndex = typeof(hitFaceIndex) !== 'undefined' ? hitFaceIndex : -1;
  81318. switch(this.mode){
  81319. case Ray.ALL:
  81320. this.hasHit = true;
  81321. result.set(
  81322. from,
  81323. to,
  81324. normal,
  81325. hitPointWorld,
  81326. shape,
  81327. body,
  81328. distance
  81329. );
  81330. result.hasHit = true;
  81331. this.callback(result);
  81332. break;
  81333. case Ray.CLOSEST:
  81334. // Store if closer than current closest
  81335. if(distance < result.distance || !result.hasHit){
  81336. this.hasHit = true;
  81337. result.hasHit = true;
  81338. result.set(
  81339. from,
  81340. to,
  81341. normal,
  81342. hitPointWorld,
  81343. shape,
  81344. body,
  81345. distance
  81346. );
  81347. }
  81348. break;
  81349. case Ray.ANY:
  81350. // Report and stop.
  81351. this.hasHit = true;
  81352. result.hasHit = true;
  81353. result.set(
  81354. from,
  81355. to,
  81356. normal,
  81357. hitPointWorld,
  81358. shape,
  81359. body,
  81360. distance
  81361. );
  81362. result._shouldStop = true;
  81363. break;
  81364. }
  81365. };
  81366. var v0 = new Vec3(),
  81367. intersect = new Vec3();
  81368. function distanceFromIntersection(from, direction, position) {
  81369. // v0 is vector from from to position
  81370. position.vsub(from,v0);
  81371. var dot = v0.dot(direction);
  81372. // intersect = direction*dot + from
  81373. direction.mult(dot,intersect);
  81374. intersect.vadd(from,intersect);
  81375. var distance = position.distanceTo(intersect);
  81376. return distance;
  81377. }
  81378. },{"../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){
  81379. var Vec3 = _dereq_('../math/Vec3');
  81380. module.exports = RaycastResult;
  81381. /**
  81382. * Storage for Ray casting data.
  81383. * @class RaycastResult
  81384. * @constructor
  81385. */
  81386. function RaycastResult(){
  81387. /**
  81388. * @property {Vec3} rayFromWorld
  81389. */
  81390. this.rayFromWorld = new Vec3();
  81391. /**
  81392. * @property {Vec3} rayToWorld
  81393. */
  81394. this.rayToWorld = new Vec3();
  81395. /**
  81396. * @property {Vec3} hitNormalWorld
  81397. */
  81398. this.hitNormalWorld = new Vec3();
  81399. /**
  81400. * @property {Vec3} hitPointWorld
  81401. */
  81402. this.hitPointWorld = new Vec3();
  81403. /**
  81404. * @property {boolean} hasHit
  81405. */
  81406. this.hasHit = false;
  81407. /**
  81408. * The hit shape, or null.
  81409. * @property {Shape} shape
  81410. */
  81411. this.shape = null;
  81412. /**
  81413. * The hit body, or null.
  81414. * @property {Body} body
  81415. */
  81416. this.body = null;
  81417. /**
  81418. * The index of the hit triangle, if the hit shape was a trimesh.
  81419. * @property {number} hitFaceIndex
  81420. * @default -1
  81421. */
  81422. this.hitFaceIndex = -1;
  81423. /**
  81424. * Distance to the hit. Will be set to -1 if there was no hit.
  81425. * @property {number} distance
  81426. * @default -1
  81427. */
  81428. this.distance = -1;
  81429. /**
  81430. * If the ray should stop traversing the bodies.
  81431. * @private
  81432. * @property {Boolean} _shouldStop
  81433. * @default false
  81434. */
  81435. this._shouldStop = false;
  81436. }
  81437. /**
  81438. * Reset all result data.
  81439. * @method reset
  81440. */
  81441. RaycastResult.prototype.reset = function () {
  81442. this.rayFromWorld.setZero();
  81443. this.rayToWorld.setZero();
  81444. this.hitNormalWorld.setZero();
  81445. this.hitPointWorld.setZero();
  81446. this.hasHit = false;
  81447. this.shape = null;
  81448. this.body = null;
  81449. this.hitFaceIndex = -1;
  81450. this.distance = -1;
  81451. this._shouldStop = false;
  81452. };
  81453. /**
  81454. * @method abort
  81455. */
  81456. RaycastResult.prototype.abort = function(){
  81457. this._shouldStop = true;
  81458. };
  81459. /**
  81460. * @method set
  81461. * @param {Vec3} rayFromWorld
  81462. * @param {Vec3} rayToWorld
  81463. * @param {Vec3} hitNormalWorld
  81464. * @param {Vec3} hitPointWorld
  81465. * @param {Shape} shape
  81466. * @param {Body} body
  81467. * @param {number} distance
  81468. */
  81469. RaycastResult.prototype.set = function(
  81470. rayFromWorld,
  81471. rayToWorld,
  81472. hitNormalWorld,
  81473. hitPointWorld,
  81474. shape,
  81475. body,
  81476. distance
  81477. ){
  81478. this.rayFromWorld.copy(rayFromWorld);
  81479. this.rayToWorld.copy(rayToWorld);
  81480. this.hitNormalWorld.copy(hitNormalWorld);
  81481. this.hitPointWorld.copy(hitPointWorld);
  81482. this.shape = shape;
  81483. this.body = body;
  81484. this.distance = distance;
  81485. };
  81486. },{"../math/Vec3":30}],11:[function(_dereq_,module,exports){
  81487. var Shape = _dereq_('../shapes/Shape');
  81488. var Broadphase = _dereq_('../collision/Broadphase');
  81489. module.exports = SAPBroadphase;
  81490. /**
  81491. * Sweep and prune broadphase along one axis.
  81492. *
  81493. * @class SAPBroadphase
  81494. * @constructor
  81495. * @param {World} [world]
  81496. * @extends Broadphase
  81497. */
  81498. function SAPBroadphase(world){
  81499. Broadphase.apply(this);
  81500. /**
  81501. * List of bodies currently in the broadphase.
  81502. * @property axisList
  81503. * @type {Array}
  81504. */
  81505. this.axisList = [];
  81506. /**
  81507. * The world to search in.
  81508. * @property world
  81509. * @type {World}
  81510. */
  81511. this.world = null;
  81512. /**
  81513. * 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.
  81514. * @property axisIndex
  81515. * @type {Number}
  81516. */
  81517. this.axisIndex = 0;
  81518. var axisList = this.axisList;
  81519. this._addBodyHandler = function(e){
  81520. axisList.push(e.body);
  81521. };
  81522. this._removeBodyHandler = function(e){
  81523. var idx = axisList.indexOf(e.body);
  81524. if(idx !== -1){
  81525. axisList.splice(idx,1);
  81526. }
  81527. };
  81528. if(world){
  81529. this.setWorld(world);
  81530. }
  81531. }
  81532. SAPBroadphase.prototype = new Broadphase();
  81533. /**
  81534. * Change the world
  81535. * @method setWorld
  81536. * @param {World} world
  81537. */
  81538. SAPBroadphase.prototype.setWorld = function(world){
  81539. // Clear the old axis array
  81540. this.axisList.length = 0;
  81541. // Add all bodies from the new world
  81542. for(var i=0; i<world.bodies.length; i++){
  81543. this.axisList.push(world.bodies[i]);
  81544. }
  81545. // Remove old handlers, if any
  81546. world.removeEventListener("addBody", this._addBodyHandler);
  81547. world.removeEventListener("removeBody", this._removeBodyHandler);
  81548. // Add handlers to update the list of bodies.
  81549. world.addEventListener("addBody", this._addBodyHandler);
  81550. world.addEventListener("removeBody", this._removeBodyHandler);
  81551. this.world = world;
  81552. this.dirty = true;
  81553. };
  81554. /**
  81555. * @static
  81556. * @method insertionSortX
  81557. * @param {Array} a
  81558. * @return {Array}
  81559. */
  81560. SAPBroadphase.insertionSortX = function(a) {
  81561. for(var i=1,l=a.length;i<l;i++) {
  81562. var v = a[i];
  81563. for(var j=i - 1;j>=0;j--) {
  81564. if(a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x){
  81565. break;
  81566. }
  81567. a[j+1] = a[j];
  81568. }
  81569. a[j+1] = v;
  81570. }
  81571. return a;
  81572. };
  81573. /**
  81574. * @static
  81575. * @method insertionSortY
  81576. * @param {Array} a
  81577. * @return {Array}
  81578. */
  81579. SAPBroadphase.insertionSortY = function(a) {
  81580. for(var i=1,l=a.length;i<l;i++) {
  81581. var v = a[i];
  81582. for(var j=i - 1;j>=0;j--) {
  81583. if(a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y){
  81584. break;
  81585. }
  81586. a[j+1] = a[j];
  81587. }
  81588. a[j+1] = v;
  81589. }
  81590. return a;
  81591. };
  81592. /**
  81593. * @static
  81594. * @method insertionSortZ
  81595. * @param {Array} a
  81596. * @return {Array}
  81597. */
  81598. SAPBroadphase.insertionSortZ = function(a) {
  81599. for(var i=1,l=a.length;i<l;i++) {
  81600. var v = a[i];
  81601. for(var j=i - 1;j>=0;j--) {
  81602. if(a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z){
  81603. break;
  81604. }
  81605. a[j+1] = a[j];
  81606. }
  81607. a[j+1] = v;
  81608. }
  81609. return a;
  81610. };
  81611. /**
  81612. * Collect all collision pairs
  81613. * @method collisionPairs
  81614. * @param {World} world
  81615. * @param {Array} p1
  81616. * @param {Array} p2
  81617. */
  81618. SAPBroadphase.prototype.collisionPairs = function(world,p1,p2){
  81619. var bodies = this.axisList,
  81620. N = bodies.length,
  81621. axisIndex = this.axisIndex,
  81622. i, j;
  81623. if(this.dirty){
  81624. this.sortList();
  81625. this.dirty = false;
  81626. }
  81627. // Look through the list
  81628. for(i=0; i !== N; i++){
  81629. var bi = bodies[i];
  81630. for(j=i+1; j < N; j++){
  81631. var bj = bodies[j];
  81632. if(!this.needBroadphaseCollision(bi,bj)){
  81633. continue;
  81634. }
  81635. if(!SAPBroadphase.checkBounds(bi,bj,axisIndex)){
  81636. break;
  81637. }
  81638. this.intersectionTest(bi,bj,p1,p2);
  81639. }
  81640. }
  81641. };
  81642. SAPBroadphase.prototype.sortList = function(){
  81643. var axisList = this.axisList;
  81644. var axisIndex = this.axisIndex;
  81645. var N = axisList.length;
  81646. // Update AABBs
  81647. for(var i = 0; i!==N; i++){
  81648. var bi = axisList[i];
  81649. if(bi.aabbNeedsUpdate){
  81650. bi.computeAABB();
  81651. }
  81652. }
  81653. // Sort the list
  81654. if(axisIndex === 0){
  81655. SAPBroadphase.insertionSortX(axisList);
  81656. } else if(axisIndex === 1){
  81657. SAPBroadphase.insertionSortY(axisList);
  81658. } else if(axisIndex === 2){
  81659. SAPBroadphase.insertionSortZ(axisList);
  81660. }
  81661. };
  81662. /**
  81663. * Check if the bounds of two bodies overlap, along the given SAP axis.
  81664. * @static
  81665. * @method checkBounds
  81666. * @param {Body} bi
  81667. * @param {Body} bj
  81668. * @param {Number} axisIndex
  81669. * @return {Boolean}
  81670. */
  81671. SAPBroadphase.checkBounds = function(bi, bj, axisIndex){
  81672. var biPos;
  81673. var bjPos;
  81674. if(axisIndex === 0){
  81675. biPos = bi.position.x;
  81676. bjPos = bj.position.x;
  81677. } else if(axisIndex === 1){
  81678. biPos = bi.position.y;
  81679. bjPos = bj.position.y;
  81680. } else if(axisIndex === 2){
  81681. biPos = bi.position.z;
  81682. bjPos = bj.position.z;
  81683. }
  81684. var ri = bi.boundingRadius,
  81685. rj = bj.boundingRadius,
  81686. boundA1 = biPos - ri,
  81687. boundA2 = biPos + ri,
  81688. boundB1 = bjPos - rj,
  81689. boundB2 = bjPos + rj;
  81690. return boundB1 < boundA2;
  81691. };
  81692. /**
  81693. * Computes the variance of the body positions and estimates the best
  81694. * axis to use. Will automatically set property .axisIndex.
  81695. * @method autoDetectAxis
  81696. */
  81697. SAPBroadphase.prototype.autoDetectAxis = function(){
  81698. var sumX=0,
  81699. sumX2=0,
  81700. sumY=0,
  81701. sumY2=0,
  81702. sumZ=0,
  81703. sumZ2=0,
  81704. bodies = this.axisList,
  81705. N = bodies.length,
  81706. invN=1/N;
  81707. for(var i=0; i!==N; i++){
  81708. var b = bodies[i];
  81709. var centerX = b.position.x;
  81710. sumX += centerX;
  81711. sumX2 += centerX*centerX;
  81712. var centerY = b.position.y;
  81713. sumY += centerY;
  81714. sumY2 += centerY*centerY;
  81715. var centerZ = b.position.z;
  81716. sumZ += centerZ;
  81717. sumZ2 += centerZ*centerZ;
  81718. }
  81719. var varianceX = sumX2 - sumX*sumX*invN,
  81720. varianceY = sumY2 - sumY*sumY*invN,
  81721. varianceZ = sumZ2 - sumZ*sumZ*invN;
  81722. if(varianceX > varianceY){
  81723. if(varianceX > varianceZ){
  81724. this.axisIndex = 0;
  81725. } else{
  81726. this.axisIndex = 2;
  81727. }
  81728. } else if(varianceY > varianceZ){
  81729. this.axisIndex = 1;
  81730. } else{
  81731. this.axisIndex = 2;
  81732. }
  81733. };
  81734. /**
  81735. * Returns all the bodies within an AABB.
  81736. * @method aabbQuery
  81737. * @param {World} world
  81738. * @param {AABB} aabb
  81739. * @param {array} result An array to store resulting bodies in.
  81740. * @return {array}
  81741. */
  81742. SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
  81743. result = result || [];
  81744. if(this.dirty){
  81745. this.sortList();
  81746. this.dirty = false;
  81747. }
  81748. var axisIndex = this.axisIndex, axis = 'x';
  81749. if(axisIndex === 1){ axis = 'y'; }
  81750. if(axisIndex === 2){ axis = 'z'; }
  81751. var axisList = this.axisList;
  81752. var lower = aabb.lowerBound[axis];
  81753. var upper = aabb.upperBound[axis];
  81754. for(var i = 0; i < axisList.length; i++){
  81755. var b = axisList[i];
  81756. if(b.aabbNeedsUpdate){
  81757. b.computeAABB();
  81758. }
  81759. if(b.aabb.overlaps(aabb)){
  81760. result.push(b);
  81761. }
  81762. }
  81763. return result;
  81764. };
  81765. },{"../collision/Broadphase":5,"../shapes/Shape":43}],12:[function(_dereq_,module,exports){
  81766. module.exports = ConeTwistConstraint;
  81767. var Constraint = _dereq_('./Constraint');
  81768. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  81769. var ConeEquation = _dereq_('../equations/ConeEquation');
  81770. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  81771. var ContactEquation = _dereq_('../equations/ContactEquation');
  81772. var Vec3 = _dereq_('../math/Vec3');
  81773. /**
  81774. * @class ConeTwistConstraint
  81775. * @constructor
  81776. * @author schteppe
  81777. * @param {Body} bodyA
  81778. * @param {Body} bodyB
  81779. * @param {object} [options]
  81780. * @param {Vec3} [options.pivotA]
  81781. * @param {Vec3} [options.pivotB]
  81782. * @param {Vec3} [options.axisA]
  81783. * @param {Vec3} [options.axisB]
  81784. * @param {Number} [options.maxForce=1e6]
  81785. * @extends PointToPointConstraint
  81786. */
  81787. function ConeTwistConstraint(bodyA, bodyB, options){
  81788. options = options || {};
  81789. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  81790. // Set pivot point in between
  81791. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  81792. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  81793. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  81794. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  81795. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  81796. this.collideConnected = !!options.collideConnected;
  81797. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  81798. /**
  81799. * @property {ConeEquation} coneEquation
  81800. */
  81801. var c = this.coneEquation = new ConeEquation(bodyA,bodyB,options);
  81802. /**
  81803. * @property {RotationalEquation} twistEquation
  81804. */
  81805. var t = this.twistEquation = new RotationalEquation(bodyA,bodyB,options);
  81806. this.twistAngle = typeof(options.twistAngle) !== 'undefined' ? options.twistAngle : 0;
  81807. // Make the cone equation push the bodies toward the cone axis, not outward
  81808. c.maxForce = 0;
  81809. c.minForce = -maxForce;
  81810. // Make the twist equation add torque toward the initial position
  81811. t.maxForce = 0;
  81812. t.minForce = -maxForce;
  81813. this.equations.push(c, t);
  81814. }
  81815. ConeTwistConstraint.prototype = new PointToPointConstraint();
  81816. ConeTwistConstraint.constructor = ConeTwistConstraint;
  81817. var ConeTwistConstraint_update_tmpVec1 = new Vec3();
  81818. var ConeTwistConstraint_update_tmpVec2 = new Vec3();
  81819. ConeTwistConstraint.prototype.update = function(){
  81820. var bodyA = this.bodyA,
  81821. bodyB = this.bodyB,
  81822. cone = this.coneEquation,
  81823. twist = this.twistEquation;
  81824. PointToPointConstraint.prototype.update.call(this);
  81825. // Update the axes to the cone constraint
  81826. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  81827. bodyB.vectorToWorldFrame(this.axisB, cone.axisB);
  81828. // Update the world axes in the twist constraint
  81829. this.axisA.tangents(twist.axisA, twist.axisA);
  81830. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  81831. this.axisB.tangents(twist.axisB, twist.axisB);
  81832. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  81833. cone.angle = this.angle;
  81834. twist.maxAngle = this.twistAngle;
  81835. };
  81836. },{"../equations/ConeEquation":18,"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],13:[function(_dereq_,module,exports){
  81837. module.exports = Constraint;
  81838. var Utils = _dereq_('../utils/Utils');
  81839. /**
  81840. * Constraint base class
  81841. * @class Constraint
  81842. * @author schteppe
  81843. * @constructor
  81844. * @param {Body} bodyA
  81845. * @param {Body} bodyB
  81846. * @param {object} [options]
  81847. * @param {boolean} [options.collideConnected=true]
  81848. * @param {boolean} [options.wakeUpBodies=true]
  81849. */
  81850. function Constraint(bodyA, bodyB, options){
  81851. options = Utils.defaults(options,{
  81852. collideConnected : true,
  81853. wakeUpBodies : true,
  81854. });
  81855. /**
  81856. * Equations to be solved in this constraint
  81857. * @property equations
  81858. * @type {Array}
  81859. */
  81860. this.equations = [];
  81861. /**
  81862. * @property {Body} bodyA
  81863. */
  81864. this.bodyA = bodyA;
  81865. /**
  81866. * @property {Body} bodyB
  81867. */
  81868. this.bodyB = bodyB;
  81869. /**
  81870. * @property {Number} id
  81871. */
  81872. this.id = Constraint.idCounter++;
  81873. /**
  81874. * Set to true if you want the bodies to collide when they are connected.
  81875. * @property collideConnected
  81876. * @type {boolean}
  81877. */
  81878. this.collideConnected = options.collideConnected;
  81879. if(options.wakeUpBodies){
  81880. if(bodyA){
  81881. bodyA.wakeUp();
  81882. }
  81883. if(bodyB){
  81884. bodyB.wakeUp();
  81885. }
  81886. }
  81887. }
  81888. /**
  81889. * Update all the equations with data.
  81890. * @method update
  81891. */
  81892. Constraint.prototype.update = function(){
  81893. throw new Error("method update() not implmemented in this Constraint subclass!");
  81894. };
  81895. /**
  81896. * Enables all equations in the constraint.
  81897. * @method enable
  81898. */
  81899. Constraint.prototype.enable = function(){
  81900. var eqs = this.equations;
  81901. for(var i=0; i<eqs.length; i++){
  81902. eqs[i].enabled = true;
  81903. }
  81904. };
  81905. /**
  81906. * Disables all equations in the constraint.
  81907. * @method disable
  81908. */
  81909. Constraint.prototype.disable = function(){
  81910. var eqs = this.equations;
  81911. for(var i=0; i<eqs.length; i++){
  81912. eqs[i].enabled = false;
  81913. }
  81914. };
  81915. Constraint.idCounter = 0;
  81916. },{"../utils/Utils":53}],14:[function(_dereq_,module,exports){
  81917. module.exports = DistanceConstraint;
  81918. var Constraint = _dereq_('./Constraint');
  81919. var ContactEquation = _dereq_('../equations/ContactEquation');
  81920. /**
  81921. * Constrains two bodies to be at a constant distance from each others center of mass.
  81922. * @class DistanceConstraint
  81923. * @constructor
  81924. * @author schteppe
  81925. * @param {Body} bodyA
  81926. * @param {Body} bodyB
  81927. * @param {Number} [distance] The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  81928. * @param {Number} [maxForce=1e6]
  81929. * @extends Constraint
  81930. */
  81931. function DistanceConstraint(bodyA,bodyB,distance,maxForce){
  81932. Constraint.call(this,bodyA,bodyB);
  81933. if(typeof(distance)==="undefined") {
  81934. distance = bodyA.position.distanceTo(bodyB.position);
  81935. }
  81936. if(typeof(maxForce)==="undefined") {
  81937. maxForce = 1e6;
  81938. }
  81939. /**
  81940. * @property {number} distance
  81941. */
  81942. this.distance = distance;
  81943. /**
  81944. * @property {ContactEquation} distanceEquation
  81945. */
  81946. var eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  81947. this.equations.push(eq);
  81948. // Make it bidirectional
  81949. eq.minForce = -maxForce;
  81950. eq.maxForce = maxForce;
  81951. }
  81952. DistanceConstraint.prototype = new Constraint();
  81953. DistanceConstraint.prototype.update = function(){
  81954. var bodyA = this.bodyA;
  81955. var bodyB = this.bodyB;
  81956. var eq = this.distanceEquation;
  81957. var halfDist = this.distance * 0.5;
  81958. var normal = eq.ni;
  81959. bodyB.position.vsub(bodyA.position, normal);
  81960. normal.normalize();
  81961. normal.mult(halfDist, eq.ri);
  81962. normal.mult(-halfDist, eq.rj);
  81963. };
  81964. },{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(_dereq_,module,exports){
  81965. module.exports = HingeConstraint;
  81966. var Constraint = _dereq_('./Constraint');
  81967. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  81968. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  81969. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  81970. var ContactEquation = _dereq_('../equations/ContactEquation');
  81971. var Vec3 = _dereq_('../math/Vec3');
  81972. /**
  81973. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  81974. * @class HingeConstraint
  81975. * @constructor
  81976. * @author schteppe
  81977. * @param {Body} bodyA
  81978. * @param {Body} bodyB
  81979. * @param {object} [options]
  81980. * @param {Vec3} [options.pivotA] A point defined locally in bodyA. This defines the offset of axisA.
  81981. * @param {Vec3} [options.axisA] An axis that bodyA can rotate around, defined locally in bodyA.
  81982. * @param {Vec3} [options.pivotB]
  81983. * @param {Vec3} [options.axisB]
  81984. * @param {Number} [options.maxForce=1e6]
  81985. * @extends PointToPointConstraint
  81986. */
  81987. function HingeConstraint(bodyA, bodyB, options){
  81988. options = options || {};
  81989. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  81990. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  81991. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  81992. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  81993. /**
  81994. * Rotation axis, defined locally in bodyA.
  81995. * @property {Vec3} axisA
  81996. */
  81997. var axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1,0,0);
  81998. axisA.normalize();
  81999. /**
  82000. * Rotation axis, defined locally in bodyB.
  82001. * @property {Vec3} axisB
  82002. */
  82003. var axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1,0,0);
  82004. axisB.normalize();
  82005. /**
  82006. * @property {RotationalEquation} rotationalEquation1
  82007. */
  82008. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  82009. /**
  82010. * @property {RotationalEquation} rotationalEquation2
  82011. */
  82012. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  82013. /**
  82014. * @property {RotationalMotorEquation} motorEquation
  82015. */
  82016. var motor = this.motorEquation = new RotationalMotorEquation(bodyA,bodyB,maxForce);
  82017. motor.enabled = false; // Not enabled by default
  82018. // Equations to be fed to the solver
  82019. this.equations.push(
  82020. r1, // rotational1
  82021. r2, // rotational2
  82022. motor
  82023. );
  82024. }
  82025. HingeConstraint.prototype = new PointToPointConstraint();
  82026. HingeConstraint.constructor = HingeConstraint;
  82027. /**
  82028. * @method enableMotor
  82029. */
  82030. HingeConstraint.prototype.enableMotor = function(){
  82031. this.motorEquation.enabled = true;
  82032. };
  82033. /**
  82034. * @method disableMotor
  82035. */
  82036. HingeConstraint.prototype.disableMotor = function(){
  82037. this.motorEquation.enabled = false;
  82038. };
  82039. /**
  82040. * @method setMotorSpeed
  82041. * @param {number} speed
  82042. */
  82043. HingeConstraint.prototype.setMotorSpeed = function(speed){
  82044. this.motorEquation.targetVelocity = speed;
  82045. };
  82046. /**
  82047. * @method setMotorMaxForce
  82048. * @param {number} maxForce
  82049. */
  82050. HingeConstraint.prototype.setMotorMaxForce = function(maxForce){
  82051. this.motorEquation.maxForce = maxForce;
  82052. this.motorEquation.minForce = -maxForce;
  82053. };
  82054. var HingeConstraint_update_tmpVec1 = new Vec3();
  82055. var HingeConstraint_update_tmpVec2 = new Vec3();
  82056. HingeConstraint.prototype.update = function(){
  82057. var bodyA = this.bodyA,
  82058. bodyB = this.bodyB,
  82059. motor = this.motorEquation,
  82060. r1 = this.rotationalEquation1,
  82061. r2 = this.rotationalEquation2,
  82062. worldAxisA = HingeConstraint_update_tmpVec1,
  82063. worldAxisB = HingeConstraint_update_tmpVec2;
  82064. var axisA = this.axisA;
  82065. var axisB = this.axisB;
  82066. PointToPointConstraint.prototype.update.call(this);
  82067. // Get world axes
  82068. bodyA.quaternion.vmult(axisA, worldAxisA);
  82069. bodyB.quaternion.vmult(axisB, worldAxisB);
  82070. worldAxisA.tangents(r1.axisA, r2.axisA);
  82071. r1.axisB.copy(worldAxisB);
  82072. r2.axisB.copy(worldAxisB);
  82073. if(this.motorEquation.enabled){
  82074. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  82075. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  82076. }
  82077. };
  82078. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(_dereq_,module,exports){
  82079. module.exports = LockConstraint;
  82080. var Constraint = _dereq_('./Constraint');
  82081. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  82082. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  82083. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  82084. var ContactEquation = _dereq_('../equations/ContactEquation');
  82085. var Vec3 = _dereq_('../math/Vec3');
  82086. /**
  82087. * Lock constraint. Will remove all degrees of freedom between the bodies.
  82088. * @class LockConstraint
  82089. * @constructor
  82090. * @author schteppe
  82091. * @param {Body} bodyA
  82092. * @param {Body} bodyB
  82093. * @param {object} [options]
  82094. * @param {Number} [options.maxForce=1e6]
  82095. * @extends PointToPointConstraint
  82096. */
  82097. function LockConstraint(bodyA, bodyB, options){
  82098. options = options || {};
  82099. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  82100. // Set pivot point in between
  82101. var pivotA = new Vec3();
  82102. var pivotB = new Vec3();
  82103. var halfWay = new Vec3();
  82104. bodyA.position.vadd(bodyB.position, halfWay);
  82105. halfWay.scale(0.5, halfWay);
  82106. bodyB.pointToLocalFrame(halfWay, pivotB);
  82107. bodyA.pointToLocalFrame(halfWay, pivotA);
  82108. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  82109. /**
  82110. * @property {RotationalEquation} rotationalEquation1
  82111. */
  82112. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  82113. /**
  82114. * @property {RotationalEquation} rotationalEquation2
  82115. */
  82116. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  82117. /**
  82118. * @property {RotationalEquation} rotationalEquation3
  82119. */
  82120. var r3 = this.rotationalEquation3 = new RotationalEquation(bodyA,bodyB,options);
  82121. this.equations.push(r1, r2, r3);
  82122. }
  82123. LockConstraint.prototype = new PointToPointConstraint();
  82124. LockConstraint.constructor = LockConstraint;
  82125. var LockConstraint_update_tmpVec1 = new Vec3();
  82126. var LockConstraint_update_tmpVec2 = new Vec3();
  82127. LockConstraint.prototype.update = function(){
  82128. var bodyA = this.bodyA,
  82129. bodyB = this.bodyB,
  82130. motor = this.motorEquation,
  82131. r1 = this.rotationalEquation1,
  82132. r2 = this.rotationalEquation2,
  82133. r3 = this.rotationalEquation3,
  82134. worldAxisA = LockConstraint_update_tmpVec1,
  82135. worldAxisB = LockConstraint_update_tmpVec2;
  82136. PointToPointConstraint.prototype.update.call(this);
  82137. bodyA.vectorToWorldFrame(Vec3.UNIT_X, r1.axisA);
  82138. bodyB.vectorToWorldFrame(Vec3.UNIT_Y, r1.axisB);
  82139. bodyA.vectorToWorldFrame(Vec3.UNIT_Y, r2.axisA);
  82140. bodyB.vectorToWorldFrame(Vec3.UNIT_Z, r2.axisB);
  82141. bodyA.vectorToWorldFrame(Vec3.UNIT_Z, r3.axisA);
  82142. bodyB.vectorToWorldFrame(Vec3.UNIT_X, r3.axisB);
  82143. };
  82144. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(_dereq_,module,exports){
  82145. module.exports = PointToPointConstraint;
  82146. var Constraint = _dereq_('./Constraint');
  82147. var ContactEquation = _dereq_('../equations/ContactEquation');
  82148. var Vec3 = _dereq_('../math/Vec3');
  82149. /**
  82150. * Connects two bodies at given offset points.
  82151. * @class PointToPointConstraint
  82152. * @extends Constraint
  82153. * @constructor
  82154. * @param {Body} bodyA
  82155. * @param {Vec3} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  82156. * @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.
  82157. * @param {Vec3} pivotB See pivotA.
  82158. * @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
  82159. *
  82160. * @example
  82161. * var bodyA = new Body({ mass: 1 });
  82162. * var bodyB = new Body({ mass: 1 });
  82163. * bodyA.position.set(-1, 0, 0);
  82164. * bodyB.position.set(1, 0, 0);
  82165. * bodyA.addShape(shapeA);
  82166. * bodyB.addShape(shapeB);
  82167. * world.addBody(bodyA);
  82168. * world.addBody(bodyB);
  82169. * var localPivotA = new Vec3(1, 0, 0);
  82170. * var localPivotB = new Vec3(-1, 0, 0);
  82171. * var constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB);
  82172. * world.addConstraint(constraint);
  82173. */
  82174. function PointToPointConstraint(bodyA,pivotA,bodyB,pivotB,maxForce){
  82175. Constraint.call(this,bodyA,bodyB);
  82176. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  82177. /**
  82178. * Pivot, defined locally in bodyA.
  82179. * @property {Vec3} pivotA
  82180. */
  82181. this.pivotA = pivotA ? pivotA.clone() : new Vec3();
  82182. /**
  82183. * Pivot, defined locally in bodyB.
  82184. * @property {Vec3} pivotB
  82185. */
  82186. this.pivotB = pivotB ? pivotB.clone() : new Vec3();
  82187. /**
  82188. * @property {ContactEquation} equationX
  82189. */
  82190. var x = this.equationX = new ContactEquation(bodyA,bodyB);
  82191. /**
  82192. * @property {ContactEquation} equationY
  82193. */
  82194. var y = this.equationY = new ContactEquation(bodyA,bodyB);
  82195. /**
  82196. * @property {ContactEquation} equationZ
  82197. */
  82198. var z = this.equationZ = new ContactEquation(bodyA,bodyB);
  82199. // Equations to be fed to the solver
  82200. this.equations.push(x, y, z);
  82201. // Make the equations bidirectional
  82202. x.minForce = y.minForce = z.minForce = -maxForce;
  82203. x.maxForce = y.maxForce = z.maxForce = maxForce;
  82204. x.ni.set(1, 0, 0);
  82205. y.ni.set(0, 1, 0);
  82206. z.ni.set(0, 0, 1);
  82207. }
  82208. PointToPointConstraint.prototype = new Constraint();
  82209. PointToPointConstraint.prototype.update = function(){
  82210. var bodyA = this.bodyA;
  82211. var bodyB = this.bodyB;
  82212. var x = this.equationX;
  82213. var y = this.equationY;
  82214. var z = this.equationZ;
  82215. // Rotate the pivots to world space
  82216. bodyA.quaternion.vmult(this.pivotA,x.ri);
  82217. bodyB.quaternion.vmult(this.pivotB,x.rj);
  82218. y.ri.copy(x.ri);
  82219. y.rj.copy(x.rj);
  82220. z.ri.copy(x.ri);
  82221. z.rj.copy(x.rj);
  82222. };
  82223. },{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(_dereq_,module,exports){
  82224. module.exports = ConeEquation;
  82225. var Vec3 = _dereq_('../math/Vec3');
  82226. var Mat3 = _dereq_('../math/Mat3');
  82227. var Equation = _dereq_('./Equation');
  82228. /**
  82229. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  82230. * @class ConeEquation
  82231. * @constructor
  82232. * @author schteppe
  82233. * @param {Body} bodyA
  82234. * @param {Body} bodyB
  82235. * @param {Vec3} [options.axisA] Local axis in A
  82236. * @param {Vec3} [options.axisB] Local axis in B
  82237. * @param {Vec3} [options.angle] The "cone angle" to keep
  82238. * @param {number} [options.maxForce=1e6]
  82239. * @extends Equation
  82240. */
  82241. function ConeEquation(bodyA, bodyB, options){
  82242. options = options || {};
  82243. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  82244. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  82245. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  82246. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  82247. /**
  82248. * The cone angle to keep
  82249. * @property {number} angle
  82250. */
  82251. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  82252. }
  82253. ConeEquation.prototype = new Equation();
  82254. ConeEquation.prototype.constructor = ConeEquation;
  82255. var tmpVec1 = new Vec3();
  82256. var tmpVec2 = new Vec3();
  82257. ConeEquation.prototype.computeB = function(h){
  82258. var a = this.a,
  82259. b = this.b,
  82260. ni = this.axisA,
  82261. nj = this.axisB,
  82262. nixnj = tmpVec1,
  82263. njxni = tmpVec2,
  82264. GA = this.jacobianElementA,
  82265. GB = this.jacobianElementB;
  82266. // Caluclate cross products
  82267. ni.cross(nj, nixnj);
  82268. nj.cross(ni, njxni);
  82269. // The angle between two vector is:
  82270. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  82271. // g = a * b
  82272. // gdot = (b x a) * wi + (a x b) * wj
  82273. // G = [0 bxa 0 axb]
  82274. // W = [vi wi vj wj]
  82275. GA.rotational.copy(njxni);
  82276. GB.rotational.copy(nixnj);
  82277. var g = Math.cos(this.angle) - ni.dot(nj),
  82278. GW = this.computeGW(),
  82279. GiMf = this.computeGiMf();
  82280. var B = - g * a - GW * b - h * GiMf;
  82281. return B;
  82282. };
  82283. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(_dereq_,module,exports){
  82284. module.exports = ContactEquation;
  82285. var Equation = _dereq_('./Equation');
  82286. var Vec3 = _dereq_('../math/Vec3');
  82287. var Mat3 = _dereq_('../math/Mat3');
  82288. /**
  82289. * Contact/non-penetration constraint equation
  82290. * @class ContactEquation
  82291. * @constructor
  82292. * @author schteppe
  82293. * @param {Body} bodyA
  82294. * @param {Body} bodyB
  82295. * @extends Equation
  82296. */
  82297. function ContactEquation(bodyA, bodyB, maxForce){
  82298. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  82299. Equation.call(this, bodyA, bodyB, 0, maxForce);
  82300. /**
  82301. * @property restitution
  82302. * @type {Number}
  82303. */
  82304. this.restitution = 0.0; // "bounciness": u1 = -e*u0
  82305. /**
  82306. * World-oriented vector that goes from the center of bi to the contact point.
  82307. * @property {Vec3} ri
  82308. */
  82309. this.ri = new Vec3();
  82310. /**
  82311. * World-oriented vector that starts in body j position and goes to the contact point.
  82312. * @property {Vec3} rj
  82313. */
  82314. this.rj = new Vec3();
  82315. /**
  82316. * Contact normal, pointing out of body i.
  82317. * @property {Vec3} ni
  82318. */
  82319. this.ni = new Vec3();
  82320. }
  82321. ContactEquation.prototype = new Equation();
  82322. ContactEquation.prototype.constructor = ContactEquation;
  82323. var ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  82324. var ContactEquation_computeB_temp2 = new Vec3();
  82325. var ContactEquation_computeB_temp3 = new Vec3();
  82326. ContactEquation.prototype.computeB = function(h){
  82327. var a = this.a,
  82328. b = this.b,
  82329. bi = this.bi,
  82330. bj = this.bj,
  82331. ri = this.ri,
  82332. rj = this.rj,
  82333. rixn = ContactEquation_computeB_temp1,
  82334. rjxn = ContactEquation_computeB_temp2,
  82335. vi = bi.velocity,
  82336. wi = bi.angularVelocity,
  82337. fi = bi.force,
  82338. taui = bi.torque,
  82339. vj = bj.velocity,
  82340. wj = bj.angularVelocity,
  82341. fj = bj.force,
  82342. tauj = bj.torque,
  82343. penetrationVec = ContactEquation_computeB_temp3,
  82344. GA = this.jacobianElementA,
  82345. GB = this.jacobianElementB,
  82346. n = this.ni;
  82347. // Caluclate cross products
  82348. ri.cross(n,rixn);
  82349. rj.cross(n,rjxn);
  82350. // g = xj+rj -(xi+ri)
  82351. // G = [ -ni -rixn ni rjxn ]
  82352. n.negate(GA.spatial);
  82353. rixn.negate(GA.rotational);
  82354. GB.spatial.copy(n);
  82355. GB.rotational.copy(rjxn);
  82356. // Calculate the penetration vector
  82357. penetrationVec.copy(bj.position);
  82358. penetrationVec.vadd(rj,penetrationVec);
  82359. penetrationVec.vsub(bi.position,penetrationVec);
  82360. penetrationVec.vsub(ri,penetrationVec);
  82361. var g = n.dot(penetrationVec);
  82362. // Compute iteration
  82363. var ePlusOne = this.restitution + 1;
  82364. var GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  82365. var GiMf = this.computeGiMf();
  82366. var B = - g * a - GW * b - h*GiMf;
  82367. return B;
  82368. };
  82369. var ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  82370. var ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  82371. var ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  82372. var ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  82373. var ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  82374. /**
  82375. * Get the current relative velocity in the contact point.
  82376. * @method getImpactVelocityAlongNormal
  82377. * @return {number}
  82378. */
  82379. ContactEquation.prototype.getImpactVelocityAlongNormal = function(){
  82380. var vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  82381. var vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  82382. var xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  82383. var xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  82384. var relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  82385. this.bi.position.vadd(this.ri, xi);
  82386. this.bj.position.vadd(this.rj, xj);
  82387. this.bi.getVelocityAtWorldPoint(xi, vi);
  82388. this.bj.getVelocityAtWorldPoint(xj, vj);
  82389. vi.vsub(vj, relVel);
  82390. return this.ni.dot(relVel);
  82391. };
  82392. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(_dereq_,module,exports){
  82393. module.exports = Equation;
  82394. var JacobianElement = _dereq_('../math/JacobianElement'),
  82395. Vec3 = _dereq_('../math/Vec3');
  82396. /**
  82397. * Equation base class
  82398. * @class Equation
  82399. * @constructor
  82400. * @author schteppe
  82401. * @param {Body} bi
  82402. * @param {Body} bj
  82403. * @param {Number} minForce Minimum (read: negative max) force to be applied by the constraint.
  82404. * @param {Number} maxForce Maximum (read: positive max) force to be applied by the constraint.
  82405. */
  82406. function Equation(bi,bj,minForce,maxForce){
  82407. this.id = Equation.id++;
  82408. /**
  82409. * @property {number} minForce
  82410. */
  82411. this.minForce = typeof(minForce)==="undefined" ? -1e6 : minForce;
  82412. /**
  82413. * @property {number} maxForce
  82414. */
  82415. this.maxForce = typeof(maxForce)==="undefined" ? 1e6 : maxForce;
  82416. /**
  82417. * @property bi
  82418. * @type {Body}
  82419. */
  82420. this.bi = bi;
  82421. /**
  82422. * @property bj
  82423. * @type {Body}
  82424. */
  82425. this.bj = bj;
  82426. /**
  82427. * SPOOK parameter
  82428. * @property {number} a
  82429. */
  82430. this.a = 0.0;
  82431. /**
  82432. * SPOOK parameter
  82433. * @property {number} b
  82434. */
  82435. this.b = 0.0;
  82436. /**
  82437. * SPOOK parameter
  82438. * @property {number} eps
  82439. */
  82440. this.eps = 0.0;
  82441. /**
  82442. * @property {JacobianElement} jacobianElementA
  82443. */
  82444. this.jacobianElementA = new JacobianElement();
  82445. /**
  82446. * @property {JacobianElement} jacobianElementB
  82447. */
  82448. this.jacobianElementB = new JacobianElement();
  82449. /**
  82450. * @property {boolean} enabled
  82451. * @default true
  82452. */
  82453. this.enabled = true;
  82454. // Set typical spook params
  82455. this.setSpookParams(1e7,4,1/60);
  82456. }
  82457. Equation.prototype.constructor = Equation;
  82458. Equation.id = 0;
  82459. /**
  82460. * Recalculates a,b,eps.
  82461. * @method setSpookParams
  82462. */
  82463. Equation.prototype.setSpookParams = function(stiffness,relaxation,timeStep){
  82464. var d = relaxation,
  82465. k = stiffness,
  82466. h = timeStep;
  82467. this.a = 4.0 / (h * (1 + 4 * d));
  82468. this.b = (4.0 * d) / (1 + 4 * d);
  82469. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  82470. };
  82471. /**
  82472. * Computes the RHS of the SPOOK equation
  82473. * @method computeB
  82474. * @return {Number}
  82475. */
  82476. Equation.prototype.computeB = function(a,b,h){
  82477. var GW = this.computeGW(),
  82478. Gq = this.computeGq(),
  82479. GiMf = this.computeGiMf();
  82480. return - Gq * a - GW * b - GiMf*h;
  82481. };
  82482. /**
  82483. * Computes G*q, where q are the generalized body coordinates
  82484. * @method computeGq
  82485. * @return {Number}
  82486. */
  82487. Equation.prototype.computeGq = function(){
  82488. var GA = this.jacobianElementA,
  82489. GB = this.jacobianElementB,
  82490. bi = this.bi,
  82491. bj = this.bj,
  82492. xi = bi.position,
  82493. xj = bj.position;
  82494. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  82495. };
  82496. var zero = new Vec3();
  82497. /**
  82498. * Computes G*W, where W are the body velocities
  82499. * @method computeGW
  82500. * @return {Number}
  82501. */
  82502. Equation.prototype.computeGW = function(){
  82503. var GA = this.jacobianElementA,
  82504. GB = this.jacobianElementB,
  82505. bi = this.bi,
  82506. bj = this.bj,
  82507. vi = bi.velocity,
  82508. vj = bj.velocity,
  82509. wi = bi.angularVelocity || zero,
  82510. wj = bj.angularVelocity || zero;
  82511. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  82512. };
  82513. /**
  82514. * Computes G*Wlambda, where W are the body velocities
  82515. * @method computeGWlambda
  82516. * @return {Number}
  82517. */
  82518. Equation.prototype.computeGWlambda = function(){
  82519. var GA = this.jacobianElementA,
  82520. GB = this.jacobianElementB,
  82521. bi = this.bi,
  82522. bj = this.bj,
  82523. vi = bi.vlambda,
  82524. vj = bj.vlambda,
  82525. wi = bi.wlambda || zero,
  82526. wj = bj.wlambda || zero;
  82527. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  82528. };
  82529. /**
  82530. * 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.
  82531. * @method computeGiMf
  82532. * @return {Number}
  82533. */
  82534. var iMfi = new Vec3(),
  82535. iMfj = new Vec3(),
  82536. invIi_vmult_taui = new Vec3(),
  82537. invIj_vmult_tauj = new Vec3();
  82538. Equation.prototype.computeGiMf = function(){
  82539. var GA = this.jacobianElementA,
  82540. GB = this.jacobianElementB,
  82541. bi = this.bi,
  82542. bj = this.bj,
  82543. fi = bi.force,
  82544. ti = bi.torque,
  82545. fj = bj.force,
  82546. tj = bj.torque,
  82547. invMassi = bi.invMassSolve,
  82548. invMassj = bj.invMassSolve;
  82549. if(bi.invInertiaWorldSolve){ bi.invInertiaWorldSolve.vmult(ti,invIi_vmult_taui); }
  82550. else { invIi_vmult_taui.set(0,0,0); }
  82551. if(bj.invInertiaWorldSolve){ bj.invInertiaWorldSolve.vmult(tj,invIj_vmult_tauj); }
  82552. else { invIj_vmult_tauj.set(0,0,0); }
  82553. fi.mult(invMassi,iMfi);
  82554. fj.mult(invMassj,iMfj);
  82555. return GA.multiplyVectors(iMfi,invIi_vmult_taui) + GB.multiplyVectors(iMfj,invIj_vmult_tauj);
  82556. };
  82557. /**
  82558. * Computes G*inv(M)*G'
  82559. * @method computeGiMGt
  82560. * @return {Number}
  82561. */
  82562. var tmp = new Vec3();
  82563. Equation.prototype.computeGiMGt = function(){
  82564. var GA = this.jacobianElementA,
  82565. GB = this.jacobianElementB,
  82566. bi = this.bi,
  82567. bj = this.bj,
  82568. invMassi = bi.invMassSolve,
  82569. invMassj = bj.invMassSolve,
  82570. invIi = bi.invInertiaWorldSolve,
  82571. invIj = bj.invInertiaWorldSolve,
  82572. result = invMassi + invMassj;
  82573. if(invIi){
  82574. invIi.vmult(GA.rotational,tmp);
  82575. result += tmp.dot(GA.rotational);
  82576. }
  82577. if(invIj){
  82578. invIj.vmult(GB.rotational,tmp);
  82579. result += tmp.dot(GB.rotational);
  82580. }
  82581. return result;
  82582. };
  82583. var addToWlambda_temp = new Vec3(),
  82584. addToWlambda_Gi = new Vec3(),
  82585. addToWlambda_Gj = new Vec3(),
  82586. addToWlambda_ri = new Vec3(),
  82587. addToWlambda_rj = new Vec3(),
  82588. addToWlambda_Mdiag = new Vec3();
  82589. /**
  82590. * Add constraint velocity to the bodies.
  82591. * @method addToWlambda
  82592. * @param {Number} deltalambda
  82593. */
  82594. Equation.prototype.addToWlambda = function(deltalambda){
  82595. var GA = this.jacobianElementA,
  82596. GB = this.jacobianElementB,
  82597. bi = this.bi,
  82598. bj = this.bj,
  82599. temp = addToWlambda_temp;
  82600. // Add to linear velocity
  82601. // v_lambda += inv(M) * delta_lamba * G
  82602. GA.spatial.mult(bi.invMassSolve * deltalambda,temp);
  82603. bi.vlambda.vadd(temp, bi.vlambda);
  82604. GB.spatial.mult(bj.invMassSolve * deltalambda,temp);
  82605. bj.vlambda.vadd(temp, bj.vlambda);
  82606. // Add to angular velocity
  82607. if(bi.invInertiaWorldSolve){
  82608. bi.invInertiaWorldSolve.vmult(GA.rotational,temp);
  82609. temp.mult(deltalambda,temp);
  82610. bi.wlambda.vadd(temp,bi.wlambda);
  82611. }
  82612. if(bj.invInertiaWorldSolve){
  82613. bj.invInertiaWorldSolve.vmult(GB.rotational,temp);
  82614. temp.mult(deltalambda,temp);
  82615. bj.wlambda.vadd(temp,bj.wlambda);
  82616. }
  82617. };
  82618. /**
  82619. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  82620. * @method computeInvC
  82621. * @param {Number} eps
  82622. * @return {Number}
  82623. */
  82624. Equation.prototype.computeC = function(){
  82625. return this.computeGiMGt() + this.eps;
  82626. };
  82627. },{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(_dereq_,module,exports){
  82628. module.exports = FrictionEquation;
  82629. var Equation = _dereq_('./Equation');
  82630. var Vec3 = _dereq_('../math/Vec3');
  82631. var Mat3 = _dereq_('../math/Mat3');
  82632. /**
  82633. * Constrains the slipping in a contact along a tangent
  82634. * @class FrictionEquation
  82635. * @constructor
  82636. * @author schteppe
  82637. * @param {Body} bodyA
  82638. * @param {Body} bodyB
  82639. * @param {Number} slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  82640. * @extends Equation
  82641. */
  82642. function FrictionEquation(bodyA, bodyB, slipForce){
  82643. Equation.call(this,bodyA, bodyB, -slipForce, slipForce);
  82644. this.ri = new Vec3();
  82645. this.rj = new Vec3();
  82646. this.t = new Vec3(); // tangent
  82647. }
  82648. FrictionEquation.prototype = new Equation();
  82649. FrictionEquation.prototype.constructor = FrictionEquation;
  82650. var FrictionEquation_computeB_temp1 = new Vec3();
  82651. var FrictionEquation_computeB_temp2 = new Vec3();
  82652. FrictionEquation.prototype.computeB = function(h){
  82653. var a = this.a,
  82654. b = this.b,
  82655. bi = this.bi,
  82656. bj = this.bj,
  82657. ri = this.ri,
  82658. rj = this.rj,
  82659. rixt = FrictionEquation_computeB_temp1,
  82660. rjxt = FrictionEquation_computeB_temp2,
  82661. t = this.t;
  82662. // Caluclate cross products
  82663. ri.cross(t,rixt);
  82664. rj.cross(t,rjxt);
  82665. // G = [-t -rixt t rjxt]
  82666. // And remember, this is a pure velocity constraint, g is always zero!
  82667. var GA = this.jacobianElementA,
  82668. GB = this.jacobianElementB;
  82669. t.negate(GA.spatial);
  82670. rixt.negate(GA.rotational);
  82671. GB.spatial.copy(t);
  82672. GB.rotational.copy(rjxt);
  82673. var GW = this.computeGW();
  82674. var GiMf = this.computeGiMf();
  82675. var B = - GW * b - h * GiMf;
  82676. return B;
  82677. };
  82678. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(_dereq_,module,exports){
  82679. module.exports = RotationalEquation;
  82680. var Vec3 = _dereq_('../math/Vec3');
  82681. var Mat3 = _dereq_('../math/Mat3');
  82682. var Equation = _dereq_('./Equation');
  82683. /**
  82684. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  82685. * @class RotationalEquation
  82686. * @constructor
  82687. * @author schteppe
  82688. * @param {Body} bodyA
  82689. * @param {Body} bodyB
  82690. * @param {Vec3} [options.axisA]
  82691. * @param {Vec3} [options.axisB]
  82692. * @param {number} [options.maxForce]
  82693. * @extends Equation
  82694. */
  82695. function RotationalEquation(bodyA, bodyB, options){
  82696. options = options || {};
  82697. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  82698. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  82699. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  82700. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  82701. this.maxAngle = Math.PI / 2;
  82702. }
  82703. RotationalEquation.prototype = new Equation();
  82704. RotationalEquation.prototype.constructor = RotationalEquation;
  82705. var tmpVec1 = new Vec3();
  82706. var tmpVec2 = new Vec3();
  82707. RotationalEquation.prototype.computeB = function(h){
  82708. var a = this.a,
  82709. b = this.b,
  82710. ni = this.axisA,
  82711. nj = this.axisB,
  82712. nixnj = tmpVec1,
  82713. njxni = tmpVec2,
  82714. GA = this.jacobianElementA,
  82715. GB = this.jacobianElementB;
  82716. // Caluclate cross products
  82717. ni.cross(nj, nixnj);
  82718. nj.cross(ni, njxni);
  82719. // g = ni * nj
  82720. // gdot = (nj x ni) * wi + (ni x nj) * wj
  82721. // G = [0 njxni 0 nixnj]
  82722. // W = [vi wi vj wj]
  82723. GA.rotational.copy(njxni);
  82724. GB.rotational.copy(nixnj);
  82725. var g = Math.cos(this.maxAngle) - ni.dot(nj),
  82726. GW = this.computeGW(),
  82727. GiMf = this.computeGiMf();
  82728. var B = - g * a - GW * b - h * GiMf;
  82729. return B;
  82730. };
  82731. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(_dereq_,module,exports){
  82732. module.exports = RotationalMotorEquation;
  82733. var Vec3 = _dereq_('../math/Vec3');
  82734. var Mat3 = _dereq_('../math/Mat3');
  82735. var Equation = _dereq_('./Equation');
  82736. /**
  82737. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  82738. * @class RotationalMotorEquation
  82739. * @constructor
  82740. * @author schteppe
  82741. * @param {Body} bodyA
  82742. * @param {Body} bodyB
  82743. * @param {Number} maxForce
  82744. * @extends Equation
  82745. */
  82746. function RotationalMotorEquation(bodyA, bodyB, maxForce){
  82747. maxForce = typeof(maxForce)!=='undefined' ? maxForce : 1e6;
  82748. Equation.call(this,bodyA,bodyB,-maxForce,maxForce);
  82749. /**
  82750. * World oriented rotational axis
  82751. * @property {Vec3} axisA
  82752. */
  82753. this.axisA = new Vec3();
  82754. /**
  82755. * World oriented rotational axis
  82756. * @property {Vec3} axisB
  82757. */
  82758. this.axisB = new Vec3(); // World oriented rotational axis
  82759. /**
  82760. * Motor velocity
  82761. * @property {Number} targetVelocity
  82762. */
  82763. this.targetVelocity = 0;
  82764. }
  82765. RotationalMotorEquation.prototype = new Equation();
  82766. RotationalMotorEquation.prototype.constructor = RotationalMotorEquation;
  82767. RotationalMotorEquation.prototype.computeB = function(h){
  82768. var a = this.a,
  82769. b = this.b,
  82770. bi = this.bi,
  82771. bj = this.bj,
  82772. axisA = this.axisA,
  82773. axisB = this.axisB,
  82774. GA = this.jacobianElementA,
  82775. GB = this.jacobianElementB;
  82776. // g = 0
  82777. // gdot = axisA * wi - axisB * wj
  82778. // gdot = G * W = G * [vi wi vj wj]
  82779. // =>
  82780. // G = [0 axisA 0 -axisB]
  82781. GA.rotational.copy(axisA);
  82782. axisB.negate(GB.rotational);
  82783. var GW = this.computeGW() - this.targetVelocity,
  82784. GiMf = this.computeGiMf();
  82785. var B = - GW * b - h * GiMf;
  82786. return B;
  82787. };
  82788. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(_dereq_,module,exports){
  82789. var Utils = _dereq_('../utils/Utils');
  82790. module.exports = ContactMaterial;
  82791. /**
  82792. * Defines what happens when two materials meet.
  82793. * @class ContactMaterial
  82794. * @constructor
  82795. * @param {Material} m1
  82796. * @param {Material} m2
  82797. * @param {object} [options]
  82798. * @param {Number} [options.friction=0.3]
  82799. * @param {Number} [options.restitution=0.3]
  82800. * @param {number} [options.contactEquationStiffness=1e7]
  82801. * @param {number} [options.contactEquationRelaxation=3]
  82802. * @param {number} [options.frictionEquationStiffness=1e7]
  82803. * @param {Number} [options.frictionEquationRelaxation=3]
  82804. */
  82805. function ContactMaterial(m1, m2, options){
  82806. options = Utils.defaults(options, {
  82807. friction: 0.3,
  82808. restitution: 0.3,
  82809. contactEquationStiffness: 1e7,
  82810. contactEquationRelaxation: 3,
  82811. frictionEquationStiffness: 1e7,
  82812. frictionEquationRelaxation: 3
  82813. });
  82814. /**
  82815. * Identifier of this material
  82816. * @property {Number} id
  82817. */
  82818. this.id = ContactMaterial.idCounter++;
  82819. /**
  82820. * Participating materials
  82821. * @property {Array} materials
  82822. * @todo Should be .materialA and .materialB instead
  82823. */
  82824. this.materials = [m1, m2];
  82825. /**
  82826. * Friction coefficient
  82827. * @property {Number} friction
  82828. */
  82829. this.friction = options.friction;
  82830. /**
  82831. * Restitution coefficient
  82832. * @property {Number} restitution
  82833. */
  82834. this.restitution = options.restitution;
  82835. /**
  82836. * Stiffness of the produced contact equations
  82837. * @property {Number} contactEquationStiffness
  82838. */
  82839. this.contactEquationStiffness = options.contactEquationStiffness;
  82840. /**
  82841. * Relaxation time of the produced contact equations
  82842. * @property {Number} contactEquationRelaxation
  82843. */
  82844. this.contactEquationRelaxation = options.contactEquationRelaxation;
  82845. /**
  82846. * Stiffness of the produced friction equations
  82847. * @property {Number} frictionEquationStiffness
  82848. */
  82849. this.frictionEquationStiffness = options.frictionEquationStiffness;
  82850. /**
  82851. * Relaxation time of the produced friction equations
  82852. * @property {Number} frictionEquationRelaxation
  82853. */
  82854. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  82855. }
  82856. ContactMaterial.idCounter = 0;
  82857. },{"../utils/Utils":53}],25:[function(_dereq_,module,exports){
  82858. module.exports = Material;
  82859. /**
  82860. * Defines a physics material.
  82861. * @class Material
  82862. * @constructor
  82863. * @param {object} [options]
  82864. * @author schteppe
  82865. */
  82866. function Material(options){
  82867. var name = '';
  82868. options = options || {};
  82869. // Backwards compatibility fix
  82870. if(typeof(options) === 'string'){
  82871. name = options;
  82872. options = {};
  82873. } else if(typeof(options) === 'object') {
  82874. name = '';
  82875. }
  82876. /**
  82877. * @property name
  82878. * @type {String}
  82879. */
  82880. this.name = name;
  82881. /**
  82882. * material id.
  82883. * @property id
  82884. * @type {number}
  82885. */
  82886. this.id = Material.idCounter++;
  82887. /**
  82888. * 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.
  82889. * @property {number} friction
  82890. */
  82891. this.friction = typeof(options.friction) !== 'undefined' ? options.friction : -1;
  82892. /**
  82893. * 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.
  82894. * @property {number} restitution
  82895. */
  82896. this.restitution = typeof(options.restitution) !== 'undefined' ? options.restitution : -1;
  82897. }
  82898. Material.idCounter = 0;
  82899. },{}],26:[function(_dereq_,module,exports){
  82900. module.exports = JacobianElement;
  82901. var Vec3 = _dereq_('./Vec3');
  82902. /**
  82903. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  82904. * @class JacobianElement
  82905. * @constructor
  82906. */
  82907. function JacobianElement(){
  82908. /**
  82909. * @property {Vec3} spatial
  82910. */
  82911. this.spatial = new Vec3();
  82912. /**
  82913. * @property {Vec3} rotational
  82914. */
  82915. this.rotational = new Vec3();
  82916. }
  82917. /**
  82918. * Multiply with other JacobianElement
  82919. * @method multiplyElement
  82920. * @param {JacobianElement} element
  82921. * @return {Number}
  82922. */
  82923. JacobianElement.prototype.multiplyElement = function(element){
  82924. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  82925. };
  82926. /**
  82927. * Multiply with two vectors
  82928. * @method multiplyVectors
  82929. * @param {Vec3} spatial
  82930. * @param {Vec3} rotational
  82931. * @return {Number}
  82932. */
  82933. JacobianElement.prototype.multiplyVectors = function(spatial,rotational){
  82934. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  82935. };
  82936. },{"./Vec3":30}],27:[function(_dereq_,module,exports){
  82937. module.exports = Mat3;
  82938. var Vec3 = _dereq_('./Vec3');
  82939. /**
  82940. * A 3x3 matrix.
  82941. * @class Mat3
  82942. * @constructor
  82943. * @param array elements Array of nine elements. Optional.
  82944. * @author schteppe / http://github.com/schteppe
  82945. */
  82946. function Mat3(elements){
  82947. /**
  82948. * A vector of length 9, containing all matrix elements
  82949. * @property {Array} elements
  82950. */
  82951. if(elements){
  82952. this.elements = elements;
  82953. } else {
  82954. this.elements = [0,0,0,0,0,0,0,0,0];
  82955. }
  82956. }
  82957. /**
  82958. * Sets the matrix to identity
  82959. * @method identity
  82960. * @todo Should perhaps be renamed to setIdentity() to be more clear.
  82961. * @todo Create another function that immediately creates an identity matrix eg. eye()
  82962. */
  82963. Mat3.prototype.identity = function(){
  82964. var e = this.elements;
  82965. e[0] = 1;
  82966. e[1] = 0;
  82967. e[2] = 0;
  82968. e[3] = 0;
  82969. e[4] = 1;
  82970. e[5] = 0;
  82971. e[6] = 0;
  82972. e[7] = 0;
  82973. e[8] = 1;
  82974. };
  82975. /**
  82976. * Set all elements to zero
  82977. * @method setZero
  82978. */
  82979. Mat3.prototype.setZero = function(){
  82980. var e = this.elements;
  82981. e[0] = 0;
  82982. e[1] = 0;
  82983. e[2] = 0;
  82984. e[3] = 0;
  82985. e[4] = 0;
  82986. e[5] = 0;
  82987. e[6] = 0;
  82988. e[7] = 0;
  82989. e[8] = 0;
  82990. };
  82991. /**
  82992. * Sets the matrix diagonal elements from a Vec3
  82993. * @method setTrace
  82994. * @param {Vec3} vec3
  82995. */
  82996. Mat3.prototype.setTrace = function(vec3){
  82997. var e = this.elements;
  82998. e[0] = vec3.x;
  82999. e[4] = vec3.y;
  83000. e[8] = vec3.z;
  83001. };
  83002. /**
  83003. * Gets the matrix diagonal elements
  83004. * @method getTrace
  83005. * @return {Vec3}
  83006. */
  83007. Mat3.prototype.getTrace = function(target){
  83008. var target = target || new Vec3();
  83009. var e = this.elements;
  83010. target.x = e[0];
  83011. target.y = e[4];
  83012. target.z = e[8];
  83013. };
  83014. /**
  83015. * Matrix-Vector multiplication
  83016. * @method vmult
  83017. * @param {Vec3} v The vector to multiply with
  83018. * @param {Vec3} target Optional, target to save the result in.
  83019. */
  83020. Mat3.prototype.vmult = function(v,target){
  83021. target = target || new Vec3();
  83022. var e = this.elements,
  83023. x = v.x,
  83024. y = v.y,
  83025. z = v.z;
  83026. target.x = e[0]*x + e[1]*y + e[2]*z;
  83027. target.y = e[3]*x + e[4]*y + e[5]*z;
  83028. target.z = e[6]*x + e[7]*y + e[8]*z;
  83029. return target;
  83030. };
  83031. /**
  83032. * Matrix-scalar multiplication
  83033. * @method smult
  83034. * @param {Number} s
  83035. */
  83036. Mat3.prototype.smult = function(s){
  83037. for(var i=0; i<this.elements.length; i++){
  83038. this.elements[i] *= s;
  83039. }
  83040. };
  83041. /**
  83042. * Matrix multiplication
  83043. * @method mmult
  83044. * @param {Mat3} m Matrix to multiply with from left side.
  83045. * @return {Mat3} The result.
  83046. */
  83047. Mat3.prototype.mmult = function(m,target){
  83048. var r = target || new Mat3();
  83049. for(var i=0; i<3; i++){
  83050. for(var j=0; j<3; j++){
  83051. var sum = 0.0;
  83052. for(var k=0; k<3; k++){
  83053. sum += m.elements[i+k*3] * this.elements[k+j*3];
  83054. }
  83055. r.elements[i+j*3] = sum;
  83056. }
  83057. }
  83058. return r;
  83059. };
  83060. /**
  83061. * Scale each column of the matrix
  83062. * @method scale
  83063. * @param {Vec3} v
  83064. * @return {Mat3} The result.
  83065. */
  83066. Mat3.prototype.scale = function(v,target){
  83067. target = target || new Mat3();
  83068. var e = this.elements,
  83069. t = target.elements;
  83070. for(var i=0; i!==3; i++){
  83071. t[3*i + 0] = v.x * e[3*i + 0];
  83072. t[3*i + 1] = v.y * e[3*i + 1];
  83073. t[3*i + 2] = v.z * e[3*i + 2];
  83074. }
  83075. return target;
  83076. };
  83077. /**
  83078. * Solve Ax=b
  83079. * @method solve
  83080. * @param {Vec3} b The right hand side
  83081. * @param {Vec3} target Optional. Target vector to save in.
  83082. * @return {Vec3} The solution x
  83083. * @todo should reuse arrays
  83084. */
  83085. Mat3.prototype.solve = function(b,target){
  83086. target = target || new Vec3();
  83087. // Construct equations
  83088. var nr = 3; // num rows
  83089. var nc = 4; // num cols
  83090. var eqns = [];
  83091. for(var i=0; i<nr*nc; i++){
  83092. eqns.push(0);
  83093. }
  83094. var i,j;
  83095. for(i=0; i<3; i++){
  83096. for(j=0; j<3; j++){
  83097. eqns[i+nc*j] = this.elements[i+3*j];
  83098. }
  83099. }
  83100. eqns[3+4*0] = b.x;
  83101. eqns[3+4*1] = b.y;
  83102. eqns[3+4*2] = b.z;
  83103. // Compute right upper triangular version of the matrix - Gauss elimination
  83104. var n = 3, k = n, np;
  83105. var kp = 4; // num rows
  83106. var p, els;
  83107. do {
  83108. i = k - n;
  83109. if (eqns[i+nc*i] === 0) {
  83110. // the pivot is null, swap lines
  83111. for (j = i + 1; j < k; j++) {
  83112. if (eqns[i+nc*j] !== 0) {
  83113. np = kp;
  83114. do { // do ligne( i ) = ligne( i ) + ligne( k )
  83115. p = kp - np;
  83116. eqns[p+nc*i] += eqns[p+nc*j];
  83117. } while (--np);
  83118. break;
  83119. }
  83120. }
  83121. }
  83122. if (eqns[i+nc*i] !== 0) {
  83123. for (j = i + 1; j < k; j++) {
  83124. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  83125. np = kp;
  83126. do { // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  83127. p = kp - np;
  83128. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  83129. } while (--np);
  83130. }
  83131. }
  83132. } while (--n);
  83133. // Get the solution
  83134. target.z = eqns[2*nc+3] / eqns[2*nc+2];
  83135. target.y = (eqns[1*nc+3] - eqns[1*nc+2]*target.z) / eqns[1*nc+1];
  83136. target.x = (eqns[0*nc+3] - eqns[0*nc+2]*target.z - eqns[0*nc+1]*target.y) / eqns[0*nc+0];
  83137. if(isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x===Infinity || target.y===Infinity || target.z===Infinity){
  83138. throw "Could not solve equation! Got x=["+target.toString()+"], b=["+b.toString()+"], A=["+this.toString()+"]";
  83139. }
  83140. return target;
  83141. };
  83142. /**
  83143. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  83144. * @method e
  83145. * @param {Number} row
  83146. * @param {Number} column
  83147. * @param {Number} value Optional. If provided, the matrix element will be set to this value.
  83148. * @return {Number}
  83149. */
  83150. Mat3.prototype.e = function( row , column ,value){
  83151. if(value===undefined){
  83152. return this.elements[column+3*row];
  83153. } else {
  83154. // Set value
  83155. this.elements[column+3*row] = value;
  83156. }
  83157. };
  83158. /**
  83159. * Copy another matrix into this matrix object.
  83160. * @method copy
  83161. * @param {Mat3} source
  83162. * @return {Mat3} this
  83163. */
  83164. Mat3.prototype.copy = function(source){
  83165. for(var i=0; i < source.elements.length; i++){
  83166. this.elements[i] = source.elements[i];
  83167. }
  83168. return this;
  83169. };
  83170. /**
  83171. * Returns a string representation of the matrix.
  83172. * @method toString
  83173. * @return string
  83174. */
  83175. Mat3.prototype.toString = function(){
  83176. var r = "";
  83177. var sep = ",";
  83178. for(var i=0; i<9; i++){
  83179. r += this.elements[i] + sep;
  83180. }
  83181. return r;
  83182. };
  83183. /**
  83184. * reverse the matrix
  83185. * @method reverse
  83186. * @param {Mat3} target Optional. Target matrix to save in.
  83187. * @return {Mat3} The solution x
  83188. */
  83189. Mat3.prototype.reverse = function(target){
  83190. target = target || new Mat3();
  83191. // Construct equations
  83192. var nr = 3; // num rows
  83193. var nc = 6; // num cols
  83194. var eqns = [];
  83195. for(var i=0; i<nr*nc; i++){
  83196. eqns.push(0);
  83197. }
  83198. var i,j;
  83199. for(i=0; i<3; i++){
  83200. for(j=0; j<3; j++){
  83201. eqns[i+nc*j] = this.elements[i+3*j];
  83202. }
  83203. }
  83204. eqns[3+6*0] = 1;
  83205. eqns[3+6*1] = 0;
  83206. eqns[3+6*2] = 0;
  83207. eqns[4+6*0] = 0;
  83208. eqns[4+6*1] = 1;
  83209. eqns[4+6*2] = 0;
  83210. eqns[5+6*0] = 0;
  83211. eqns[5+6*1] = 0;
  83212. eqns[5+6*2] = 1;
  83213. // Compute right upper triangular version of the matrix - Gauss elimination
  83214. var n = 3, k = n, np;
  83215. var kp = nc; // num rows
  83216. var p;
  83217. do {
  83218. i = k - n;
  83219. if (eqns[i+nc*i] === 0) {
  83220. // the pivot is null, swap lines
  83221. for (j = i + 1; j < k; j++) {
  83222. if (eqns[i+nc*j] !== 0) {
  83223. np = kp;
  83224. do { // do line( i ) = line( i ) + line( k )
  83225. p = kp - np;
  83226. eqns[p+nc*i] += eqns[p+nc*j];
  83227. } while (--np);
  83228. break;
  83229. }
  83230. }
  83231. }
  83232. if (eqns[i+nc*i] !== 0) {
  83233. for (j = i + 1; j < k; j++) {
  83234. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  83235. np = kp;
  83236. do { // do line( k ) = line( k ) - multiplier * line( i )
  83237. p = kp - np;
  83238. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  83239. } while (--np);
  83240. }
  83241. }
  83242. } while (--n);
  83243. // eliminate the upper left triangle of the matrix
  83244. i = 2;
  83245. do {
  83246. j = i-1;
  83247. do {
  83248. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  83249. np = nc;
  83250. do {
  83251. p = nc - np;
  83252. eqns[p+nc*j] = eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  83253. } while (--np);
  83254. } while (j--);
  83255. } while (--i);
  83256. // operations on the diagonal
  83257. i = 2;
  83258. do {
  83259. var multiplier = 1 / eqns[i+nc*i];
  83260. np = nc;
  83261. do {
  83262. p = nc - np;
  83263. eqns[p+nc*i] = eqns[p+nc*i] * multiplier ;
  83264. } while (--np);
  83265. } while (i--);
  83266. i = 2;
  83267. do {
  83268. j = 2;
  83269. do {
  83270. p = eqns[nr+j+nc*i];
  83271. if( isNaN( p ) || p ===Infinity ){
  83272. throw "Could not reverse! A=["+this.toString()+"]";
  83273. }
  83274. target.e( i , j , p );
  83275. } while (j--);
  83276. } while (i--);
  83277. return target;
  83278. };
  83279. /**
  83280. * Set the matrix from a quaterion
  83281. * @method setRotationFromQuaternion
  83282. * @param {Quaternion} q
  83283. */
  83284. Mat3.prototype.setRotationFromQuaternion = function( q ) {
  83285. var x = q.x, y = q.y, z = q.z, w = q.w,
  83286. x2 = x + x, y2 = y + y, z2 = z + z,
  83287. xx = x * x2, xy = x * y2, xz = x * z2,
  83288. yy = y * y2, yz = y * z2, zz = z * z2,
  83289. wx = w * x2, wy = w * y2, wz = w * z2,
  83290. e = this.elements;
  83291. e[3*0 + 0] = 1 - ( yy + zz );
  83292. e[3*0 + 1] = xy - wz;
  83293. e[3*0 + 2] = xz + wy;
  83294. e[3*1 + 0] = xy + wz;
  83295. e[3*1 + 1] = 1 - ( xx + zz );
  83296. e[3*1 + 2] = yz - wx;
  83297. e[3*2 + 0] = xz - wy;
  83298. e[3*2 + 1] = yz + wx;
  83299. e[3*2 + 2] = 1 - ( xx + yy );
  83300. return this;
  83301. };
  83302. /**
  83303. * Transpose the matrix
  83304. * @method transpose
  83305. * @param {Mat3} target Where to store the result.
  83306. * @return {Mat3} The target Mat3, or a new Mat3 if target was omitted.
  83307. */
  83308. Mat3.prototype.transpose = function( target ) {
  83309. target = target || new Mat3();
  83310. var Mt = target.elements,
  83311. M = this.elements;
  83312. for(var i=0; i!==3; i++){
  83313. for(var j=0; j!==3; j++){
  83314. Mt[3*i + j] = M[3*j + i];
  83315. }
  83316. }
  83317. return target;
  83318. };
  83319. },{"./Vec3":30}],28:[function(_dereq_,module,exports){
  83320. module.exports = Quaternion;
  83321. var Vec3 = _dereq_('./Vec3');
  83322. /**
  83323. * 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.
  83324. * @class Quaternion
  83325. * @constructor
  83326. * @param {Number} x Multiplier of the imaginary basis vector i.
  83327. * @param {Number} y Multiplier of the imaginary basis vector j.
  83328. * @param {Number} z Multiplier of the imaginary basis vector k.
  83329. * @param {Number} w Multiplier of the real part.
  83330. * @see http://en.wikipedia.org/wiki/Quaternion
  83331. */
  83332. function Quaternion(x,y,z,w){
  83333. /**
  83334. * @property {Number} x
  83335. */
  83336. this.x = x!==undefined ? x : 0;
  83337. /**
  83338. * @property {Number} y
  83339. */
  83340. this.y = y!==undefined ? y : 0;
  83341. /**
  83342. * @property {Number} z
  83343. */
  83344. this.z = z!==undefined ? z : 0;
  83345. /**
  83346. * The multiplier of the real quaternion basis vector.
  83347. * @property {Number} w
  83348. */
  83349. this.w = w!==undefined ? w : 1;
  83350. }
  83351. /**
  83352. * Set the value of the quaternion.
  83353. * @method set
  83354. * @param {Number} x
  83355. * @param {Number} y
  83356. * @param {Number} z
  83357. * @param {Number} w
  83358. */
  83359. Quaternion.prototype.set = function(x,y,z,w){
  83360. this.x = x;
  83361. this.y = y;
  83362. this.z = z;
  83363. this.w = w;
  83364. };
  83365. /**
  83366. * Convert to a readable format
  83367. * @method toString
  83368. * @return string
  83369. */
  83370. Quaternion.prototype.toString = function(){
  83371. return this.x+","+this.y+","+this.z+","+this.w;
  83372. };
  83373. /**
  83374. * Convert to an Array
  83375. * @method toArray
  83376. * @return Array
  83377. */
  83378. Quaternion.prototype.toArray = function(){
  83379. return [this.x, this.y, this.z, this.w];
  83380. };
  83381. /**
  83382. * Set the quaternion components given an axis and an angle.
  83383. * @method setFromAxisAngle
  83384. * @param {Vec3} axis
  83385. * @param {Number} angle in radians
  83386. */
  83387. Quaternion.prototype.setFromAxisAngle = function(axis,angle){
  83388. var s = Math.sin(angle*0.5);
  83389. this.x = axis.x * s;
  83390. this.y = axis.y * s;
  83391. this.z = axis.z * s;
  83392. this.w = Math.cos(angle*0.5);
  83393. };
  83394. /**
  83395. * Converts the quaternion to axis/angle representation.
  83396. * @method toAxisAngle
  83397. * @param {Vec3} targetAxis Optional. A vector object to reuse for storing the axis.
  83398. * @return Array An array, first elemnt is the axis and the second is the angle in radians.
  83399. */
  83400. Quaternion.prototype.toAxisAngle = function(targetAxis){
  83401. targetAxis = targetAxis || new Vec3();
  83402. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  83403. var angle = 2 * Math.acos(this.w);
  83404. var s = Math.sqrt(1-this.w*this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  83405. if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt
  83406. // if s close to zero then direction of axis not important
  83407. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  83408. targetAxis.y = this.y;
  83409. targetAxis.z = this.z;
  83410. } else {
  83411. targetAxis.x = this.x / s; // normalise axis
  83412. targetAxis.y = this.y / s;
  83413. targetAxis.z = this.z / s;
  83414. }
  83415. return [targetAxis,angle];
  83416. };
  83417. var sfv_t1 = new Vec3(),
  83418. sfv_t2 = new Vec3();
  83419. /**
  83420. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  83421. * @method setFromVectors
  83422. * @param {Vec3} u
  83423. * @param {Vec3} v
  83424. */
  83425. Quaternion.prototype.setFromVectors = function(u,v){
  83426. if(u.isAntiparallelTo(v)){
  83427. var t1 = sfv_t1;
  83428. var t2 = sfv_t2;
  83429. u.tangents(t1,t2);
  83430. this.setFromAxisAngle(t1,Math.PI);
  83431. } else {
  83432. var a = u.cross(v);
  83433. this.x = a.x;
  83434. this.y = a.y;
  83435. this.z = a.z;
  83436. this.w = Math.sqrt(Math.pow(u.norm(),2) * Math.pow(v.norm(),2)) + u.dot(v);
  83437. this.normalize();
  83438. }
  83439. };
  83440. /**
  83441. * Quaternion multiplication
  83442. * @method mult
  83443. * @param {Quaternion} q
  83444. * @param {Quaternion} target Optional.
  83445. * @return {Quaternion}
  83446. */
  83447. var Quaternion_mult_va = new Vec3();
  83448. var Quaternion_mult_vb = new Vec3();
  83449. var Quaternion_mult_vaxvb = new Vec3();
  83450. Quaternion.prototype.mult = function(q,target){
  83451. target = target || new Quaternion();
  83452. var w = this.w,
  83453. va = Quaternion_mult_va,
  83454. vb = Quaternion_mult_vb,
  83455. vaxvb = Quaternion_mult_vaxvb;
  83456. va.set(this.x,this.y,this.z);
  83457. vb.set(q.x,q.y,q.z);
  83458. target.w = w*q.w - va.dot(vb);
  83459. va.cross(vb,vaxvb);
  83460. target.x = w * vb.x + q.w*va.x + vaxvb.x;
  83461. target.y = w * vb.y + q.w*va.y + vaxvb.y;
  83462. target.z = w * vb.z + q.w*va.z + vaxvb.z;
  83463. return target;
  83464. };
  83465. /**
  83466. * Get the inverse quaternion rotation.
  83467. * @method inverse
  83468. * @param {Quaternion} target
  83469. * @return {Quaternion}
  83470. */
  83471. Quaternion.prototype.inverse = function(target){
  83472. var x = this.x, y = this.y, z = this.z, w = this.w;
  83473. target = target || new Quaternion();
  83474. this.conjugate(target);
  83475. var inorm2 = 1/(x*x + y*y + z*z + w*w);
  83476. target.x *= inorm2;
  83477. target.y *= inorm2;
  83478. target.z *= inorm2;
  83479. target.w *= inorm2;
  83480. return target;
  83481. };
  83482. /**
  83483. * Get the quaternion conjugate
  83484. * @method conjugate
  83485. * @param {Quaternion} target
  83486. * @return {Quaternion}
  83487. */
  83488. Quaternion.prototype.conjugate = function(target){
  83489. target = target || new Quaternion();
  83490. target.x = -this.x;
  83491. target.y = -this.y;
  83492. target.z = -this.z;
  83493. target.w = this.w;
  83494. return target;
  83495. };
  83496. /**
  83497. * Normalize the quaternion. Note that this changes the values of the quaternion.
  83498. * @method normalize
  83499. */
  83500. Quaternion.prototype.normalize = function(){
  83501. var l = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);
  83502. if ( l === 0 ) {
  83503. this.x = 0;
  83504. this.y = 0;
  83505. this.z = 0;
  83506. this.w = 0;
  83507. } else {
  83508. l = 1 / l;
  83509. this.x *= l;
  83510. this.y *= l;
  83511. this.z *= l;
  83512. this.w *= l;
  83513. }
  83514. };
  83515. /**
  83516. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  83517. * @method normalizeFast
  83518. * @see http://jsperf.com/fast-quaternion-normalization
  83519. * @author unphased, https://github.com/unphased
  83520. */
  83521. Quaternion.prototype.normalizeFast = function () {
  83522. var f = (3.0-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2.0;
  83523. if ( f === 0 ) {
  83524. this.x = 0;
  83525. this.y = 0;
  83526. this.z = 0;
  83527. this.w = 0;
  83528. } else {
  83529. this.x *= f;
  83530. this.y *= f;
  83531. this.z *= f;
  83532. this.w *= f;
  83533. }
  83534. };
  83535. /**
  83536. * Multiply the quaternion by a vector
  83537. * @method vmult
  83538. * @param {Vec3} v
  83539. * @param {Vec3} target Optional
  83540. * @return {Vec3}
  83541. */
  83542. Quaternion.prototype.vmult = function(v,target){
  83543. target = target || new Vec3();
  83544. var x = v.x,
  83545. y = v.y,
  83546. z = v.z;
  83547. var qx = this.x,
  83548. qy = this.y,
  83549. qz = this.z,
  83550. qw = this.w;
  83551. // q*v
  83552. var ix = qw * x + qy * z - qz * y,
  83553. iy = qw * y + qz * x - qx * z,
  83554. iz = qw * z + qx * y - qy * x,
  83555. iw = -qx * x - qy * y - qz * z;
  83556. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  83557. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  83558. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  83559. return target;
  83560. };
  83561. /**
  83562. * Copies value of source to this quaternion.
  83563. * @method copy
  83564. * @param {Quaternion} source
  83565. * @return {Quaternion} this
  83566. */
  83567. Quaternion.prototype.copy = function(source){
  83568. this.x = source.x;
  83569. this.y = source.y;
  83570. this.z = source.z;
  83571. this.w = source.w;
  83572. return this;
  83573. };
  83574. /**
  83575. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: http://www.euclideanspace.com/maths/standards/index.htm
  83576. * @method toEuler
  83577. * @param {Vec3} target
  83578. * @param string order Three-character string e.g. "YZX", which also is default.
  83579. */
  83580. Quaternion.prototype.toEuler = function(target,order){
  83581. order = order || "YZX";
  83582. var heading, attitude, bank;
  83583. var x = this.x, y = this.y, z = this.z, w = this.w;
  83584. switch(order){
  83585. case "YZX":
  83586. var test = x*y + z*w;
  83587. if (test > 0.499) { // singularity at north pole
  83588. heading = 2 * Math.atan2(x,w);
  83589. attitude = Math.PI/2;
  83590. bank = 0;
  83591. }
  83592. if (test < -0.499) { // singularity at south pole
  83593. heading = -2 * Math.atan2(x,w);
  83594. attitude = - Math.PI/2;
  83595. bank = 0;
  83596. }
  83597. if(isNaN(heading)){
  83598. var sqx = x*x;
  83599. var sqy = y*y;
  83600. var sqz = z*z;
  83601. heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // Heading
  83602. attitude = Math.asin(2*test); // attitude
  83603. bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank
  83604. }
  83605. break;
  83606. default:
  83607. throw new Error("Euler order "+order+" not supported yet.");
  83608. }
  83609. target.y = heading;
  83610. target.z = attitude;
  83611. target.x = bank;
  83612. };
  83613. /**
  83614. * See http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  83615. * @method setFromEuler
  83616. * @param {Number} x
  83617. * @param {Number} y
  83618. * @param {Number} z
  83619. * @param {String} order The order to apply angles: 'XYZ' or 'YXZ' or any other combination
  83620. */
  83621. Quaternion.prototype.setFromEuler = function ( x, y, z, order ) {
  83622. order = order || "XYZ";
  83623. var c1 = Math.cos( x / 2 );
  83624. var c2 = Math.cos( y / 2 );
  83625. var c3 = Math.cos( z / 2 );
  83626. var s1 = Math.sin( x / 2 );
  83627. var s2 = Math.sin( y / 2 );
  83628. var s3 = Math.sin( z / 2 );
  83629. if ( order === 'XYZ' ) {
  83630. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  83631. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  83632. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  83633. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  83634. } else if ( order === 'YXZ' ) {
  83635. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  83636. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  83637. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  83638. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  83639. } else if ( order === 'ZXY' ) {
  83640. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  83641. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  83642. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  83643. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  83644. } else if ( order === 'ZYX' ) {
  83645. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  83646. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  83647. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  83648. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  83649. } else if ( order === 'YZX' ) {
  83650. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  83651. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  83652. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  83653. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  83654. } else if ( order === 'XZY' ) {
  83655. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  83656. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  83657. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  83658. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  83659. }
  83660. return this;
  83661. };
  83662. Quaternion.prototype.clone = function(){
  83663. return new Quaternion(this.x, this.y, this.z, this.w);
  83664. };
  83665. },{"./Vec3":30}],29:[function(_dereq_,module,exports){
  83666. var Vec3 = _dereq_('./Vec3');
  83667. var Quaternion = _dereq_('./Quaternion');
  83668. module.exports = Transform;
  83669. /**
  83670. * @class Transform
  83671. * @constructor
  83672. */
  83673. function Transform(options) {
  83674. options = options || {};
  83675. /**
  83676. * @property {Vec3} position
  83677. */
  83678. this.position = new Vec3();
  83679. if(options.position){
  83680. this.position.copy(options.position);
  83681. }
  83682. /**
  83683. * @property {Quaternion} quaternion
  83684. */
  83685. this.quaternion = new Quaternion();
  83686. if(options.quaternion){
  83687. this.quaternion.copy(options.quaternion);
  83688. }
  83689. }
  83690. var tmpQuat = new Quaternion();
  83691. /**
  83692. * @static
  83693. * @method pointToLocaFrame
  83694. * @param {Vec3} position
  83695. * @param {Quaternion} quaternion
  83696. * @param {Vec3} worldPoint
  83697. * @param {Vec3} result
  83698. */
  83699. Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
  83700. var result = result || new Vec3();
  83701. worldPoint.vsub(position, result);
  83702. quaternion.conjugate(tmpQuat);
  83703. tmpQuat.vmult(result, result);
  83704. return result;
  83705. };
  83706. /**
  83707. * Get a global point in local transform coordinates.
  83708. * @method pointToLocal
  83709. * @param {Vec3} point
  83710. * @param {Vec3} result
  83711. * @return {Vec3} The "result" vector object
  83712. */
  83713. Transform.prototype.pointToLocal = function(worldPoint, result){
  83714. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  83715. };
  83716. /**
  83717. * @static
  83718. * @method pointToWorldFrame
  83719. * @param {Vec3} position
  83720. * @param {Vec3} quaternion
  83721. * @param {Vec3} localPoint
  83722. * @param {Vec3} result
  83723. */
  83724. Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
  83725. var result = result || new Vec3();
  83726. quaternion.vmult(localPoint, result);
  83727. result.vadd(position, result);
  83728. return result;
  83729. };
  83730. /**
  83731. * Get a local point in global transform coordinates.
  83732. * @method pointToWorld
  83733. * @param {Vec3} point
  83734. * @param {Vec3} result
  83735. * @return {Vec3} The "result" vector object
  83736. */
  83737. Transform.prototype.pointToWorld = function(localPoint, result){
  83738. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  83739. };
  83740. Transform.prototype.vectorToWorldFrame = function(localVector, result){
  83741. var result = result || new Vec3();
  83742. this.quaternion.vmult(localVector, result);
  83743. return result;
  83744. };
  83745. Transform.vectorToWorldFrame = function(quaternion, localVector, result){
  83746. quaternion.vmult(localVector, result);
  83747. return result;
  83748. };
  83749. Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
  83750. var result = result || new Vec3();
  83751. quaternion.w *= -1;
  83752. quaternion.vmult(worldVector, result);
  83753. quaternion.w *= -1;
  83754. return result;
  83755. };
  83756. },{"./Quaternion":28,"./Vec3":30}],30:[function(_dereq_,module,exports){
  83757. module.exports = Vec3;
  83758. var Mat3 = _dereq_('./Mat3');
  83759. /**
  83760. * 3-dimensional vector
  83761. * @class Vec3
  83762. * @constructor
  83763. * @param {Number} x
  83764. * @param {Number} y
  83765. * @param {Number} z
  83766. * @author schteppe
  83767. * @example
  83768. * var v = new Vec3(1, 2, 3);
  83769. * console.log('x=' + v.x); // x=1
  83770. */
  83771. function Vec3(x,y,z){
  83772. /**
  83773. * @property x
  83774. * @type {Number}
  83775. */
  83776. this.x = x||0.0;
  83777. /**
  83778. * @property y
  83779. * @type {Number}
  83780. */
  83781. this.y = y||0.0;
  83782. /**
  83783. * @property z
  83784. * @type {Number}
  83785. */
  83786. this.z = z||0.0;
  83787. }
  83788. /**
  83789. * @static
  83790. * @property {Vec3} ZERO
  83791. */
  83792. Vec3.ZERO = new Vec3(0, 0, 0);
  83793. /**
  83794. * @static
  83795. * @property {Vec3} UNIT_X
  83796. */
  83797. Vec3.UNIT_X = new Vec3(1, 0, 0);
  83798. /**
  83799. * @static
  83800. * @property {Vec3} UNIT_Y
  83801. */
  83802. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  83803. /**
  83804. * @static
  83805. * @property {Vec3} UNIT_Z
  83806. */
  83807. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  83808. /**
  83809. * Vector cross product
  83810. * @method cross
  83811. * @param {Vec3} v
  83812. * @param {Vec3} target Optional. Target to save in.
  83813. * @return {Vec3}
  83814. */
  83815. Vec3.prototype.cross = function(v,target){
  83816. var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z;
  83817. target = target || new Vec3();
  83818. target.x = (y * vz) - (z * vy);
  83819. target.y = (z * vx) - (x * vz);
  83820. target.z = (x * vy) - (y * vx);
  83821. return target;
  83822. };
  83823. /**
  83824. * Set the vectors' 3 elements
  83825. * @method set
  83826. * @param {Number} x
  83827. * @param {Number} y
  83828. * @param {Number} z
  83829. * @return Vec3
  83830. */
  83831. Vec3.prototype.set = function(x,y,z){
  83832. this.x = x;
  83833. this.y = y;
  83834. this.z = z;
  83835. return this;
  83836. };
  83837. /**
  83838. * Set all components of the vector to zero.
  83839. * @method setZero
  83840. */
  83841. Vec3.prototype.setZero = function(){
  83842. this.x = this.y = this.z = 0;
  83843. };
  83844. /**
  83845. * Vector addition
  83846. * @method vadd
  83847. * @param {Vec3} v
  83848. * @param {Vec3} target Optional.
  83849. * @return {Vec3}
  83850. */
  83851. Vec3.prototype.vadd = function(v,target){
  83852. if(target){
  83853. target.x = v.x + this.x;
  83854. target.y = v.y + this.y;
  83855. target.z = v.z + this.z;
  83856. } else {
  83857. return new Vec3(this.x + v.x,
  83858. this.y + v.y,
  83859. this.z + v.z);
  83860. }
  83861. };
  83862. /**
  83863. * Vector subtraction
  83864. * @method vsub
  83865. * @param {Vec3} v
  83866. * @param {Vec3} target Optional. Target to save in.
  83867. * @return {Vec3}
  83868. */
  83869. Vec3.prototype.vsub = function(v,target){
  83870. if(target){
  83871. target.x = this.x - v.x;
  83872. target.y = this.y - v.y;
  83873. target.z = this.z - v.z;
  83874. } else {
  83875. return new Vec3(this.x-v.x,
  83876. this.y-v.y,
  83877. this.z-v.z);
  83878. }
  83879. };
  83880. /**
  83881. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  83882. * @method crossmat
  83883. * @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf
  83884. * @return {Mat3}
  83885. */
  83886. Vec3.prototype.crossmat = function(){
  83887. return new Mat3([ 0, -this.z, this.y,
  83888. this.z, 0, -this.x,
  83889. -this.y, this.x, 0]);
  83890. };
  83891. /**
  83892. * Normalize the vector. Note that this changes the values in the vector.
  83893. * @method normalize
  83894. * @return {Number} Returns the norm of the vector
  83895. */
  83896. Vec3.prototype.normalize = function(){
  83897. var x=this.x, y=this.y, z=this.z;
  83898. var n = Math.sqrt(x*x + y*y + z*z);
  83899. if(n>0.0){
  83900. var invN = 1/n;
  83901. this.x *= invN;
  83902. this.y *= invN;
  83903. this.z *= invN;
  83904. } else {
  83905. // Make something up
  83906. this.x = 0;
  83907. this.y = 0;
  83908. this.z = 0;
  83909. }
  83910. return n;
  83911. };
  83912. /**
  83913. * Get the version of this vector that is of length 1.
  83914. * @method unit
  83915. * @param {Vec3} target Optional target to save in
  83916. * @return {Vec3} Returns the unit vector
  83917. */
  83918. Vec3.prototype.unit = function(target){
  83919. target = target || new Vec3();
  83920. var x=this.x, y=this.y, z=this.z;
  83921. var ninv = Math.sqrt(x*x + y*y + z*z);
  83922. if(ninv>0.0){
  83923. ninv = 1.0/ninv;
  83924. target.x = x * ninv;
  83925. target.y = y * ninv;
  83926. target.z = z * ninv;
  83927. } else {
  83928. target.x = 1;
  83929. target.y = 0;
  83930. target.z = 0;
  83931. }
  83932. return target;
  83933. };
  83934. /**
  83935. * Get the length of the vector
  83936. * @method norm
  83937. * @return {Number}
  83938. * @deprecated Use .length() instead
  83939. */
  83940. Vec3.prototype.norm = function(){
  83941. var x=this.x, y=this.y, z=this.z;
  83942. return Math.sqrt(x*x + y*y + z*z);
  83943. };
  83944. /**
  83945. * Get the length of the vector
  83946. * @method length
  83947. * @return {Number}
  83948. */
  83949. Vec3.prototype.length = Vec3.prototype.norm;
  83950. /**
  83951. * Get the squared length of the vector
  83952. * @method norm2
  83953. * @return {Number}
  83954. * @deprecated Use .lengthSquared() instead.
  83955. */
  83956. Vec3.prototype.norm2 = function(){
  83957. return this.dot(this);
  83958. };
  83959. /**
  83960. * Get the squared length of the vector.
  83961. * @method lengthSquared
  83962. * @return {Number}
  83963. */
  83964. Vec3.prototype.lengthSquared = Vec3.prototype.norm2;
  83965. /**
  83966. * Get distance from this point to another point
  83967. * @method distanceTo
  83968. * @param {Vec3} p
  83969. * @return {Number}
  83970. */
  83971. Vec3.prototype.distanceTo = function(p){
  83972. var x=this.x, y=this.y, z=this.z;
  83973. var px=p.x, py=p.y, pz=p.z;
  83974. return Math.sqrt((px-x)*(px-x)+
  83975. (py-y)*(py-y)+
  83976. (pz-z)*(pz-z));
  83977. };
  83978. /**
  83979. * Get squared distance from this point to another point
  83980. * @method distanceSquared
  83981. * @param {Vec3} p
  83982. * @return {Number}
  83983. */
  83984. Vec3.prototype.distanceSquared = function(p){
  83985. var x=this.x, y=this.y, z=this.z;
  83986. var px=p.x, py=p.y, pz=p.z;
  83987. return (px-x)*(px-x) + (py-y)*(py-y) + (pz-z)*(pz-z);
  83988. };
  83989. /**
  83990. * Multiply all the components of the vector with a scalar.
  83991. * @deprecated Use .scale instead
  83992. * @method mult
  83993. * @param {Number} scalar
  83994. * @param {Vec3} target The vector to save the result in.
  83995. * @return {Vec3}
  83996. * @deprecated Use .scale() instead
  83997. */
  83998. Vec3.prototype.mult = function(scalar,target){
  83999. target = target || new Vec3();
  84000. var x = this.x,
  84001. y = this.y,
  84002. z = this.z;
  84003. target.x = scalar * x;
  84004. target.y = scalar * y;
  84005. target.z = scalar * z;
  84006. return target;
  84007. };
  84008. /**
  84009. * Multiply the vector with a scalar.
  84010. * @method scale
  84011. * @param {Number} scalar
  84012. * @param {Vec3} target
  84013. * @return {Vec3}
  84014. */
  84015. Vec3.prototype.scale = Vec3.prototype.mult;
  84016. /**
  84017. * Calculate dot product
  84018. * @method dot
  84019. * @param {Vec3} v
  84020. * @return {Number}
  84021. */
  84022. Vec3.prototype.dot = function(v){
  84023. return this.x * v.x + this.y * v.y + this.z * v.z;
  84024. };
  84025. /**
  84026. * @method isZero
  84027. * @return bool
  84028. */
  84029. Vec3.prototype.isZero = function(){
  84030. return this.x===0 && this.y===0 && this.z===0;
  84031. };
  84032. /**
  84033. * Make the vector point in the opposite direction.
  84034. * @method negate
  84035. * @param {Vec3} target Optional target to save in
  84036. * @return {Vec3}
  84037. */
  84038. Vec3.prototype.negate = function(target){
  84039. target = target || new Vec3();
  84040. target.x = -this.x;
  84041. target.y = -this.y;
  84042. target.z = -this.z;
  84043. return target;
  84044. };
  84045. /**
  84046. * Compute two artificial tangents to the vector
  84047. * @method tangents
  84048. * @param {Vec3} t1 Vector object to save the first tangent in
  84049. * @param {Vec3} t2 Vector object to save the second tangent in
  84050. */
  84051. var Vec3_tangents_n = new Vec3();
  84052. var Vec3_tangents_randVec = new Vec3();
  84053. Vec3.prototype.tangents = function(t1,t2){
  84054. var norm = this.norm();
  84055. if(norm>0.0){
  84056. var n = Vec3_tangents_n;
  84057. var inorm = 1/norm;
  84058. n.set(this.x*inorm,this.y*inorm,this.z*inorm);
  84059. var randVec = Vec3_tangents_randVec;
  84060. if(Math.abs(n.x) < 0.9){
  84061. randVec.set(1,0,0);
  84062. n.cross(randVec,t1);
  84063. } else {
  84064. randVec.set(0,1,0);
  84065. n.cross(randVec,t1);
  84066. }
  84067. n.cross(t1,t2);
  84068. } else {
  84069. // The normal length is zero, make something up
  84070. t1.set(1, 0, 0);
  84071. t2.set(0, 1, 0);
  84072. }
  84073. };
  84074. /**
  84075. * Converts to a more readable format
  84076. * @method toString
  84077. * @return string
  84078. */
  84079. Vec3.prototype.toString = function(){
  84080. return this.x+","+this.y+","+this.z;
  84081. };
  84082. /**
  84083. * Converts to an array
  84084. * @method toArray
  84085. * @return Array
  84086. */
  84087. Vec3.prototype.toArray = function(){
  84088. return [this.x, this.y, this.z];
  84089. };
  84090. /**
  84091. * Copies value of source to this vector.
  84092. * @method copy
  84093. * @param {Vec3} source
  84094. * @return {Vec3} this
  84095. */
  84096. Vec3.prototype.copy = function(source){
  84097. this.x = source.x;
  84098. this.y = source.y;
  84099. this.z = source.z;
  84100. return this;
  84101. };
  84102. /**
  84103. * Do a linear interpolation between two vectors
  84104. * @method lerp
  84105. * @param {Vec3} v
  84106. * @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.
  84107. * @param {Vec3} target
  84108. */
  84109. Vec3.prototype.lerp = function(v,t,target){
  84110. var x=this.x, y=this.y, z=this.z;
  84111. target.x = x + (v.x-x)*t;
  84112. target.y = y + (v.y-y)*t;
  84113. target.z = z + (v.z-z)*t;
  84114. };
  84115. /**
  84116. * Check if a vector equals is almost equal to another one.
  84117. * @method almostEquals
  84118. * @param {Vec3} v
  84119. * @param {Number} precision
  84120. * @return bool
  84121. */
  84122. Vec3.prototype.almostEquals = function(v,precision){
  84123. if(precision===undefined){
  84124. precision = 1e-6;
  84125. }
  84126. if( Math.abs(this.x-v.x)>precision ||
  84127. Math.abs(this.y-v.y)>precision ||
  84128. Math.abs(this.z-v.z)>precision){
  84129. return false;
  84130. }
  84131. return true;
  84132. };
  84133. /**
  84134. * Check if a vector is almost zero
  84135. * @method almostZero
  84136. * @param {Number} precision
  84137. */
  84138. Vec3.prototype.almostZero = function(precision){
  84139. if(precision===undefined){
  84140. precision = 1e-6;
  84141. }
  84142. if( Math.abs(this.x)>precision ||
  84143. Math.abs(this.y)>precision ||
  84144. Math.abs(this.z)>precision){
  84145. return false;
  84146. }
  84147. return true;
  84148. };
  84149. var antip_neg = new Vec3();
  84150. /**
  84151. * Check if the vector is anti-parallel to another vector.
  84152. * @method isAntiparallelTo
  84153. * @param {Vec3} v
  84154. * @param {Number} precision Set to zero for exact comparisons
  84155. * @return {Boolean}
  84156. */
  84157. Vec3.prototype.isAntiparallelTo = function(v,precision){
  84158. this.negate(antip_neg);
  84159. return antip_neg.almostEquals(v,precision);
  84160. };
  84161. /**
  84162. * Clone the vector
  84163. * @method clone
  84164. * @return {Vec3}
  84165. */
  84166. Vec3.prototype.clone = function(){
  84167. return new Vec3(this.x, this.y, this.z);
  84168. };
  84169. },{"./Mat3":27}],31:[function(_dereq_,module,exports){
  84170. module.exports = Body;
  84171. var EventTarget = _dereq_('../utils/EventTarget');
  84172. var Shape = _dereq_('../shapes/Shape');
  84173. var Vec3 = _dereq_('../math/Vec3');
  84174. var Mat3 = _dereq_('../math/Mat3');
  84175. var Quaternion = _dereq_('../math/Quaternion');
  84176. var Material = _dereq_('../material/Material');
  84177. var AABB = _dereq_('../collision/AABB');
  84178. var Box = _dereq_('../shapes/Box');
  84179. /**
  84180. * Base class for all body types.
  84181. * @class Body
  84182. * @constructor
  84183. * @extends EventTarget
  84184. * @param {object} [options]
  84185. * @param {Vec3} [options.position]
  84186. * @param {Vec3} [options.velocity]
  84187. * @param {Vec3} [options.angularVelocity]
  84188. * @param {Quaternion} [options.quaternion]
  84189. * @param {number} [options.mass]
  84190. * @param {Material} [options.material]
  84191. * @param {number} [options.type]
  84192. * @param {number} [options.linearDamping=0.01]
  84193. * @param {number} [options.angularDamping=0.01]
  84194. * @param {boolean} [options.allowSleep=true]
  84195. * @param {number} [options.sleepSpeedLimit=0.1]
  84196. * @param {number} [options.sleepTimeLimit=1]
  84197. * @param {number} [options.collisionFilterGroup=1]
  84198. * @param {number} [options.collisionFilterMask=1]
  84199. * @param {boolean} [options.fixedRotation=false]
  84200. * @param {Body} [options.shape]
  84201. * @example
  84202. * var body = new Body({
  84203. * mass: 1
  84204. * });
  84205. * var shape = new Sphere(1);
  84206. * body.addShape(shape);
  84207. * world.add(body);
  84208. */
  84209. function Body(options){
  84210. options = options || {};
  84211. EventTarget.apply(this);
  84212. this.id = Body.idCounter++;
  84213. /**
  84214. * Reference to the world the body is living in
  84215. * @property world
  84216. * @type {World}
  84217. */
  84218. this.world = null;
  84219. /**
  84220. * 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.
  84221. * @property preStep
  84222. * @type {Function}
  84223. * @deprecated Use World events instead
  84224. */
  84225. this.preStep = null;
  84226. /**
  84227. * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object.
  84228. * @property postStep
  84229. * @type {Function}
  84230. * @deprecated Use World events instead
  84231. */
  84232. this.postStep = null;
  84233. this.vlambda = new Vec3();
  84234. /**
  84235. * @property {Number} collisionFilterGroup
  84236. */
  84237. this.collisionFilterGroup = typeof(options.collisionFilterGroup) === 'number' ? options.collisionFilterGroup : 1;
  84238. /**
  84239. * @property {Number} collisionFilterMask
  84240. */
  84241. this.collisionFilterMask = typeof(options.collisionFilterMask) === 'number' ? options.collisionFilterMask : 1;
  84242. /**
  84243. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  84244. * @property {Number} collisionResponse
  84245. */
  84246. this.collisionResponse = true;
  84247. /**
  84248. * @property position
  84249. * @type {Vec3}
  84250. */
  84251. this.position = new Vec3();
  84252. if(options.position){
  84253. this.position.copy(options.position);
  84254. }
  84255. /**
  84256. * @property {Vec3} previousPosition
  84257. */
  84258. this.previousPosition = new Vec3();
  84259. /**
  84260. * Initial position of the body
  84261. * @property initPosition
  84262. * @type {Vec3}
  84263. */
  84264. this.initPosition = new Vec3();
  84265. /**
  84266. * @property velocity
  84267. * @type {Vec3}
  84268. */
  84269. this.velocity = new Vec3();
  84270. if(options.velocity){
  84271. this.velocity.copy(options.velocity);
  84272. }
  84273. /**
  84274. * @property initVelocity
  84275. * @type {Vec3}
  84276. */
  84277. this.initVelocity = new Vec3();
  84278. /**
  84279. * Linear force on the body
  84280. * @property force
  84281. * @type {Vec3}
  84282. */
  84283. this.force = new Vec3();
  84284. var mass = typeof(options.mass) === 'number' ? options.mass : 0;
  84285. /**
  84286. * @property mass
  84287. * @type {Number}
  84288. * @default 0
  84289. */
  84290. this.mass = mass;
  84291. /**
  84292. * @property invMass
  84293. * @type {Number}
  84294. */
  84295. this.invMass = mass > 0 ? 1.0 / mass : 0;
  84296. /**
  84297. * @property material
  84298. * @type {Material}
  84299. */
  84300. this.material = options.material || null;
  84301. /**
  84302. * @property linearDamping
  84303. * @type {Number}
  84304. */
  84305. this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01;
  84306. /**
  84307. * One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC.
  84308. * @property type
  84309. * @type {Number}
  84310. */
  84311. this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC);
  84312. if(typeof(options.type) === typeof(Body.STATIC)){
  84313. this.type = options.type;
  84314. }
  84315. /**
  84316. * If true, the body will automatically fall to sleep.
  84317. * @property allowSleep
  84318. * @type {Boolean}
  84319. * @default true
  84320. */
  84321. this.allowSleep = typeof(options.allowSleep) !== 'undefined' ? options.allowSleep : true;
  84322. /**
  84323. * Current sleep state.
  84324. * @property sleepState
  84325. * @type {Number}
  84326. */
  84327. this.sleepState = 0;
  84328. /**
  84329. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  84330. * @property sleepSpeedLimit
  84331. * @type {Number}
  84332. * @default 0.1
  84333. */
  84334. this.sleepSpeedLimit = typeof(options.sleepSpeedLimit) !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  84335. /**
  84336. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  84337. * @property sleepTimeLimit
  84338. * @type {Number}
  84339. * @default 1
  84340. */
  84341. this.sleepTimeLimit = typeof(options.sleepTimeLimit) !== 'undefined' ? options.sleepTimeLimit : 1;
  84342. this.timeLastSleepy = 0;
  84343. this._wakeUpAfterNarrowphase = false;
  84344. /**
  84345. * Rotational force on the body, around center of mass
  84346. * @property {Vec3} torque
  84347. */
  84348. this.torque = new Vec3();
  84349. /**
  84350. * Orientation of the body
  84351. * @property quaternion
  84352. * @type {Quaternion}
  84353. */
  84354. this.quaternion = new Quaternion();
  84355. if(options.quaternion){
  84356. this.quaternion.copy(options.quaternion);
  84357. }
  84358. /**
  84359. * @property initQuaternion
  84360. * @type {Quaternion}
  84361. */
  84362. this.initQuaternion = new Quaternion();
  84363. /**
  84364. * @property angularVelocity
  84365. * @type {Vec3}
  84366. */
  84367. this.angularVelocity = new Vec3();
  84368. if(options.angularVelocity){
  84369. this.angularVelocity.copy(options.angularVelocity);
  84370. }
  84371. /**
  84372. * @property initAngularVelocity
  84373. * @type {Vec3}
  84374. */
  84375. this.initAngularVelocity = new Vec3();
  84376. this.interpolatedPosition = new Vec3();
  84377. this.interpolatedQuaternion = new Quaternion();
  84378. /**
  84379. * @property shapes
  84380. * @type {array}
  84381. */
  84382. this.shapes = [];
  84383. /**
  84384. * @property shapeOffsets
  84385. * @type {array}
  84386. */
  84387. this.shapeOffsets = [];
  84388. /**
  84389. * @property shapeOrientations
  84390. * @type {array}
  84391. */
  84392. this.shapeOrientations = [];
  84393. /**
  84394. * @property inertia
  84395. * @type {Vec3}
  84396. */
  84397. this.inertia = new Vec3();
  84398. /**
  84399. * @property {Vec3} invInertia
  84400. */
  84401. this.invInertia = new Vec3();
  84402. /**
  84403. * @property {Mat3} invInertiaWorld
  84404. */
  84405. this.invInertiaWorld = new Mat3();
  84406. this.invMassSolve = 0;
  84407. /**
  84408. * @property {Vec3} invInertiaSolve
  84409. */
  84410. this.invInertiaSolve = new Vec3();
  84411. /**
  84412. * @property {Mat3} invInertiaWorldSolve
  84413. */
  84414. this.invInertiaWorldSolve = new Mat3();
  84415. /**
  84416. * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
  84417. * @property {Boolean} fixedRotation
  84418. * @default false
  84419. */
  84420. this.fixedRotation = typeof(options.fixedRotation) !== "undefined" ? options.fixedRotation : false;
  84421. /**
  84422. * @property {Number} angularDamping
  84423. */
  84424. this.angularDamping = typeof(options.angularDamping) !== 'undefined' ? options.angularDamping : 0.01;
  84425. /**
  84426. * @property aabb
  84427. * @type {AABB}
  84428. */
  84429. this.aabb = new AABB();
  84430. /**
  84431. * Indicates if the AABB needs to be updated before use.
  84432. * @property aabbNeedsUpdate
  84433. * @type {Boolean}
  84434. */
  84435. this.aabbNeedsUpdate = true;
  84436. this.wlambda = new Vec3();
  84437. if(options.shape){
  84438. this.addShape(options.shape);
  84439. }
  84440. this.updateMassProperties();
  84441. }
  84442. Body.prototype = new EventTarget();
  84443. Body.prototype.constructor = Body;
  84444. /**
  84445. * 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.
  84446. * @static
  84447. * @property DYNAMIC
  84448. * @type {Number}
  84449. */
  84450. Body.DYNAMIC = 1;
  84451. /**
  84452. * 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.
  84453. * @static
  84454. * @property STATIC
  84455. * @type {Number}
  84456. */
  84457. Body.STATIC = 2;
  84458. /**
  84459. * 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.
  84460. * @static
  84461. * @property KINEMATIC
  84462. * @type {Number}
  84463. */
  84464. Body.KINEMATIC = 4;
  84465. /**
  84466. * @static
  84467. * @property AWAKE
  84468. * @type {number}
  84469. */
  84470. Body.AWAKE = 0;
  84471. /**
  84472. * @static
  84473. * @property SLEEPY
  84474. * @type {number}
  84475. */
  84476. Body.SLEEPY = 1;
  84477. /**
  84478. * @static
  84479. * @property SLEEPING
  84480. * @type {number}
  84481. */
  84482. Body.SLEEPING = 2;
  84483. Body.idCounter = 0;
  84484. /**
  84485. * Wake the body up.
  84486. * @method wakeUp
  84487. */
  84488. Body.prototype.wakeUp = function(){
  84489. var s = this.sleepState;
  84490. this.sleepState = 0;
  84491. if(s === Body.SLEEPING){
  84492. this.dispatchEvent({type:"wakeup"});
  84493. }
  84494. };
  84495. /**
  84496. * Force body sleep
  84497. * @method sleep
  84498. */
  84499. Body.prototype.sleep = function(){
  84500. this.sleepState = Body.SLEEPING;
  84501. this.velocity.set(0,0,0);
  84502. this.angularVelocity.set(0,0,0);
  84503. };
  84504. Body.sleepyEvent = {
  84505. type: "sleepy"
  84506. };
  84507. Body.sleepEvent = {
  84508. type: "sleep"
  84509. };
  84510. /**
  84511. * Called every timestep to update internal sleep timer and change sleep state if needed.
  84512. * @method sleepTick
  84513. * @param {Number} time The world time in seconds
  84514. */
  84515. Body.prototype.sleepTick = function(time){
  84516. if(this.allowSleep){
  84517. var sleepState = this.sleepState;
  84518. var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2();
  84519. var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
  84520. if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
  84521. this.sleepState = Body.SLEEPY; // Sleepy
  84522. this.timeLastSleepy = time;
  84523. this.dispatchEvent(Body.sleepyEvent);
  84524. } else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
  84525. this.wakeUp(); // Wake up
  84526. } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
  84527. this.sleep(); // Sleeping
  84528. this.dispatchEvent(Body.sleepEvent);
  84529. }
  84530. }
  84531. };
  84532. /**
  84533. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  84534. * @method updateSolveMassProperties
  84535. */
  84536. Body.prototype.updateSolveMassProperties = function(){
  84537. if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
  84538. this.invMassSolve = 0;
  84539. this.invInertiaSolve.setZero();
  84540. this.invInertiaWorldSolve.setZero();
  84541. } else {
  84542. this.invMassSolve = this.invMass;
  84543. this.invInertiaSolve.copy(this.invInertia);
  84544. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  84545. }
  84546. };
  84547. /**
  84548. * Convert a world point to local body frame.
  84549. * @method pointToLocalFrame
  84550. * @param {Vec3} worldPoint
  84551. * @param {Vec3} result
  84552. * @return {Vec3}
  84553. */
  84554. Body.prototype.pointToLocalFrame = function(worldPoint,result){
  84555. var result = result || new Vec3();
  84556. worldPoint.vsub(this.position,result);
  84557. this.quaternion.conjugate().vmult(result,result);
  84558. return result;
  84559. };
  84560. /**
  84561. * Convert a world vector to local body frame.
  84562. * @method vectorToLocalFrame
  84563. * @param {Vec3} worldPoint
  84564. * @param {Vec3} result
  84565. * @return {Vec3}
  84566. */
  84567. Body.prototype.vectorToLocalFrame = function(worldVector, result){
  84568. var result = result || new Vec3();
  84569. this.quaternion.conjugate().vmult(worldVector,result);
  84570. return result;
  84571. };
  84572. /**
  84573. * Convert a local body point to world frame.
  84574. * @method pointToWorldFrame
  84575. * @param {Vec3} localPoint
  84576. * @param {Vec3} result
  84577. * @return {Vec3}
  84578. */
  84579. Body.prototype.pointToWorldFrame = function(localPoint,result){
  84580. var result = result || new Vec3();
  84581. this.quaternion.vmult(localPoint,result);
  84582. result.vadd(this.position,result);
  84583. return result;
  84584. };
  84585. /**
  84586. * Convert a local body point to world frame.
  84587. * @method vectorToWorldFrame
  84588. * @param {Vec3} localVector
  84589. * @param {Vec3} result
  84590. * @return {Vec3}
  84591. */
  84592. Body.prototype.vectorToWorldFrame = function(localVector, result){
  84593. var result = result || new Vec3();
  84594. this.quaternion.vmult(localVector, result);
  84595. return result;
  84596. };
  84597. var tmpVec = new Vec3();
  84598. var tmpQuat = new Quaternion();
  84599. /**
  84600. * Add a shape to the body with a local offset and orientation.
  84601. * @method addShape
  84602. * @param {Shape} shape
  84603. * @param {Vec3} offset
  84604. * @param {Quaternion} quaternion
  84605. * @return {Body} The body object, for chainability.
  84606. */
  84607. Body.prototype.addShape = function(shape, _offset, _orientation){
  84608. var offset = new Vec3();
  84609. var orientation = new Quaternion();
  84610. if(_offset){
  84611. offset.copy(_offset);
  84612. }
  84613. if(_orientation){
  84614. orientation.copy(_orientation);
  84615. }
  84616. this.shapes.push(shape);
  84617. this.shapeOffsets.push(offset);
  84618. this.shapeOrientations.push(orientation);
  84619. this.updateMassProperties();
  84620. this.updateBoundingRadius();
  84621. this.aabbNeedsUpdate = true;
  84622. return this;
  84623. };
  84624. /**
  84625. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  84626. * @method updateBoundingRadius
  84627. */
  84628. Body.prototype.updateBoundingRadius = function(){
  84629. var shapes = this.shapes,
  84630. shapeOffsets = this.shapeOffsets,
  84631. N = shapes.length,
  84632. radius = 0;
  84633. for(var i=0; i!==N; i++){
  84634. var shape = shapes[i];
  84635. shape.updateBoundingSphereRadius();
  84636. var offset = shapeOffsets[i].norm(),
  84637. r = shape.boundingSphereRadius;
  84638. if(offset + r > radius){
  84639. radius = offset + r;
  84640. }
  84641. }
  84642. this.boundingRadius = radius;
  84643. };
  84644. var computeAABB_shapeAABB = new AABB();
  84645. /**
  84646. * Updates the .aabb
  84647. * @method computeAABB
  84648. * @todo rename to updateAABB()
  84649. */
  84650. Body.prototype.computeAABB = function(){
  84651. var shapes = this.shapes,
  84652. shapeOffsets = this.shapeOffsets,
  84653. shapeOrientations = this.shapeOrientations,
  84654. N = shapes.length,
  84655. offset = tmpVec,
  84656. orientation = tmpQuat,
  84657. bodyQuat = this.quaternion,
  84658. aabb = this.aabb,
  84659. shapeAABB = computeAABB_shapeAABB;
  84660. for(var i=0; i!==N; i++){
  84661. var shape = shapes[i];
  84662. // Get shape world quaternion
  84663. shapeOrientations[i].mult(bodyQuat, orientation);
  84664. // Get shape world position
  84665. orientation.vmult(shapeOffsets[i], offset);
  84666. offset.vadd(this.position, offset);
  84667. // vec2.rotate(offset, shapeOffsets[i], bodyAngle);
  84668. // vec2.add(offset, offset, this.position);
  84669. // Get shape AABB
  84670. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  84671. if(i === 0){
  84672. aabb.copy(shapeAABB);
  84673. } else {
  84674. aabb.extend(shapeAABB);
  84675. }
  84676. }
  84677. this.aabbNeedsUpdate = false;
  84678. };
  84679. var uiw_m1 = new Mat3(),
  84680. uiw_m2 = new Mat3(),
  84681. uiw_m3 = new Mat3();
  84682. /**
  84683. * Update .inertiaWorld and .invInertiaWorld
  84684. * @method updateInertiaWorld
  84685. */
  84686. Body.prototype.updateInertiaWorld = function(force){
  84687. var I = this.invInertia;
  84688. if (I.x === I.y && I.y === I.z && !force) {
  84689. // If inertia M = s*I, where I is identity and s a scalar, then
  84690. // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
  84691. // where R is the rotation matrix.
  84692. // In other words, we don't have to transform the inertia if all
  84693. // inertia diagonal entries are equal.
  84694. } else {
  84695. var m1 = uiw_m1,
  84696. m2 = uiw_m2,
  84697. m3 = uiw_m3;
  84698. m1.setRotationFromQuaternion(this.quaternion);
  84699. m1.transpose(m2);
  84700. m1.scale(I,m1);
  84701. m1.mmult(m2,this.invInertiaWorld);
  84702. //m3.getTrace(this.invInertiaWorld);
  84703. }
  84704. /*
  84705. this.quaternion.vmult(this.inertia,this.inertiaWorld);
  84706. this.quaternion.vmult(this.invInertia,this.invInertiaWorld);
  84707. */
  84708. };
  84709. /**
  84710. * 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.
  84711. * @method applyForce
  84712. * @param {Vec3} force The amount of force to add.
  84713. * @param {Vec3} worldPoint A world point to apply the force on.
  84714. */
  84715. var Body_applyForce_r = new Vec3();
  84716. var Body_applyForce_rotForce = new Vec3();
  84717. Body.prototype.applyForce = function(force,worldPoint){
  84718. if(this.type !== Body.DYNAMIC){
  84719. return;
  84720. }
  84721. // Compute point position relative to the body center
  84722. var r = Body_applyForce_r;
  84723. worldPoint.vsub(this.position,r);
  84724. // Compute produced rotational force
  84725. var rotForce = Body_applyForce_rotForce;
  84726. r.cross(force,rotForce);
  84727. // Add linear force
  84728. this.force.vadd(force,this.force);
  84729. // Add rotational force
  84730. this.torque.vadd(rotForce,this.torque);
  84731. };
  84732. /**
  84733. * Apply force to a local point in the body.
  84734. * @method applyLocalForce
  84735. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  84736. * @param {Vec3} localPoint A local point in the body to apply the force on.
  84737. */
  84738. var Body_applyLocalForce_worldForce = new Vec3();
  84739. var Body_applyLocalForce_worldPoint = new Vec3();
  84740. Body.prototype.applyLocalForce = function(localForce, localPoint){
  84741. if(this.type !== Body.DYNAMIC){
  84742. return;
  84743. }
  84744. var worldForce = Body_applyLocalForce_worldForce;
  84745. var worldPoint = Body_applyLocalForce_worldPoint;
  84746. // Transform the force vector to world space
  84747. this.vectorToWorldFrame(localForce, worldForce);
  84748. this.pointToWorldFrame(localPoint, worldPoint);
  84749. this.applyForce(worldForce, worldPoint);
  84750. };
  84751. /**
  84752. * 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.
  84753. * @method applyImpulse
  84754. * @param {Vec3} impulse The amount of impulse to add.
  84755. * @param {Vec3} worldPoint A world point to apply the force on.
  84756. */
  84757. var Body_applyImpulse_r = new Vec3();
  84758. var Body_applyImpulse_velo = new Vec3();
  84759. var Body_applyImpulse_rotVelo = new Vec3();
  84760. Body.prototype.applyImpulse = function(impulse, worldPoint){
  84761. if(this.type !== Body.DYNAMIC){
  84762. return;
  84763. }
  84764. // Compute point position relative to the body center
  84765. var r = Body_applyImpulse_r;
  84766. worldPoint.vsub(this.position,r);
  84767. // Compute produced central impulse velocity
  84768. var velo = Body_applyImpulse_velo;
  84769. velo.copy(impulse);
  84770. velo.mult(this.invMass,velo);
  84771. // Add linear impulse
  84772. this.velocity.vadd(velo, this.velocity);
  84773. // Compute produced rotational impulse velocity
  84774. var rotVelo = Body_applyImpulse_rotVelo;
  84775. r.cross(impulse,rotVelo);
  84776. /*
  84777. rotVelo.x *= this.invInertia.x;
  84778. rotVelo.y *= this.invInertia.y;
  84779. rotVelo.z *= this.invInertia.z;
  84780. */
  84781. this.invInertiaWorld.vmult(rotVelo,rotVelo);
  84782. // Add rotational Impulse
  84783. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  84784. };
  84785. /**
  84786. * Apply locally-defined impulse to a local point in the body.
  84787. * @method applyLocalImpulse
  84788. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  84789. * @param {Vec3} localPoint A local point in the body to apply the force on.
  84790. */
  84791. var Body_applyLocalImpulse_worldImpulse = new Vec3();
  84792. var Body_applyLocalImpulse_worldPoint = new Vec3();
  84793. Body.prototype.applyLocalImpulse = function(localImpulse, localPoint){
  84794. if(this.type !== Body.DYNAMIC){
  84795. return;
  84796. }
  84797. var worldImpulse = Body_applyLocalImpulse_worldImpulse;
  84798. var worldPoint = Body_applyLocalImpulse_worldPoint;
  84799. // Transform the force vector to world space
  84800. this.vectorToWorldFrame(localImpulse, worldImpulse);
  84801. this.pointToWorldFrame(localPoint, worldPoint);
  84802. this.applyImpulse(worldImpulse, worldPoint);
  84803. };
  84804. var Body_updateMassProperties_halfExtents = new Vec3();
  84805. /**
  84806. * Should be called whenever you change the body shape or mass.
  84807. * @method updateMassProperties
  84808. */
  84809. Body.prototype.updateMassProperties = function(){
  84810. var halfExtents = Body_updateMassProperties_halfExtents;
  84811. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  84812. var I = this.inertia;
  84813. var fixed = this.fixedRotation;
  84814. // Approximate with AABB box
  84815. this.computeAABB();
  84816. halfExtents.set(
  84817. (this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2,
  84818. (this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2,
  84819. (this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2
  84820. );
  84821. Box.calculateInertia(halfExtents, this.mass, I);
  84822. this.invInertia.set(
  84823. I.x > 0 && !fixed ? 1.0 / I.x : 0,
  84824. I.y > 0 && !fixed ? 1.0 / I.y : 0,
  84825. I.z > 0 && !fixed ? 1.0 / I.z : 0
  84826. );
  84827. this.updateInertiaWorld(true);
  84828. };
  84829. /**
  84830. * Get world velocity of a point in the body.
  84831. * @method getVelocityAtWorldPoint
  84832. * @param {Vec3} worldPoint
  84833. * @param {Vec3} result
  84834. * @return {Vec3} The result vector.
  84835. */
  84836. Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){
  84837. var r = new Vec3();
  84838. worldPoint.vsub(this.position, r);
  84839. this.angularVelocity.cross(r, result);
  84840. this.velocity.vadd(result, result);
  84841. return result;
  84842. };
  84843. },{"../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){
  84844. var Body = _dereq_('./Body');
  84845. var Vec3 = _dereq_('../math/Vec3');
  84846. var Quaternion = _dereq_('../math/Quaternion');
  84847. var RaycastResult = _dereq_('../collision/RaycastResult');
  84848. var Ray = _dereq_('../collision/Ray');
  84849. var WheelInfo = _dereq_('../objects/WheelInfo');
  84850. module.exports = RaycastVehicle;
  84851. /**
  84852. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  84853. * @class RaycastVehicle
  84854. * @constructor
  84855. * @param {object} [options]
  84856. * @param {Body} [options.chassisBody] The car chassis body.
  84857. * @param {integer} [options.indexRightAxis] Axis to use for right. x=0, y=1, z=2
  84858. * @param {integer} [options.indexLeftAxis]
  84859. * @param {integer} [options.indexUpAxis]
  84860. */
  84861. function RaycastVehicle(options){
  84862. /**
  84863. * @property {Body} chassisBody
  84864. */
  84865. this.chassisBody = options.chassisBody;
  84866. /**
  84867. * An array of WheelInfo objects.
  84868. * @property {array} wheelInfos
  84869. */
  84870. this.wheelInfos = [];
  84871. /**
  84872. * Will be set to true if the car is sliding.
  84873. * @property {boolean} sliding
  84874. */
  84875. this.sliding = false;
  84876. /**
  84877. * @property {World} world
  84878. */
  84879. this.world = null;
  84880. /**
  84881. * Index of the right axis, 0=x, 1=y, 2=z
  84882. * @property {integer} indexRightAxis
  84883. * @default 1
  84884. */
  84885. this.indexRightAxis = typeof(options.indexRightAxis) !== 'undefined' ? options.indexRightAxis : 1;
  84886. /**
  84887. * Index of the forward axis, 0=x, 1=y, 2=z
  84888. * @property {integer} indexForwardAxis
  84889. * @default 0
  84890. */
  84891. this.indexForwardAxis = typeof(options.indexForwardAxis) !== 'undefined' ? options.indexForwardAxis : 0;
  84892. /**
  84893. * Index of the up axis, 0=x, 1=y, 2=z
  84894. * @property {integer} indexUpAxis
  84895. * @default 2
  84896. */
  84897. this.indexUpAxis = typeof(options.indexUpAxis) !== 'undefined' ? options.indexUpAxis : 2;
  84898. }
  84899. var tmpVec1 = new Vec3();
  84900. var tmpVec2 = new Vec3();
  84901. var tmpVec3 = new Vec3();
  84902. var tmpVec4 = new Vec3();
  84903. var tmpVec5 = new Vec3();
  84904. var tmpVec6 = new Vec3();
  84905. var tmpRay = new Ray();
  84906. /**
  84907. * Add a wheel. For information about the options, see WheelInfo.
  84908. * @method addWheel
  84909. * @param {object} [options]
  84910. */
  84911. RaycastVehicle.prototype.addWheel = function(options){
  84912. options = options || {};
  84913. var info = new WheelInfo(options);
  84914. var index = this.wheelInfos.length;
  84915. this.wheelInfos.push(info);
  84916. return index;
  84917. };
  84918. /**
  84919. * Set the steering value of a wheel.
  84920. * @method setSteeringValue
  84921. * @param {number} value
  84922. * @param {integer} wheelIndex
  84923. */
  84924. RaycastVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  84925. var wheel = this.wheelInfos[wheelIndex];
  84926. wheel.steering = value;
  84927. };
  84928. var torque = new Vec3();
  84929. /**
  84930. * Set the wheel force to apply on one of the wheels each time step
  84931. * @method applyEngineForce
  84932. * @param {number} value
  84933. * @param {integer} wheelIndex
  84934. */
  84935. RaycastVehicle.prototype.applyEngineForce = function(value, wheelIndex){
  84936. this.wheelInfos[wheelIndex].engineForce = value;
  84937. };
  84938. /**
  84939. * Set the braking force of a wheel
  84940. * @method setBrake
  84941. * @param {number} brake
  84942. * @param {integer} wheelIndex
  84943. */
  84944. RaycastVehicle.prototype.setBrake = function(brake, wheelIndex){
  84945. this.wheelInfos[wheelIndex].brake = brake;
  84946. };
  84947. /**
  84948. * Add the vehicle including its constraints to the world.
  84949. * @method addToWorld
  84950. * @param {World} world
  84951. */
  84952. RaycastVehicle.prototype.addToWorld = function(world){
  84953. var constraints = this.constraints;
  84954. world.add(this.chassisBody);
  84955. var that = this;
  84956. this.preStepCallback = function(){
  84957. that.updateVehicle(world.dt);
  84958. };
  84959. world.addEventListener('preStep', this.preStepCallback);
  84960. this.world = world;
  84961. };
  84962. /**
  84963. * Get one of the wheel axles, world-oriented.
  84964. * @private
  84965. * @method getVehicleAxisWorld
  84966. * @param {integer} axisIndex
  84967. * @param {Vec3} result
  84968. */
  84969. RaycastVehicle.prototype.getVehicleAxisWorld = function(axisIndex, result){
  84970. result.set(
  84971. axisIndex === 0 ? 1 : 0,
  84972. axisIndex === 1 ? 1 : 0,
  84973. axisIndex === 2 ? 1 : 0
  84974. );
  84975. this.chassisBody.vectorToWorldFrame(result, result);
  84976. };
  84977. RaycastVehicle.prototype.updateVehicle = function(timeStep){
  84978. var wheelInfos = this.wheelInfos;
  84979. var numWheels = wheelInfos.length;
  84980. var chassisBody = this.chassisBody;
  84981. for (var i = 0; i < numWheels; i++) {
  84982. this.updateWheelTransform(i);
  84983. }
  84984. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.norm();
  84985. var forwardWorld = new Vec3();
  84986. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  84987. if (forwardWorld.dot(chassisBody.velocity) < 0){
  84988. this.currentVehicleSpeedKmHour *= -1;
  84989. }
  84990. // simulate suspension
  84991. for (var i = 0; i < numWheels; i++) {
  84992. this.castRay(wheelInfos[i]);
  84993. }
  84994. this.updateSuspension(timeStep);
  84995. var impulse = new Vec3();
  84996. var relpos = new Vec3();
  84997. for (var i = 0; i < numWheels; i++) {
  84998. //apply suspension force
  84999. var wheel = wheelInfos[i];
  85000. var suspensionForce = wheel.suspensionForce;
  85001. if (suspensionForce > wheel.maxSuspensionForce) {
  85002. suspensionForce = wheel.maxSuspensionForce;
  85003. }
  85004. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  85005. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  85006. chassisBody.applyImpulse(impulse, wheel.raycastResult.hitPointWorld/*relpos*/);
  85007. }
  85008. this.updateFriction(timeStep);
  85009. var hitNormalWorldScaledWithProj = new Vec3();
  85010. var fwd = new Vec3();
  85011. var vel = new Vec3();
  85012. for (i = 0; i < numWheels; i++) {
  85013. var wheel = wheelInfos[i];
  85014. //var relpos = new Vec3();
  85015. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  85016. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel);
  85017. // Hack to get the rotation in the correct direction
  85018. var m = 1;
  85019. switch(this.indexUpAxis){
  85020. case 1:
  85021. m = -1;
  85022. break;
  85023. }
  85024. if (wheel.isInContact) {
  85025. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  85026. var proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  85027. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  85028. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  85029. var proj2 = fwd.dot(vel);
  85030. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  85031. }
  85032. if((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed){
  85033. // Apply custom rotation when accelerating and sliding
  85034. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  85035. }
  85036. // Lock wheels
  85037. if(Math.abs(wheel.brake) > Math.abs(wheel.engineForce)){
  85038. wheel.deltaRotation = 0;
  85039. }
  85040. wheel.rotation += wheel.deltaRotation; // Use the old value
  85041. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  85042. }
  85043. };
  85044. RaycastVehicle.prototype.updateSuspension = function(deltaTime) {
  85045. var chassisBody = this.chassisBody;
  85046. var chassisMass = chassisBody.mass;
  85047. var wheelInfos = this.wheelInfos;
  85048. var numWheels = wheelInfos.length;
  85049. for (var w_it = 0; w_it < numWheels; w_it++){
  85050. var wheel = wheelInfos[w_it];
  85051. if (wheel.isInContact){
  85052. var force;
  85053. // Spring
  85054. var susp_length = wheel.suspensionRestLength;
  85055. var current_length = wheel.suspensionLength;
  85056. var length_diff = (susp_length - current_length);
  85057. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension;
  85058. // Damper
  85059. var projected_rel_vel = wheel.suspensionRelativeVelocity;
  85060. var susp_damping;
  85061. if (projected_rel_vel < 0) {
  85062. susp_damping = wheel.dampingCompression;
  85063. } else {
  85064. susp_damping = wheel.dampingRelaxation;
  85065. }
  85066. force -= susp_damping * projected_rel_vel;
  85067. wheel.suspensionForce = force * chassisMass;
  85068. if (wheel.suspensionForce < 0) {
  85069. wheel.suspensionForce = 0;
  85070. }
  85071. } else {
  85072. wheel.suspensionForce = 0;
  85073. }
  85074. }
  85075. };
  85076. /**
  85077. * Remove the vehicle including its constraints from the world.
  85078. * @method removeFromWorld
  85079. * @param {World} world
  85080. */
  85081. RaycastVehicle.prototype.removeFromWorld = function(world){
  85082. var constraints = this.constraints;
  85083. world.remove(this.chassisBody);
  85084. world.removeEventListener('preStep', this.preStepCallback);
  85085. this.world = null;
  85086. };
  85087. var castRay_rayvector = new Vec3();
  85088. var castRay_target = new Vec3();
  85089. RaycastVehicle.prototype.castRay = function(wheel) {
  85090. var rayvector = castRay_rayvector;
  85091. var target = castRay_target;
  85092. this.updateWheelTransformWorld(wheel);
  85093. var chassisBody = this.chassisBody;
  85094. var depth = -1;
  85095. var raylen = wheel.suspensionRestLength + wheel.radius;
  85096. wheel.directionWorld.scale(raylen, rayvector);
  85097. var source = wheel.chassisConnectionPointWorld;
  85098. source.vadd(rayvector, target);
  85099. var raycastResult = wheel.raycastResult;
  85100. var param = 0;
  85101. raycastResult.reset();
  85102. // Turn off ray collision with the chassis temporarily
  85103. var oldState = chassisBody.collisionResponse;
  85104. chassisBody.collisionResponse = false;
  85105. // Cast ray against world
  85106. this.world.rayTest(source, target, raycastResult);
  85107. chassisBody.collisionResponse = oldState;
  85108. var object = raycastResult.body;
  85109. wheel.raycastResult.groundObject = 0;
  85110. if (object) {
  85111. depth = raycastResult.distance;
  85112. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  85113. wheel.isInContact = true;
  85114. var hitDistance = raycastResult.distance;
  85115. wheel.suspensionLength = hitDistance - wheel.radius;
  85116. // clamp on max suspension travel
  85117. var minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  85118. var maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  85119. if (wheel.suspensionLength < minSuspensionLength) {
  85120. wheel.suspensionLength = minSuspensionLength;
  85121. }
  85122. if (wheel.suspensionLength > maxSuspensionLength) {
  85123. wheel.suspensionLength = maxSuspensionLength;
  85124. wheel.raycastResult.reset();
  85125. }
  85126. var denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  85127. var chassis_velocity_at_contactPoint = new Vec3();
  85128. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  85129. var projVel = wheel.raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  85130. if (denominator >= -0.1) {
  85131. wheel.suspensionRelativeVelocity = 0;
  85132. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  85133. } else {
  85134. var inv = -1 / denominator;
  85135. wheel.suspensionRelativeVelocity = projVel * inv;
  85136. wheel.clippedInvContactDotSuspension = inv;
  85137. }
  85138. } else {
  85139. //put wheel info as in rest position
  85140. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  85141. wheel.suspensionRelativeVelocity = 0.0;
  85142. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  85143. wheel.clippedInvContactDotSuspension = 1.0;
  85144. }
  85145. return depth;
  85146. };
  85147. RaycastVehicle.prototype.updateWheelTransformWorld = function(wheel){
  85148. wheel.isInContact = false;
  85149. var chassisBody = this.chassisBody;
  85150. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  85151. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  85152. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  85153. };
  85154. /**
  85155. * Update one of the wheel transform.
  85156. * 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.
  85157. * @method updateWheelTransform
  85158. * @param {integer} wheelIndex The wheel index to update.
  85159. */
  85160. RaycastVehicle.prototype.updateWheelTransform = function(wheelIndex){
  85161. var up = tmpVec4;
  85162. var right = tmpVec5;
  85163. var fwd = tmpVec6;
  85164. var wheel = this.wheelInfos[wheelIndex];
  85165. this.updateWheelTransformWorld(wheel);
  85166. wheel.directionLocal.scale(-1, up);
  85167. right.copy(wheel.axleLocal);
  85168. up.cross(right, fwd);
  85169. fwd.normalize();
  85170. right.normalize();
  85171. // Rotate around steering over the wheelAxle
  85172. var steering = wheel.steering;
  85173. var steeringOrn = new Quaternion();
  85174. steeringOrn.setFromAxisAngle(up, steering);
  85175. var rotatingOrn = new Quaternion();
  85176. rotatingOrn.setFromAxisAngle(right, wheel.rotation);
  85177. // World rotation of the wheel
  85178. var q = wheel.worldTransform.quaternion;
  85179. this.chassisBody.quaternion.mult(steeringOrn, q);
  85180. q.mult(rotatingOrn, q);
  85181. q.normalize();
  85182. // world position of the wheel
  85183. var p = wheel.worldTransform.position;
  85184. p.copy(wheel.directionWorld);
  85185. p.scale(wheel.suspensionLength, p);
  85186. p.vadd(wheel.chassisConnectionPointWorld, p);
  85187. };
  85188. var directions = [
  85189. new Vec3(1, 0, 0),
  85190. new Vec3(0, 1, 0),
  85191. new Vec3(0, 0, 1)
  85192. ];
  85193. /**
  85194. * Get the world transform of one of the wheels
  85195. * @method getWheelTransformWorld
  85196. * @param {integer} wheelIndex
  85197. * @return {Transform}
  85198. */
  85199. RaycastVehicle.prototype.getWheelTransformWorld = function(wheelIndex) {
  85200. return this.wheelInfos[wheelIndex].worldTransform;
  85201. };
  85202. var updateFriction_surfNormalWS_scaled_proj = new Vec3();
  85203. var updateFriction_axle = [];
  85204. var updateFriction_forwardWS = [];
  85205. var sideFrictionStiffness2 = 1;
  85206. RaycastVehicle.prototype.updateFriction = function(timeStep) {
  85207. var surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj;
  85208. //calculate the impulse, so that the wheels don't move sidewards
  85209. var wheelInfos = this.wheelInfos;
  85210. var numWheels = wheelInfos.length;
  85211. var chassisBody = this.chassisBody;
  85212. var forwardWS = updateFriction_forwardWS;
  85213. var axle = updateFriction_axle;
  85214. var numWheelsOnGround = 0;
  85215. for (var i = 0; i < numWheels; i++) {
  85216. var wheel = wheelInfos[i];
  85217. var groundObject = wheel.raycastResult.body;
  85218. if (groundObject){
  85219. numWheelsOnGround++;
  85220. }
  85221. wheel.sideImpulse = 0;
  85222. wheel.forwardImpulse = 0;
  85223. if(!forwardWS[i]){
  85224. forwardWS[i] = new Vec3();
  85225. }
  85226. if(!axle[i]){
  85227. axle[i] = new Vec3();
  85228. }
  85229. }
  85230. for (var i = 0; i < numWheels; i++){
  85231. var wheel = wheelInfos[i];
  85232. var groundObject = wheel.raycastResult.body;
  85233. if (groundObject) {
  85234. var axlei = axle[i];
  85235. var wheelTrans = this.getWheelTransformWorld(i);
  85236. // Get world axle
  85237. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  85238. var surfNormalWS = wheel.raycastResult.hitNormalWorld;
  85239. var proj = axlei.dot(surfNormalWS);
  85240. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  85241. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  85242. axlei.normalize();
  85243. surfNormalWS.cross(axlei, forwardWS[i]);
  85244. forwardWS[i].normalize();
  85245. wheel.sideImpulse = resolveSingleBilateral(
  85246. chassisBody,
  85247. wheel.raycastResult.hitPointWorld,
  85248. groundObject,
  85249. wheel.raycastResult.hitPointWorld,
  85250. axlei
  85251. );
  85252. wheel.sideImpulse *= sideFrictionStiffness2;
  85253. }
  85254. }
  85255. var sideFactor = 1;
  85256. var fwdFactor = 0.5;
  85257. this.sliding = false;
  85258. for (var i = 0; i < numWheels; i++) {
  85259. var wheel = wheelInfos[i];
  85260. var groundObject = wheel.raycastResult.body;
  85261. var rollingFriction = 0;
  85262. wheel.slipInfo = 1;
  85263. if (groundObject) {
  85264. var defaultRollingFrictionImpulse = 0;
  85265. var maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse;
  85266. // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  85267. // rollingFriction = calcRollingFriction(contactPt);
  85268. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  85269. rollingFriction += wheel.engineForce * timeStep;
  85270. // rollingFriction = 0;
  85271. var factor = maxImpulse / rollingFriction;
  85272. wheel.slipInfo *= factor;
  85273. }
  85274. //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  85275. wheel.forwardImpulse = 0;
  85276. wheel.skidInfo = 1;
  85277. if (groundObject) {
  85278. wheel.skidInfo = 1;
  85279. var maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  85280. var maximpSide = maximp;
  85281. var maximpSquared = maximp * maximpSide;
  85282. wheel.forwardImpulse = rollingFriction;//wheelInfo.engineForce* timeStep;
  85283. var x = wheel.forwardImpulse * fwdFactor;
  85284. var y = wheel.sideImpulse * sideFactor;
  85285. var impulseSquared = x * x + y * y;
  85286. wheel.sliding = false;
  85287. if (impulseSquared > maximpSquared) {
  85288. this.sliding = true;
  85289. wheel.sliding = true;
  85290. var factor = maximp / Math.sqrt(impulseSquared);
  85291. wheel.skidInfo *= factor;
  85292. }
  85293. }
  85294. }
  85295. if (this.sliding) {
  85296. for (var i = 0; i < numWheels; i++) {
  85297. var wheel = wheelInfos[i];
  85298. if (wheel.sideImpulse !== 0) {
  85299. if (wheel.skidInfo < 1){
  85300. wheel.forwardImpulse *= wheel.skidInfo;
  85301. wheel.sideImpulse *= wheel.skidInfo;
  85302. }
  85303. }
  85304. }
  85305. }
  85306. // apply the impulses
  85307. for (var i = 0; i < numWheels; i++) {
  85308. var wheel = wheelInfos[i];
  85309. var rel_pos = new Vec3();
  85310. //wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos);
  85311. // cannons applyimpulse is using world coord for the position
  85312. rel_pos.copy(wheel.raycastResult.hitPointWorld);
  85313. if (wheel.forwardImpulse !== 0) {
  85314. var impulse = new Vec3();
  85315. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  85316. chassisBody.applyImpulse(impulse, rel_pos);
  85317. }
  85318. if (wheel.sideImpulse !== 0){
  85319. var groundObject = wheel.raycastResult.body;
  85320. var rel_pos2 = new Vec3();
  85321. //wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2);
  85322. rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  85323. var sideImp = new Vec3();
  85324. axle[i].scale(wheel.sideImpulse, sideImp);
  85325. // Scale the relative position in the up direction with rollInfluence.
  85326. // 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).
  85327. chassisBody.pointToLocalFrame(rel_pos, rel_pos);
  85328. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  85329. chassisBody.pointToWorldFrame(rel_pos, rel_pos);
  85330. chassisBody.applyImpulse(sideImp, rel_pos);
  85331. //apply friction impulse on the ground
  85332. sideImp.scale(-1, sideImp);
  85333. groundObject.applyImpulse(sideImp, rel_pos2);
  85334. }
  85335. }
  85336. };
  85337. var calcRollingFriction_vel1 = new Vec3();
  85338. var calcRollingFriction_vel2 = new Vec3();
  85339. var calcRollingFriction_vel = new Vec3();
  85340. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  85341. var j1 = 0;
  85342. var contactPosWorld = frictionPosWorld;
  85343. // var rel_pos1 = new Vec3();
  85344. // var rel_pos2 = new Vec3();
  85345. var vel1 = calcRollingFriction_vel1;
  85346. var vel2 = calcRollingFriction_vel2;
  85347. var vel = calcRollingFriction_vel;
  85348. // contactPosWorld.vsub(body0.position, rel_pos1);
  85349. // contactPosWorld.vsub(body1.position, rel_pos2);
  85350. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  85351. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  85352. vel1.vsub(vel2, vel);
  85353. var vrel = frictionDirectionWorld.dot(vel);
  85354. var denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  85355. var denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  85356. var relaxation = 1;
  85357. var jacDiagABInv = relaxation / (denom0 + denom1);
  85358. // calculate j that moves us to zero relative velocity
  85359. j1 = -vrel * jacDiagABInv;
  85360. if (maxImpulse < j1) {
  85361. j1 = maxImpulse;
  85362. }
  85363. if (j1 < -maxImpulse) {
  85364. j1 = -maxImpulse;
  85365. }
  85366. return j1;
  85367. }
  85368. var computeImpulseDenominator_r0 = new Vec3();
  85369. var computeImpulseDenominator_c0 = new Vec3();
  85370. var computeImpulseDenominator_vec = new Vec3();
  85371. var computeImpulseDenominator_m = new Vec3();
  85372. function computeImpulseDenominator(body, pos, normal) {
  85373. var r0 = computeImpulseDenominator_r0;
  85374. var c0 = computeImpulseDenominator_c0;
  85375. var vec = computeImpulseDenominator_vec;
  85376. var m = computeImpulseDenominator_m;
  85377. pos.vsub(body.position, r0);
  85378. r0.cross(normal, c0);
  85379. body.invInertiaWorld.vmult(c0, m);
  85380. m.cross(r0, vec);
  85381. return body.invMass + normal.dot(vec);
  85382. }
  85383. var resolveSingleBilateral_vel1 = new Vec3();
  85384. var resolveSingleBilateral_vel2 = new Vec3();
  85385. var resolveSingleBilateral_vel = new Vec3();
  85386. //bilateral constraint between two dynamic objects
  85387. function resolveSingleBilateral(body1, pos1, body2, pos2, normal, impulse){
  85388. var normalLenSqr = normal.norm2();
  85389. if (normalLenSqr > 1.1){
  85390. return 0; // no impulse
  85391. }
  85392. // var rel_pos1 = new Vec3();
  85393. // var rel_pos2 = new Vec3();
  85394. // pos1.vsub(body1.position, rel_pos1);
  85395. // pos2.vsub(body2.position, rel_pos2);
  85396. var vel1 = resolveSingleBilateral_vel1;
  85397. var vel2 = resolveSingleBilateral_vel2;
  85398. var vel = resolveSingleBilateral_vel;
  85399. body1.getVelocityAtWorldPoint(pos1, vel1);
  85400. body2.getVelocityAtWorldPoint(pos2, vel2);
  85401. vel1.vsub(vel2, vel);
  85402. var rel_vel = normal.dot(vel);
  85403. var contactDamping = 0.2;
  85404. var massTerm = 1 / (body1.invMass + body2.invMass);
  85405. var impulse = - contactDamping * rel_vel * massTerm;
  85406. return impulse;
  85407. }
  85408. },{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(_dereq_,module,exports){
  85409. var Body = _dereq_('./Body');
  85410. var Sphere = _dereq_('../shapes/Sphere');
  85411. var Box = _dereq_('../shapes/Box');
  85412. var Vec3 = _dereq_('../math/Vec3');
  85413. var HingeConstraint = _dereq_('../constraints/HingeConstraint');
  85414. module.exports = RigidVehicle;
  85415. /**
  85416. * Simple vehicle helper class with spherical rigid body wheels.
  85417. * @class RigidVehicle
  85418. * @constructor
  85419. * @param {Body} [options.chassisBody]
  85420. */
  85421. function RigidVehicle(options){
  85422. this.wheelBodies = [];
  85423. /**
  85424. * @property coordinateSystem
  85425. * @type {Vec3}
  85426. */
  85427. this.coordinateSystem = typeof(options.coordinateSystem)==='undefined' ? new Vec3(1, 2, 3) : options.coordinateSystem.clone();
  85428. /**
  85429. * @property {Body} chassisBody
  85430. */
  85431. this.chassisBody = options.chassisBody;
  85432. if(!this.chassisBody){
  85433. // No chassis body given. Create it!
  85434. var chassisShape = new Box(new Vec3(5, 2, 0.5));
  85435. this.chassisBody = new Body(1, chassisShape);
  85436. }
  85437. /**
  85438. * @property constraints
  85439. * @type {Array}
  85440. */
  85441. this.constraints = [];
  85442. this.wheelAxes = [];
  85443. this.wheelForces = [];
  85444. }
  85445. /**
  85446. * Add a wheel
  85447. * @method addWheel
  85448. * @param {object} options
  85449. * @param {boolean} [options.isFrontWheel]
  85450. * @param {Vec3} [options.position] Position of the wheel, locally in the chassis body.
  85451. * @param {Vec3} [options.direction] Slide direction of the wheel along the suspension.
  85452. * @param {Vec3} [options.axis] Axis of rotation of the wheel, locally defined in the chassis.
  85453. * @param {Body} [options.body] The wheel body.
  85454. */
  85455. RigidVehicle.prototype.addWheel = function(options){
  85456. options = options || {};
  85457. var wheelBody = options.body;
  85458. if(!wheelBody){
  85459. wheelBody = new Body(1, new Sphere(1.2));
  85460. }
  85461. this.wheelBodies.push(wheelBody);
  85462. this.wheelForces.push(0);
  85463. // Position constrain wheels
  85464. var zero = new Vec3();
  85465. var position = typeof(options.position) !== 'undefined' ? options.position.clone() : new Vec3();
  85466. // Set position locally to the chassis
  85467. var worldPosition = new Vec3();
  85468. this.chassisBody.pointToWorldFrame(position, worldPosition);
  85469. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z);
  85470. // Constrain wheel
  85471. var axis = typeof(options.axis) !== 'undefined' ? options.axis.clone() : new Vec3(0, 1, 0);
  85472. this.wheelAxes.push(axis);
  85473. var hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  85474. pivotA: position,
  85475. axisA: axis,
  85476. pivotB: Vec3.ZERO,
  85477. axisB: axis,
  85478. collideConnected: false
  85479. });
  85480. this.constraints.push(hingeConstraint);
  85481. return this.wheelBodies.length - 1;
  85482. };
  85483. /**
  85484. * Set the steering value of a wheel.
  85485. * @method setSteeringValue
  85486. * @param {number} value
  85487. * @param {integer} wheelIndex
  85488. * @todo check coordinateSystem
  85489. */
  85490. RigidVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  85491. // Set angle of the hinge axis
  85492. var axis = this.wheelAxes[wheelIndex];
  85493. var c = Math.cos(value),
  85494. s = Math.sin(value),
  85495. x = axis.x,
  85496. y = axis.y;
  85497. this.constraints[wheelIndex].axisA.set(
  85498. c*x -s*y,
  85499. s*x +c*y,
  85500. 0
  85501. );
  85502. };
  85503. /**
  85504. * Set the target rotational speed of the hinge constraint.
  85505. * @method setMotorSpeed
  85506. * @param {number} value
  85507. * @param {integer} wheelIndex
  85508. */
  85509. RigidVehicle.prototype.setMotorSpeed = function(value, wheelIndex){
  85510. var hingeConstraint = this.constraints[wheelIndex];
  85511. hingeConstraint.enableMotor();
  85512. hingeConstraint.motorTargetVelocity = value;
  85513. };
  85514. /**
  85515. * Set the target rotational speed of the hinge constraint.
  85516. * @method disableMotor
  85517. * @param {number} value
  85518. * @param {integer} wheelIndex
  85519. */
  85520. RigidVehicle.prototype.disableMotor = function(wheelIndex){
  85521. var hingeConstraint = this.constraints[wheelIndex];
  85522. hingeConstraint.disableMotor();
  85523. };
  85524. var torque = new Vec3();
  85525. /**
  85526. * Set the wheel force to apply on one of the wheels each time step
  85527. * @method setWheelForce
  85528. * @param {number} value
  85529. * @param {integer} wheelIndex
  85530. */
  85531. RigidVehicle.prototype.setWheelForce = function(value, wheelIndex){
  85532. this.wheelForces[wheelIndex] = value;
  85533. };
  85534. /**
  85535. * Apply a torque on one of the wheels.
  85536. * @method applyWheelForce
  85537. * @param {number} value
  85538. * @param {integer} wheelIndex
  85539. */
  85540. RigidVehicle.prototype.applyWheelForce = function(value, wheelIndex){
  85541. var axis = this.wheelAxes[wheelIndex];
  85542. var wheelBody = this.wheelBodies[wheelIndex];
  85543. var bodyTorque = wheelBody.torque;
  85544. axis.scale(value, torque);
  85545. wheelBody.vectorToWorldFrame(torque, torque);
  85546. bodyTorque.vadd(torque, bodyTorque);
  85547. };
  85548. /**
  85549. * Add the vehicle including its constraints to the world.
  85550. * @method addToWorld
  85551. * @param {World} world
  85552. */
  85553. RigidVehicle.prototype.addToWorld = function(world){
  85554. var constraints = this.constraints;
  85555. var bodies = this.wheelBodies.concat([this.chassisBody]);
  85556. for (var i = 0; i < bodies.length; i++) {
  85557. world.add(bodies[i]);
  85558. }
  85559. for (var i = 0; i < constraints.length; i++) {
  85560. world.addConstraint(constraints[i]);
  85561. }
  85562. world.addEventListener('preStep', this._update.bind(this));
  85563. };
  85564. RigidVehicle.prototype._update = function(){
  85565. var wheelForces = this.wheelForces;
  85566. for (var i = 0; i < wheelForces.length; i++) {
  85567. this.applyWheelForce(wheelForces[i], i);
  85568. }
  85569. };
  85570. /**
  85571. * Remove the vehicle including its constraints from the world.
  85572. * @method removeFromWorld
  85573. * @param {World} world
  85574. */
  85575. RigidVehicle.prototype.removeFromWorld = function(world){
  85576. var constraints = this.constraints;
  85577. var bodies = this.wheelBodies.concat([this.chassisBody]);
  85578. for (var i = 0; i < bodies.length; i++) {
  85579. world.remove(bodies[i]);
  85580. }
  85581. for (var i = 0; i < constraints.length; i++) {
  85582. world.removeConstraint(constraints[i]);
  85583. }
  85584. };
  85585. var worldAxis = new Vec3();
  85586. /**
  85587. * Get current rotational velocity of a wheel
  85588. * @method getWheelSpeed
  85589. * @param {integer} wheelIndex
  85590. */
  85591. RigidVehicle.prototype.getWheelSpeed = function(wheelIndex){
  85592. var axis = this.wheelAxes[wheelIndex];
  85593. var wheelBody = this.wheelBodies[wheelIndex];
  85594. var w = wheelBody.angularVelocity;
  85595. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  85596. return w.dot(worldAxis);
  85597. };
  85598. },{"../constraints/HingeConstraint":15,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Sphere":44,"./Body":31}],34:[function(_dereq_,module,exports){
  85599. module.exports = SPHSystem;
  85600. var Shape = _dereq_('../shapes/Shape');
  85601. var Vec3 = _dereq_('../math/Vec3');
  85602. var Quaternion = _dereq_('../math/Quaternion');
  85603. var Particle = _dereq_('../shapes/Particle');
  85604. var Body = _dereq_('../objects/Body');
  85605. var Material = _dereq_('../material/Material');
  85606. /**
  85607. * Smoothed-particle hydrodynamics system
  85608. * @class SPHSystem
  85609. * @constructor
  85610. */
  85611. function SPHSystem(){
  85612. this.particles = [];
  85613. /**
  85614. * Density of the system (kg/m3).
  85615. * @property {number} density
  85616. */
  85617. this.density = 1;
  85618. /**
  85619. * Distance below which two particles are considered to be neighbors.
  85620. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  85621. * @property {number} smoothingRadius
  85622. */
  85623. this.smoothingRadius = 1;
  85624. this.speedOfSound = 1;
  85625. /**
  85626. * Viscosity of the system.
  85627. * @property {number} viscosity
  85628. */
  85629. this.viscosity = 0.01;
  85630. this.eps = 0.000001;
  85631. // Stuff Computed per particle
  85632. this.pressures = [];
  85633. this.densities = [];
  85634. this.neighbors = [];
  85635. }
  85636. /**
  85637. * Add a particle to the system.
  85638. * @method add
  85639. * @param {Body} particle
  85640. */
  85641. SPHSystem.prototype.add = function(particle){
  85642. this.particles.push(particle);
  85643. if(this.neighbors.length < this.particles.length){
  85644. this.neighbors.push([]);
  85645. }
  85646. };
  85647. /**
  85648. * Remove a particle from the system.
  85649. * @method remove
  85650. * @param {Body} particle
  85651. */
  85652. SPHSystem.prototype.remove = function(particle){
  85653. var idx = this.particles.indexOf(particle);
  85654. if(idx !== -1){
  85655. this.particles.splice(idx,1);
  85656. if(this.neighbors.length > this.particles.length){
  85657. this.neighbors.pop();
  85658. }
  85659. }
  85660. };
  85661. /**
  85662. * Get neighbors within smoothing volume, save in the array neighbors
  85663. * @method getNeighbors
  85664. * @param {Body} particle
  85665. * @param {Array} neighbors
  85666. */
  85667. var SPHSystem_getNeighbors_dist = new Vec3();
  85668. SPHSystem.prototype.getNeighbors = function(particle,neighbors){
  85669. var N = this.particles.length,
  85670. id = particle.id,
  85671. R2 = this.smoothingRadius * this.smoothingRadius,
  85672. dist = SPHSystem_getNeighbors_dist;
  85673. for(var i=0; i!==N; i++){
  85674. var p = this.particles[i];
  85675. p.position.vsub(particle.position,dist);
  85676. if(id!==p.id && dist.norm2() < R2){
  85677. neighbors.push(p);
  85678. }
  85679. }
  85680. };
  85681. // Temp vectors for calculation
  85682. var SPHSystem_update_dist = new Vec3(),
  85683. SPHSystem_update_a_pressure = new Vec3(),
  85684. SPHSystem_update_a_visc = new Vec3(),
  85685. SPHSystem_update_gradW = new Vec3(),
  85686. SPHSystem_update_r_vec = new Vec3(),
  85687. SPHSystem_update_u = new Vec3(); // Relative velocity
  85688. SPHSystem.prototype.update = function(){
  85689. var N = this.particles.length,
  85690. dist = SPHSystem_update_dist,
  85691. cs = this.speedOfSound,
  85692. eps = this.eps;
  85693. for(var i=0; i!==N; i++){
  85694. var p = this.particles[i]; // Current particle
  85695. var neighbors = this.neighbors[i];
  85696. // Get neighbors
  85697. neighbors.length = 0;
  85698. this.getNeighbors(p,neighbors);
  85699. neighbors.push(this.particles[i]); // Add current too
  85700. var numNeighbors = neighbors.length;
  85701. // Accumulate density for the particle
  85702. var sum = 0.0;
  85703. for(var j=0; j!==numNeighbors; j++){
  85704. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  85705. p.position.vsub(neighbors[j].position, dist);
  85706. var len = dist.norm();
  85707. var weight = this.w(len);
  85708. sum += neighbors[j].mass * weight;
  85709. }
  85710. // Save
  85711. this.densities[i] = sum;
  85712. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  85713. }
  85714. // Add forces
  85715. // Sum to these accelerations
  85716. var a_pressure= SPHSystem_update_a_pressure;
  85717. var a_visc = SPHSystem_update_a_visc;
  85718. var gradW = SPHSystem_update_gradW;
  85719. var r_vec = SPHSystem_update_r_vec;
  85720. var u = SPHSystem_update_u;
  85721. for(var i=0; i!==N; i++){
  85722. var particle = this.particles[i];
  85723. a_pressure.set(0,0,0);
  85724. a_visc.set(0,0,0);
  85725. // Init vars
  85726. var Pij;
  85727. var nabla;
  85728. var Vij;
  85729. // Sum up for all other neighbors
  85730. var neighbors = this.neighbors[i];
  85731. var numNeighbors = neighbors.length;
  85732. //printf("Neighbors: ");
  85733. for(var j=0; j!==numNeighbors; j++){
  85734. var neighbor = neighbors[j];
  85735. //printf("%d ",nj);
  85736. // Get r once for all..
  85737. particle.position.vsub(neighbor.position,r_vec);
  85738. var r = r_vec.norm();
  85739. // Pressure contribution
  85740. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i]*this.densities[i] + eps) + this.pressures[j] / (this.densities[j]*this.densities[j] + eps));
  85741. this.gradw(r_vec, gradW);
  85742. // Add to pressure acceleration
  85743. gradW.mult(Pij , gradW);
  85744. a_pressure.vadd(gradW, a_pressure);
  85745. // Viscosity contribution
  85746. neighbor.velocity.vsub(particle.velocity, u);
  85747. u.mult( 1.0 / (0.0001+this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass , u );
  85748. nabla = this.nablaw(r);
  85749. u.mult(nabla,u);
  85750. // Add to viscosity acceleration
  85751. a_visc.vadd( u, a_visc );
  85752. }
  85753. // Calculate force
  85754. a_visc.mult(particle.mass, a_visc);
  85755. a_pressure.mult(particle.mass, a_pressure);
  85756. // Add force to particles
  85757. particle.force.vadd(a_visc, particle.force);
  85758. particle.force.vadd(a_pressure, particle.force);
  85759. }
  85760. };
  85761. // Calculate the weight using the W(r) weightfunction
  85762. SPHSystem.prototype.w = function(r){
  85763. // 315
  85764. var h = this.smoothingRadius;
  85765. return 315.0/(64.0*Math.PI*Math.pow(h,9)) * Math.pow(h*h-r*r,3);
  85766. };
  85767. // calculate gradient of the weight function
  85768. SPHSystem.prototype.gradw = function(rVec,resultVec){
  85769. var r = rVec.norm(),
  85770. h = this.smoothingRadius;
  85771. rVec.mult(945.0/(32.0*Math.PI*Math.pow(h,9)) * Math.pow((h*h-r*r),2) , resultVec);
  85772. };
  85773. // Calculate nabla(W)
  85774. SPHSystem.prototype.nablaw = function(r){
  85775. var h = this.smoothingRadius;
  85776. var nabla = 945.0/(32.0*Math.PI*Math.pow(h,9)) * (h*h-r*r)*(7*r*r - 3*h*h);
  85777. return nabla;
  85778. };
  85779. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Particle":41,"../shapes/Shape":43}],35:[function(_dereq_,module,exports){
  85780. var Vec3 = _dereq_('../math/Vec3');
  85781. module.exports = Spring;
  85782. /**
  85783. * A spring, connecting two bodies.
  85784. *
  85785. * @class Spring
  85786. * @constructor
  85787. * @param {Body} bodyA
  85788. * @param {Body} bodyB
  85789. * @param {Object} [options]
  85790. * @param {number} [options.restLength] A number > 0. Default: 1
  85791. * @param {number} [options.stiffness] A number >= 0. Default: 100
  85792. * @param {number} [options.damping] A number >= 0. Default: 1
  85793. * @param {Vec3} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates.
  85794. * @param {Vec3} [options.worldAnchorB]
  85795. * @param {Vec3} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates.
  85796. * @param {Vec3} [options.localAnchorB]
  85797. */
  85798. function Spring(bodyA,bodyB,options){
  85799. options = options || {};
  85800. /**
  85801. * Rest length of the spring.
  85802. * @property restLength
  85803. * @type {number}
  85804. */
  85805. this.restLength = typeof(options.restLength) === "number" ? options.restLength : 1;
  85806. /**
  85807. * Stiffness of the spring.
  85808. * @property stiffness
  85809. * @type {number}
  85810. */
  85811. this.stiffness = options.stiffness || 100;
  85812. /**
  85813. * Damping of the spring.
  85814. * @property damping
  85815. * @type {number}
  85816. */
  85817. this.damping = options.damping || 1;
  85818. /**
  85819. * First connected body.
  85820. * @property bodyA
  85821. * @type {Body}
  85822. */
  85823. this.bodyA = bodyA;
  85824. /**
  85825. * Second connected body.
  85826. * @property bodyB
  85827. * @type {Body}
  85828. */
  85829. this.bodyB = bodyB;
  85830. /**
  85831. * Anchor for bodyA in local bodyA coordinates.
  85832. * @property localAnchorA
  85833. * @type {Vec3}
  85834. */
  85835. this.localAnchorA = new Vec3();
  85836. /**
  85837. * Anchor for bodyB in local bodyB coordinates.
  85838. * @property localAnchorB
  85839. * @type {Vec3}
  85840. */
  85841. this.localAnchorB = new Vec3();
  85842. if(options.localAnchorA){
  85843. this.localAnchorA.copy(options.localAnchorA);
  85844. }
  85845. if(options.localAnchorB){
  85846. this.localAnchorB.copy(options.localAnchorB);
  85847. }
  85848. if(options.worldAnchorA){
  85849. this.setWorldAnchorA(options.worldAnchorA);
  85850. }
  85851. if(options.worldAnchorB){
  85852. this.setWorldAnchorB(options.worldAnchorB);
  85853. }
  85854. }
  85855. /**
  85856. * Set the anchor point on body A, using world coordinates.
  85857. * @method setWorldAnchorA
  85858. * @param {Vec3} worldAnchorA
  85859. */
  85860. Spring.prototype.setWorldAnchorA = function(worldAnchorA){
  85861. this.bodyA.pointToLocalFrame(worldAnchorA,this.localAnchorA);
  85862. };
  85863. /**
  85864. * Set the anchor point on body B, using world coordinates.
  85865. * @method setWorldAnchorB
  85866. * @param {Vec3} worldAnchorB
  85867. */
  85868. Spring.prototype.setWorldAnchorB = function(worldAnchorB){
  85869. this.bodyB.pointToLocalFrame(worldAnchorB,this.localAnchorB);
  85870. };
  85871. /**
  85872. * Get the anchor point on body A, in world coordinates.
  85873. * @method getWorldAnchorA
  85874. * @param {Vec3} result The vector to store the result in.
  85875. */
  85876. Spring.prototype.getWorldAnchorA = function(result){
  85877. this.bodyA.pointToWorldFrame(this.localAnchorA,result);
  85878. };
  85879. /**
  85880. * Get the anchor point on body B, in world coordinates.
  85881. * @method getWorldAnchorB
  85882. * @param {Vec3} result The vector to store the result in.
  85883. */
  85884. Spring.prototype.getWorldAnchorB = function(result){
  85885. this.bodyB.pointToWorldFrame(this.localAnchorB,result);
  85886. };
  85887. var applyForce_r = new Vec3(),
  85888. applyForce_r_unit = new Vec3(),
  85889. applyForce_u = new Vec3(),
  85890. applyForce_f = new Vec3(),
  85891. applyForce_worldAnchorA = new Vec3(),
  85892. applyForce_worldAnchorB = new Vec3(),
  85893. applyForce_ri = new Vec3(),
  85894. applyForce_rj = new Vec3(),
  85895. applyForce_ri_x_f = new Vec3(),
  85896. applyForce_rj_x_f = new Vec3(),
  85897. applyForce_tmp = new Vec3();
  85898. /**
  85899. * Apply the spring force to the connected bodies.
  85900. * @method applyForce
  85901. */
  85902. Spring.prototype.applyForce = function(){
  85903. var k = this.stiffness,
  85904. d = this.damping,
  85905. l = this.restLength,
  85906. bodyA = this.bodyA,
  85907. bodyB = this.bodyB,
  85908. r = applyForce_r,
  85909. r_unit = applyForce_r_unit,
  85910. u = applyForce_u,
  85911. f = applyForce_f,
  85912. tmp = applyForce_tmp;
  85913. var worldAnchorA = applyForce_worldAnchorA,
  85914. worldAnchorB = applyForce_worldAnchorB,
  85915. ri = applyForce_ri,
  85916. rj = applyForce_rj,
  85917. ri_x_f = applyForce_ri_x_f,
  85918. rj_x_f = applyForce_rj_x_f;
  85919. // Get world anchors
  85920. this.getWorldAnchorA(worldAnchorA);
  85921. this.getWorldAnchorB(worldAnchorB);
  85922. // Get offset points
  85923. worldAnchorA.vsub(bodyA.position,ri);
  85924. worldAnchorB.vsub(bodyB.position,rj);
  85925. // Compute distance vector between world anchor points
  85926. worldAnchorB.vsub(worldAnchorA,r);
  85927. var rlen = r.norm();
  85928. r_unit.copy(r);
  85929. r_unit.normalize();
  85930. // Compute relative velocity of the anchor points, u
  85931. bodyB.velocity.vsub(bodyA.velocity,u);
  85932. // Add rotational velocity
  85933. bodyB.angularVelocity.cross(rj,tmp);
  85934. u.vadd(tmp,u);
  85935. bodyA.angularVelocity.cross(ri,tmp);
  85936. u.vsub(tmp,u);
  85937. // F = - k * ( x - L ) - D * ( u )
  85938. r_unit.mult(-k*(rlen-l) - d*u.dot(r_unit), f);
  85939. // Add forces to bodies
  85940. bodyA.force.vsub(f,bodyA.force);
  85941. bodyB.force.vadd(f,bodyB.force);
  85942. // Angular force
  85943. ri.cross(f,ri_x_f);
  85944. rj.cross(f,rj_x_f);
  85945. bodyA.torque.vsub(ri_x_f,bodyA.torque);
  85946. bodyB.torque.vadd(rj_x_f,bodyB.torque);
  85947. };
  85948. },{"../math/Vec3":30}],36:[function(_dereq_,module,exports){
  85949. var Vec3 = _dereq_('../math/Vec3');
  85950. var Transform = _dereq_('../math/Transform');
  85951. var RaycastResult = _dereq_('../collision/RaycastResult');
  85952. var Utils = _dereq_('../utils/Utils');
  85953. module.exports = WheelInfo;
  85954. /**
  85955. * @class WheelInfo
  85956. * @constructor
  85957. * @param {Object} [options]
  85958. *
  85959. * @param {Vec3} [options.chassisConnectionPointLocal]
  85960. * @param {Vec3} [options.chassisConnectionPointWorld]
  85961. * @param {Vec3} [options.directionLocal]
  85962. * @param {Vec3} [options.directionWorld]
  85963. * @param {Vec3} [options.axleLocal]
  85964. * @param {Vec3} [options.axleWorld]
  85965. * @param {number} [options.suspensionRestLength=1]
  85966. * @param {number} [options.suspensionMaxLength=2]
  85967. * @param {number} [options.radius=1]
  85968. * @param {number} [options.suspensionStiffness=100]
  85969. * @param {number} [options.dampingCompression=10]
  85970. * @param {number} [options.dampingRelaxation=10]
  85971. * @param {number} [options.frictionSlip=10000]
  85972. * @param {number} [options.steering=0]
  85973. * @param {number} [options.rotation=0]
  85974. * @param {number} [options.deltaRotation=0]
  85975. * @param {number} [options.rollInfluence=0.01]
  85976. * @param {number} [options.maxSuspensionForce]
  85977. * @param {boolean} [options.isFrontWheel=true]
  85978. * @param {number} [options.clippedInvContactDotSuspension=1]
  85979. * @param {number} [options.suspensionRelativeVelocity=0]
  85980. * @param {number} [options.suspensionForce=0]
  85981. * @param {number} [options.skidInfo=0]
  85982. * @param {number} [options.suspensionLength=0]
  85983. * @param {number} [options.maxSuspensionTravel=1]
  85984. * @param {boolean} [options.useCustomSlidingRotationalSpeed=false]
  85985. * @param {number} [options.customSlidingRotationalSpeed=-0.1]
  85986. */
  85987. function WheelInfo(options){
  85988. options = Utils.defaults(options, {
  85989. chassisConnectionPointLocal: new Vec3(),
  85990. chassisConnectionPointWorld: new Vec3(),
  85991. directionLocal: new Vec3(),
  85992. directionWorld: new Vec3(),
  85993. axleLocal: new Vec3(),
  85994. axleWorld: new Vec3(),
  85995. suspensionRestLength: 1,
  85996. suspensionMaxLength: 2,
  85997. radius: 1,
  85998. suspensionStiffness: 100,
  85999. dampingCompression: 10,
  86000. dampingRelaxation: 10,
  86001. frictionSlip: 10000,
  86002. steering: 0,
  86003. rotation: 0,
  86004. deltaRotation: 0,
  86005. rollInfluence: 0.01,
  86006. maxSuspensionForce: Number.MAX_VALUE,
  86007. isFrontWheel: true,
  86008. clippedInvContactDotSuspension: 1,
  86009. suspensionRelativeVelocity: 0,
  86010. suspensionForce: 0,
  86011. skidInfo: 0,
  86012. suspensionLength: 0,
  86013. maxSuspensionTravel: 1,
  86014. useCustomSlidingRotationalSpeed: false,
  86015. customSlidingRotationalSpeed: -0.1
  86016. });
  86017. /**
  86018. * Max travel distance of the suspension, in meters.
  86019. * @property {number} maxSuspensionTravel
  86020. */
  86021. this.maxSuspensionTravel = options.maxSuspensionTravel;
  86022. /**
  86023. * Speed to apply to the wheel rotation when the wheel is sliding.
  86024. * @property {number} customSlidingRotationalSpeed
  86025. */
  86026. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  86027. /**
  86028. * If the customSlidingRotationalSpeed should be used.
  86029. * @property {Boolean} useCustomSlidingRotationalSpeed
  86030. */
  86031. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  86032. /**
  86033. * @property {Boolean} sliding
  86034. */
  86035. this.sliding = false;
  86036. /**
  86037. * Connection point, defined locally in the chassis body frame.
  86038. * @property {Vec3} chassisConnectionPointLocal
  86039. */
  86040. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  86041. /**
  86042. * @property {Vec3} chassisConnectionPointWorld
  86043. */
  86044. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  86045. /**
  86046. * @property {Vec3} directionLocal
  86047. */
  86048. this.directionLocal = options.directionLocal.clone();
  86049. /**
  86050. * @property {Vec3} directionWorld
  86051. */
  86052. this.directionWorld = options.directionWorld.clone();
  86053. /**
  86054. * @property {Vec3} axleLocal
  86055. */
  86056. this.axleLocal = options.axleLocal.clone();
  86057. /**
  86058. * @property {Vec3} axleWorld
  86059. */
  86060. this.axleWorld = options.axleWorld.clone();
  86061. /**
  86062. * @property {number} suspensionRestLength
  86063. */
  86064. this.suspensionRestLength = options.suspensionRestLength;
  86065. /**
  86066. * @property {number} suspensionMaxLength
  86067. */
  86068. this.suspensionMaxLength = options.suspensionMaxLength;
  86069. /**
  86070. * @property {number} radius
  86071. */
  86072. this.radius = options.radius;
  86073. /**
  86074. * @property {number} suspensionStiffness
  86075. */
  86076. this.suspensionStiffness = options.suspensionStiffness;
  86077. /**
  86078. * @property {number} dampingCompression
  86079. */
  86080. this.dampingCompression = options.dampingCompression;
  86081. /**
  86082. * @property {number} dampingRelaxation
  86083. */
  86084. this.dampingRelaxation = options.dampingRelaxation;
  86085. /**
  86086. * @property {number} frictionSlip
  86087. */
  86088. this.frictionSlip = options.frictionSlip;
  86089. /**
  86090. * @property {number} steering
  86091. */
  86092. this.steering = 0;
  86093. /**
  86094. * Rotation value, in radians.
  86095. * @property {number} rotation
  86096. */
  86097. this.rotation = 0;
  86098. /**
  86099. * @property {number} deltaRotation
  86100. */
  86101. this.deltaRotation = 0;
  86102. /**
  86103. * @property {number} rollInfluence
  86104. */
  86105. this.rollInfluence = options.rollInfluence;
  86106. /**
  86107. * @property {number} maxSuspensionForce
  86108. */
  86109. this.maxSuspensionForce = options.maxSuspensionForce;
  86110. /**
  86111. * @property {number} engineForce
  86112. */
  86113. this.engineForce = 0;
  86114. /**
  86115. * @property {number} brake
  86116. */
  86117. this.brake = 0;
  86118. /**
  86119. * @property {number} isFrontWheel
  86120. */
  86121. this.isFrontWheel = options.isFrontWheel;
  86122. /**
  86123. * @property {number} clippedInvContactDotSuspension
  86124. */
  86125. this.clippedInvContactDotSuspension = 1;
  86126. /**
  86127. * @property {number} suspensionRelativeVelocity
  86128. */
  86129. this.suspensionRelativeVelocity = 0;
  86130. /**
  86131. * @property {number} suspensionForce
  86132. */
  86133. this.suspensionForce = 0;
  86134. /**
  86135. * @property {number} skidInfo
  86136. */
  86137. this.skidInfo = 0;
  86138. /**
  86139. * @property {number} suspensionLength
  86140. */
  86141. this.suspensionLength = 0;
  86142. /**
  86143. * @property {number} sideImpulse
  86144. */
  86145. this.sideImpulse = 0;
  86146. /**
  86147. * @property {number} forwardImpulse
  86148. */
  86149. this.forwardImpulse = 0;
  86150. /**
  86151. * The result from raycasting
  86152. * @property {RaycastResult} raycastResult
  86153. */
  86154. this.raycastResult = new RaycastResult();
  86155. /**
  86156. * Wheel world transform
  86157. * @property {Transform} worldTransform
  86158. */
  86159. this.worldTransform = new Transform();
  86160. /**
  86161. * @property {boolean} isInContact
  86162. */
  86163. this.isInContact = false;
  86164. }
  86165. var chassis_velocity_at_contactPoint = new Vec3();
  86166. var relpos = new Vec3();
  86167. var chassis_velocity_at_contactPoint = new Vec3();
  86168. WheelInfo.prototype.updateWheel = function(chassis){
  86169. var raycastResult = this.raycastResult;
  86170. if (this.isInContact){
  86171. var project= raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  86172. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  86173. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  86174. var projVel = raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  86175. if (project >= -0.1) {
  86176. this.suspensionRelativeVelocity = 0.0;
  86177. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  86178. } else {
  86179. var inv = -1 / project;
  86180. this.suspensionRelativeVelocity = projVel * inv;
  86181. this.clippedInvContactDotSuspension = inv;
  86182. }
  86183. } else {
  86184. // Not in contact : position wheel in a nice (rest length) position
  86185. raycastResult.suspensionLength = this.suspensionRestLength;
  86186. this.suspensionRelativeVelocity = 0.0;
  86187. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  86188. this.clippedInvContactDotSuspension = 1.0;
  86189. }
  86190. };
  86191. },{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(_dereq_,module,exports){
  86192. module.exports = Box;
  86193. var Shape = _dereq_('./Shape');
  86194. var Vec3 = _dereq_('../math/Vec3');
  86195. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  86196. /**
  86197. * A 3d box shape.
  86198. * @class Box
  86199. * @constructor
  86200. * @param {Vec3} halfExtents
  86201. * @author schteppe
  86202. * @extends Shape
  86203. */
  86204. function Box(halfExtents){
  86205. Shape.call(this);
  86206. this.type = Shape.types.BOX;
  86207. /**
  86208. * @property halfExtents
  86209. * @type {Vec3}
  86210. */
  86211. this.halfExtents = halfExtents;
  86212. /**
  86213. * Used by the contact generator to make contacts with other convex polyhedra for example
  86214. * @property convexPolyhedronRepresentation
  86215. * @type {ConvexPolyhedron}
  86216. */
  86217. this.convexPolyhedronRepresentation = null;
  86218. this.updateConvexPolyhedronRepresentation();
  86219. this.updateBoundingSphereRadius();
  86220. }
  86221. Box.prototype = new Shape();
  86222. Box.prototype.constructor = Box;
  86223. /**
  86224. * Updates the local convex polyhedron representation used for some collisions.
  86225. * @method updateConvexPolyhedronRepresentation
  86226. */
  86227. Box.prototype.updateConvexPolyhedronRepresentation = function(){
  86228. var sx = this.halfExtents.x;
  86229. var sy = this.halfExtents.y;
  86230. var sz = this.halfExtents.z;
  86231. var V = Vec3;
  86232. var vertices = [
  86233. new V(-sx,-sy,-sz),
  86234. new V( sx,-sy,-sz),
  86235. new V( sx, sy,-sz),
  86236. new V(-sx, sy,-sz),
  86237. new V(-sx,-sy, sz),
  86238. new V( sx,-sy, sz),
  86239. new V( sx, sy, sz),
  86240. new V(-sx, sy, sz)
  86241. ];
  86242. var indices = [
  86243. [3,2,1,0], // -z
  86244. [4,5,6,7], // +z
  86245. [5,4,0,1], // -y
  86246. [2,3,7,6], // +y
  86247. [0,4,7,3], // -x
  86248. [1,2,6,5], // +x
  86249. ];
  86250. var axes = [
  86251. new V(0, 0, 1),
  86252. new V(0, 1, 0),
  86253. new V(1, 0, 0)
  86254. ];
  86255. var h = new ConvexPolyhedron(vertices, indices);
  86256. this.convexPolyhedronRepresentation = h;
  86257. h.material = this.material;
  86258. };
  86259. /**
  86260. * @method calculateLocalInertia
  86261. * @param {Number} mass
  86262. * @param {Vec3} target
  86263. * @return {Vec3}
  86264. */
  86265. Box.prototype.calculateLocalInertia = function(mass,target){
  86266. target = target || new Vec3();
  86267. Box.calculateInertia(this.halfExtents, mass, target);
  86268. return target;
  86269. };
  86270. Box.calculateInertia = function(halfExtents,mass,target){
  86271. var e = halfExtents;
  86272. target.x = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.z*2*e.z );
  86273. target.y = 1.0 / 12.0 * mass * ( 2*e.x*2*e.x + 2*e.z*2*e.z );
  86274. target.z = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.x*2*e.x );
  86275. };
  86276. /**
  86277. * Get the box 6 side normals
  86278. * @method getSideNormals
  86279. * @param {array} sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  86280. * @param {Quaternion} quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  86281. * @return {array}
  86282. */
  86283. Box.prototype.getSideNormals = function(sixTargetVectors,quat){
  86284. var sides = sixTargetVectors;
  86285. var ex = this.halfExtents;
  86286. sides[0].set( ex.x, 0, 0);
  86287. sides[1].set( 0, ex.y, 0);
  86288. sides[2].set( 0, 0, ex.z);
  86289. sides[3].set( -ex.x, 0, 0);
  86290. sides[4].set( 0, -ex.y, 0);
  86291. sides[5].set( 0, 0, -ex.z);
  86292. if(quat!==undefined){
  86293. for(var i=0; i!==sides.length; i++){
  86294. quat.vmult(sides[i],sides[i]);
  86295. }
  86296. }
  86297. return sides;
  86298. };
  86299. Box.prototype.volume = function(){
  86300. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  86301. };
  86302. Box.prototype.updateBoundingSphereRadius = function(){
  86303. this.boundingSphereRadius = this.halfExtents.norm();
  86304. };
  86305. var worldCornerTempPos = new Vec3();
  86306. var worldCornerTempNeg = new Vec3();
  86307. Box.prototype.forEachWorldCorner = function(pos,quat,callback){
  86308. var e = this.halfExtents;
  86309. var corners = [[ e.x, e.y, e.z],
  86310. [ -e.x, e.y, e.z],
  86311. [ -e.x, -e.y, e.z],
  86312. [ -e.x, -e.y, -e.z],
  86313. [ e.x, -e.y, -e.z],
  86314. [ e.x, e.y, -e.z],
  86315. [ -e.x, e.y, -e.z],
  86316. [ e.x, -e.y, e.z]];
  86317. for(var i=0; i<corners.length; i++){
  86318. worldCornerTempPos.set(corners[i][0],corners[i][1],corners[i][2]);
  86319. quat.vmult(worldCornerTempPos,worldCornerTempPos);
  86320. pos.vadd(worldCornerTempPos,worldCornerTempPos);
  86321. callback(worldCornerTempPos.x,
  86322. worldCornerTempPos.y,
  86323. worldCornerTempPos.z);
  86324. }
  86325. };
  86326. var worldCornersTemp = [
  86327. new Vec3(),
  86328. new Vec3(),
  86329. new Vec3(),
  86330. new Vec3(),
  86331. new Vec3(),
  86332. new Vec3(),
  86333. new Vec3(),
  86334. new Vec3()
  86335. ];
  86336. Box.prototype.calculateWorldAABB = function(pos,quat,min,max){
  86337. var e = this.halfExtents;
  86338. worldCornersTemp[0].set(e.x, e.y, e.z);
  86339. worldCornersTemp[1].set(-e.x, e.y, e.z);
  86340. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  86341. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  86342. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  86343. worldCornersTemp[5].set(e.x, e.y, -e.z);
  86344. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  86345. worldCornersTemp[7].set(e.x, -e.y, e.z);
  86346. var wc = worldCornersTemp[0];
  86347. quat.vmult(wc, wc);
  86348. pos.vadd(wc, wc);
  86349. max.copy(wc);
  86350. min.copy(wc);
  86351. for(var i=1; i<8; i++){
  86352. var wc = worldCornersTemp[i];
  86353. quat.vmult(wc, wc);
  86354. pos.vadd(wc, wc);
  86355. var x = wc.x;
  86356. var y = wc.y;
  86357. var z = wc.z;
  86358. if(x > max.x){
  86359. max.x = x;
  86360. }
  86361. if(y > max.y){
  86362. max.y = y;
  86363. }
  86364. if(z > max.z){
  86365. max.z = z;
  86366. }
  86367. if(x < min.x){
  86368. min.x = x;
  86369. }
  86370. if(y < min.y){
  86371. min.y = y;
  86372. }
  86373. if(z < min.z){
  86374. min.z = z;
  86375. }
  86376. }
  86377. // Get each axis max
  86378. // min.set(Infinity,Infinity,Infinity);
  86379. // max.set(-Infinity,-Infinity,-Infinity);
  86380. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  86381. // if(x > max.x){
  86382. // max.x = x;
  86383. // }
  86384. // if(y > max.y){
  86385. // max.y = y;
  86386. // }
  86387. // if(z > max.z){
  86388. // max.z = z;
  86389. // }
  86390. // if(x < min.x){
  86391. // min.x = x;
  86392. // }
  86393. // if(y < min.y){
  86394. // min.y = y;
  86395. // }
  86396. // if(z < min.z){
  86397. // min.z = z;
  86398. // }
  86399. // });
  86400. };
  86401. },{"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],38:[function(_dereq_,module,exports){
  86402. module.exports = ConvexPolyhedron;
  86403. var Shape = _dereq_('./Shape');
  86404. var Vec3 = _dereq_('../math/Vec3');
  86405. var Quaternion = _dereq_('../math/Quaternion');
  86406. var Transform = _dereq_('../math/Transform');
  86407. /**
  86408. * A set of polygons describing a convex shape.
  86409. * @class ConvexPolyhedron
  86410. * @constructor
  86411. * @extends Shape
  86412. * @description The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  86413. * in the same 3D plane), instead these should be merged into one polygon.
  86414. *
  86415. * @param {array} points An array of Vec3's
  86416. * @param {array} faces Array of integer arrays, describing which vertices that is included in each face.
  86417. *
  86418. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  86419. * @author schteppe / https://github.com/schteppe
  86420. * @see http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  86421. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  86422. *
  86423. * @todo Move the clipping functions to ContactGenerator?
  86424. * @todo Automatically merge coplanar polygons in constructor.
  86425. */
  86426. function ConvexPolyhedron(points, faces, uniqueAxes) {
  86427. var that = this;
  86428. Shape.call(this);
  86429. this.type = Shape.types.CONVEXPOLYHEDRON;
  86430. /**
  86431. * Array of Vec3
  86432. * @property vertices
  86433. * @type {Array}
  86434. */
  86435. this.vertices = points||[];
  86436. this.worldVertices = []; // World transformed version of .vertices
  86437. this.worldVerticesNeedsUpdate = true;
  86438. /**
  86439. * Array of integer arrays, indicating which vertices each face consists of
  86440. * @property faces
  86441. * @type {Array}
  86442. */
  86443. this.faces = faces||[];
  86444. /**
  86445. * Array of Vec3
  86446. * @property faceNormals
  86447. * @type {Array}
  86448. */
  86449. this.faceNormals = [];
  86450. this.computeNormals();
  86451. this.worldFaceNormalsNeedsUpdate = true;
  86452. this.worldFaceNormals = []; // World transformed version of .faceNormals
  86453. /**
  86454. * Array of Vec3
  86455. * @property uniqueEdges
  86456. * @type {Array}
  86457. */
  86458. this.uniqueEdges = [];
  86459. /**
  86460. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  86461. * @property {Array} uniqueAxes
  86462. */
  86463. this.uniqueAxes = uniqueAxes ? uniqueAxes.slice() : null;
  86464. this.computeEdges();
  86465. this.updateBoundingSphereRadius();
  86466. }
  86467. ConvexPolyhedron.prototype = new Shape();
  86468. ConvexPolyhedron.prototype.constructor = ConvexPolyhedron;
  86469. var computeEdges_tmpEdge = new Vec3();
  86470. /**
  86471. * Computes uniqueEdges
  86472. * @method computeEdges
  86473. */
  86474. ConvexPolyhedron.prototype.computeEdges = function(){
  86475. var faces = this.faces;
  86476. var vertices = this.vertices;
  86477. var nv = vertices.length;
  86478. var edges = this.uniqueEdges;
  86479. edges.length = 0;
  86480. var edge = computeEdges_tmpEdge;
  86481. for(var i=0; i !== faces.length; i++){
  86482. var face = faces[i];
  86483. var numVertices = face.length;
  86484. for(var j = 0; j !== numVertices; j++){
  86485. var k = ( j+1 ) % numVertices;
  86486. vertices[face[j]].vsub(vertices[face[k]], edge);
  86487. edge.normalize();
  86488. var found = false;
  86489. for(var p=0; p !== edges.length; p++){
  86490. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)){
  86491. found = true;
  86492. break;
  86493. }
  86494. }
  86495. if (!found){
  86496. edges.push(edge.clone());
  86497. }
  86498. }
  86499. }
  86500. };
  86501. /**
  86502. * Compute the normals of the faces. Will reuse existing Vec3 objects in the .faceNormals array if they exist.
  86503. * @method computeNormals
  86504. */
  86505. ConvexPolyhedron.prototype.computeNormals = function(){
  86506. this.faceNormals.length = this.faces.length;
  86507. // Generate normals
  86508. for(var i=0; i<this.faces.length; i++){
  86509. // Check so all vertices exists for this face
  86510. for(var j=0; j<this.faces[i].length; j++){
  86511. if(!this.vertices[this.faces[i][j]]){
  86512. throw new Error("Vertex "+this.faces[i][j]+" not found!");
  86513. }
  86514. }
  86515. var n = this.faceNormals[i] || new Vec3();
  86516. this.getFaceNormal(i,n);
  86517. n.negate(n);
  86518. this.faceNormals[i] = n;
  86519. var vertex = this.vertices[this.faces[i][0]];
  86520. if(n.dot(vertex) < 0){
  86521. 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.");
  86522. for(var j=0; j<this.faces[i].length; j++){
  86523. console.warn(".vertices["+this.faces[i][j]+"] = Vec3("+this.vertices[this.faces[i][j]].toString()+")");
  86524. }
  86525. }
  86526. }
  86527. };
  86528. /**
  86529. * Get face normal given 3 vertices
  86530. * @static
  86531. * @method getFaceNormal
  86532. * @param {Vec3} va
  86533. * @param {Vec3} vb
  86534. * @param {Vec3} vc
  86535. * @param {Vec3} target
  86536. */
  86537. var cb = new Vec3();
  86538. var ab = new Vec3();
  86539. ConvexPolyhedron.computeNormal = function ( va, vb, vc, target ) {
  86540. vb.vsub(va,ab);
  86541. vc.vsub(vb,cb);
  86542. cb.cross(ab,target);
  86543. if ( !target.isZero() ) {
  86544. target.normalize();
  86545. }
  86546. };
  86547. /**
  86548. * Compute the normal of a face from its vertices
  86549. * @method getFaceNormal
  86550. * @param {Number} i
  86551. * @param {Vec3} target
  86552. */
  86553. ConvexPolyhedron.prototype.getFaceNormal = function(i,target){
  86554. var f = this.faces[i];
  86555. var va = this.vertices[f[0]];
  86556. var vb = this.vertices[f[1]];
  86557. var vc = this.vertices[f[2]];
  86558. return ConvexPolyhedron.computeNormal(va,vb,vc,target);
  86559. };
  86560. /**
  86561. * @method clipAgainstHull
  86562. * @param {Vec3} posA
  86563. * @param {Quaternion} quatA
  86564. * @param {ConvexPolyhedron} hullB
  86565. * @param {Vec3} posB
  86566. * @param {Quaternion} quatB
  86567. * @param {Vec3} separatingNormal
  86568. * @param {Number} minDist Clamp distance
  86569. * @param {Number} maxDist
  86570. * @param {array} result The an array of contact point objects, see clipFaceAgainstHull
  86571. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  86572. */
  86573. var cah_WorldNormal = new Vec3();
  86574. ConvexPolyhedron.prototype.clipAgainstHull = function(posA,quatA,hullB,posB,quatB,separatingNormal,minDist,maxDist,result){
  86575. var WorldNormal = cah_WorldNormal;
  86576. var hullA = this;
  86577. var curMaxDist = maxDist;
  86578. var closestFaceB = -1;
  86579. var dmax = -Number.MAX_VALUE;
  86580. for(var face=0; face < hullB.faces.length; face++){
  86581. WorldNormal.copy(hullB.faceNormals[face]);
  86582. quatB.vmult(WorldNormal,WorldNormal);
  86583. //posB.vadd(WorldNormal,WorldNormal);
  86584. var d = WorldNormal.dot(separatingNormal);
  86585. if (d > dmax){
  86586. dmax = d;
  86587. closestFaceB = face;
  86588. }
  86589. }
  86590. var worldVertsB1 = [];
  86591. var polyB = hullB.faces[closestFaceB];
  86592. var numVertices = polyB.length;
  86593. for(var e0=0; e0<numVertices; e0++){
  86594. var b = hullB.vertices[polyB[e0]];
  86595. var worldb = new Vec3();
  86596. worldb.copy(b);
  86597. quatB.vmult(worldb,worldb);
  86598. posB.vadd(worldb,worldb);
  86599. worldVertsB1.push(worldb);
  86600. }
  86601. if (closestFaceB>=0){
  86602. this.clipFaceAgainstHull(separatingNormal,
  86603. posA,
  86604. quatA,
  86605. worldVertsB1,
  86606. minDist,
  86607. maxDist,
  86608. result);
  86609. }
  86610. };
  86611. /**
  86612. * Find the separating axis between this hull and another
  86613. * @method findSeparatingAxis
  86614. * @param {ConvexPolyhedron} hullB
  86615. * @param {Vec3} posA
  86616. * @param {Quaternion} quatA
  86617. * @param {Vec3} posB
  86618. * @param {Quaternion} quatB
  86619. * @param {Vec3} target The target vector to save the axis in
  86620. * @return {bool} Returns false if a separation is found, else true
  86621. */
  86622. var fsa_faceANormalWS3 = new Vec3(),
  86623. fsa_Worldnormal1 = new Vec3(),
  86624. fsa_deltaC = new Vec3(),
  86625. fsa_worldEdge0 = new Vec3(),
  86626. fsa_worldEdge1 = new Vec3(),
  86627. fsa_Cross = new Vec3();
  86628. ConvexPolyhedron.prototype.findSeparatingAxis = function(hullB,posA,quatA,posB,quatB,target, faceListA, faceListB){
  86629. var faceANormalWS3 = fsa_faceANormalWS3,
  86630. Worldnormal1 = fsa_Worldnormal1,
  86631. deltaC = fsa_deltaC,
  86632. worldEdge0 = fsa_worldEdge0,
  86633. worldEdge1 = fsa_worldEdge1,
  86634. Cross = fsa_Cross;
  86635. var dmin = Number.MAX_VALUE;
  86636. var hullA = this;
  86637. var curPlaneTests=0;
  86638. if(!hullA.uniqueAxes){
  86639. var numFacesA = faceListA ? faceListA.length : hullA.faces.length;
  86640. // Test face normals from hullA
  86641. for(var i=0; i<numFacesA; i++){
  86642. var fi = faceListA ? faceListA[i] : i;
  86643. // Get world face normal
  86644. faceANormalWS3.copy(hullA.faceNormals[fi]);
  86645. quatA.vmult(faceANormalWS3,faceANormalWS3);
  86646. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  86647. if(d===false){
  86648. return false;
  86649. }
  86650. if(d<dmin){
  86651. dmin = d;
  86652. target.copy(faceANormalWS3);
  86653. }
  86654. }
  86655. } else {
  86656. // Test unique axes
  86657. for(var i = 0; i !== hullA.uniqueAxes.length; i++){
  86658. // Get world axis
  86659. quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3);
  86660. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  86661. if(d===false){
  86662. return false;
  86663. }
  86664. if(d<dmin){
  86665. dmin = d;
  86666. target.copy(faceANormalWS3);
  86667. }
  86668. }
  86669. }
  86670. if(!hullB.uniqueAxes){
  86671. // Test face normals from hullB
  86672. var numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  86673. for(var i=0;i<numFacesB;i++){
  86674. var fi = faceListB ? faceListB[i] : i;
  86675. Worldnormal1.copy(hullB.faceNormals[fi]);
  86676. quatB.vmult(Worldnormal1,Worldnormal1);
  86677. curPlaneTests++;
  86678. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  86679. if(d===false){
  86680. return false;
  86681. }
  86682. if(d<dmin){
  86683. dmin = d;
  86684. target.copy(Worldnormal1);
  86685. }
  86686. }
  86687. } else {
  86688. // Test unique axes in B
  86689. for(var i = 0; i !== hullB.uniqueAxes.length; i++){
  86690. quatB.vmult(hullB.uniqueAxes[i],Worldnormal1);
  86691. curPlaneTests++;
  86692. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  86693. if(d===false){
  86694. return false;
  86695. }
  86696. if(d<dmin){
  86697. dmin = d;
  86698. target.copy(Worldnormal1);
  86699. }
  86700. }
  86701. }
  86702. // Test edges
  86703. for(var e0=0; e0 !== hullA.uniqueEdges.length; e0++){
  86704. // Get world edge
  86705. quatA.vmult(hullA.uniqueEdges[e0],worldEdge0);
  86706. for(var e1=0; e1 !== hullB.uniqueEdges.length; e1++){
  86707. // Get world edge 2
  86708. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  86709. worldEdge0.cross(worldEdge1,Cross);
  86710. if(!Cross.almostZero()){
  86711. Cross.normalize();
  86712. var dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  86713. if(dist === false){
  86714. return false;
  86715. }
  86716. if(dist < dmin){
  86717. dmin = dist;
  86718. target.copy(Cross);
  86719. }
  86720. }
  86721. }
  86722. }
  86723. posB.vsub(posA,deltaC);
  86724. if((deltaC.dot(target))>0.0){
  86725. target.negate(target);
  86726. }
  86727. return true;
  86728. };
  86729. var maxminA=[], maxminB=[];
  86730. /**
  86731. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  86732. * @method testSepAxis
  86733. * @param {Vec3} axis
  86734. * @param {ConvexPolyhedron} hullB
  86735. * @param {Vec3} posA
  86736. * @param {Quaternion} quatA
  86737. * @param {Vec3} posB
  86738. * @param {Quaternion} quatB
  86739. * @return {number} The overlap depth, or FALSE if no penetration.
  86740. */
  86741. ConvexPolyhedron.prototype.testSepAxis = function(axis, hullB, posA, quatA, posB, quatB){
  86742. var hullA=this;
  86743. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  86744. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  86745. var maxA = maxminA[0];
  86746. var minA = maxminA[1];
  86747. var maxB = maxminB[0];
  86748. var minB = maxminB[1];
  86749. if(maxA<minB || maxB<minA){
  86750. return false; // Separated
  86751. }
  86752. var d0 = maxA - minB;
  86753. var d1 = maxB - minA;
  86754. var depth = d0<d1 ? d0:d1;
  86755. return depth;
  86756. };
  86757. var cli_aabbmin = new Vec3(),
  86758. cli_aabbmax = new Vec3();
  86759. /**
  86760. * @method calculateLocalInertia
  86761. * @param {Number} mass
  86762. * @param {Vec3} target
  86763. */
  86764. ConvexPolyhedron.prototype.calculateLocalInertia = function(mass,target){
  86765. // Approximate with box inertia
  86766. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  86767. this.computeLocalAABB(cli_aabbmin,cli_aabbmax);
  86768. var x = cli_aabbmax.x - cli_aabbmin.x,
  86769. y = cli_aabbmax.y - cli_aabbmin.y,
  86770. z = cli_aabbmax.z - cli_aabbmin.z;
  86771. target.x = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z );
  86772. target.y = 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z );
  86773. target.z = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x );
  86774. };
  86775. /**
  86776. * @method getPlaneConstantOfFace
  86777. * @param {Number} face_i Index of the face
  86778. * @return {Number}
  86779. */
  86780. ConvexPolyhedron.prototype.getPlaneConstantOfFace = function(face_i){
  86781. var f = this.faces[face_i];
  86782. var n = this.faceNormals[face_i];
  86783. var v = this.vertices[f[0]];
  86784. var c = -n.dot(v);
  86785. return c;
  86786. };
  86787. /**
  86788. * Clip a face against a hull.
  86789. * @method clipFaceAgainstHull
  86790. * @param {Vec3} separatingNormal
  86791. * @param {Vec3} posA
  86792. * @param {Quaternion} quatA
  86793. * @param {Array} worldVertsB1 An array of Vec3 with vertices in the world frame.
  86794. * @param {Number} minDist Distance clamping
  86795. * @param {Number} maxDist
  86796. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  86797. */
  86798. var cfah_faceANormalWS = new Vec3(),
  86799. cfah_edge0 = new Vec3(),
  86800. cfah_WorldEdge0 = new Vec3(),
  86801. cfah_worldPlaneAnormal1 = new Vec3(),
  86802. cfah_planeNormalWS1 = new Vec3(),
  86803. cfah_worldA1 = new Vec3(),
  86804. cfah_localPlaneNormal = new Vec3(),
  86805. cfah_planeNormalWS = new Vec3();
  86806. ConvexPolyhedron.prototype.clipFaceAgainstHull = function(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist,result){
  86807. var faceANormalWS = cfah_faceANormalWS,
  86808. edge0 = cfah_edge0,
  86809. WorldEdge0 = cfah_WorldEdge0,
  86810. worldPlaneAnormal1 = cfah_worldPlaneAnormal1,
  86811. planeNormalWS1 = cfah_planeNormalWS1,
  86812. worldA1 = cfah_worldA1,
  86813. localPlaneNormal = cfah_localPlaneNormal,
  86814. planeNormalWS = cfah_planeNormalWS;
  86815. var hullA = this;
  86816. var worldVertsB2 = [];
  86817. var pVtxIn = worldVertsB1;
  86818. var pVtxOut = worldVertsB2;
  86819. // Find the face with normal closest to the separating axis
  86820. var closestFaceA = -1;
  86821. var dmin = Number.MAX_VALUE;
  86822. for(var face=0; face<hullA.faces.length; face++){
  86823. faceANormalWS.copy(hullA.faceNormals[face]);
  86824. quatA.vmult(faceANormalWS,faceANormalWS);
  86825. //posA.vadd(faceANormalWS,faceANormalWS);
  86826. var d = faceANormalWS.dot(separatingNormal);
  86827. if (d < dmin){
  86828. dmin = d;
  86829. closestFaceA = face;
  86830. }
  86831. }
  86832. if (closestFaceA < 0){
  86833. // console.log("--- did not find any closest face... ---");
  86834. return;
  86835. }
  86836. //console.log("closest A: ",closestFaceA);
  86837. // Get the face and construct connected faces
  86838. var polyA = hullA.faces[closestFaceA];
  86839. polyA.connectedFaces = [];
  86840. for(var i=0; i<hullA.faces.length; i++){
  86841. for(var j=0; j<hullA.faces[i].length; j++){
  86842. 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 */ ){
  86843. polyA.connectedFaces.push(i);
  86844. }
  86845. }
  86846. }
  86847. // Clip the polygon to the back of the planes of all faces of hull A, that are adjacent to the witness face
  86848. var numContacts = pVtxIn.length;
  86849. var numVerticesA = polyA.length;
  86850. var res = [];
  86851. for(var e0=0; e0<numVerticesA; e0++){
  86852. var a = hullA.vertices[polyA[e0]];
  86853. var b = hullA.vertices[polyA[(e0+1)%numVerticesA]];
  86854. a.vsub(b,edge0);
  86855. WorldEdge0.copy(edge0);
  86856. quatA.vmult(WorldEdge0,WorldEdge0);
  86857. posA.vadd(WorldEdge0,WorldEdge0);
  86858. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);//transA.getBasis()* btVector3(polyA.m_plane[0],polyA.m_plane[1],polyA.m_plane[2]);
  86859. quatA.vmult(worldPlaneAnormal1,worldPlaneAnormal1);
  86860. posA.vadd(worldPlaneAnormal1,worldPlaneAnormal1);
  86861. WorldEdge0.cross(worldPlaneAnormal1,planeNormalWS1);
  86862. planeNormalWS1.negate(planeNormalWS1);
  86863. worldA1.copy(a);
  86864. quatA.vmult(worldA1,worldA1);
  86865. posA.vadd(worldA1,worldA1);
  86866. var planeEqWS1 = -worldA1.dot(planeNormalWS1);
  86867. var planeEqWS;
  86868. if(true){
  86869. var otherFace = polyA.connectedFaces[e0];
  86870. localPlaneNormal.copy(this.faceNormals[otherFace]);
  86871. var localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  86872. planeNormalWS.copy(localPlaneNormal);
  86873. quatA.vmult(planeNormalWS,planeNormalWS);
  86874. //posA.vadd(planeNormalWS,planeNormalWS);
  86875. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  86876. } else {
  86877. planeNormalWS.copy(planeNormalWS1);
  86878. planeEqWS = planeEqWS1;
  86879. }
  86880. // Clip face against our constructed plane
  86881. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS);
  86882. // Throw away all clipped points, but save the reamining until next clip
  86883. while(pVtxIn.length){
  86884. pVtxIn.shift();
  86885. }
  86886. while(pVtxOut.length){
  86887. pVtxIn.push(pVtxOut.shift());
  86888. }
  86889. }
  86890. //console.log("Resulting points after clip:",pVtxIn);
  86891. // only keep contact points that are behind the witness face
  86892. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  86893. var localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  86894. planeNormalWS.copy(localPlaneNormal);
  86895. quatA.vmult(planeNormalWS,planeNormalWS);
  86896. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  86897. for (var i=0; i<pVtxIn.length; i++){
  86898. var depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; //???
  86899. /*console.log("depth calc from normal=",planeNormalWS.toString()," and constant "+planeEqWS+" and vertex ",pVtxIn[i].toString()," gives "+depth);*/
  86900. if (depth <=minDist){
  86901. console.log("clamped: depth="+depth+" to minDist="+(minDist+""));
  86902. depth = minDist;
  86903. }
  86904. if (depth <=maxDist){
  86905. var point = pVtxIn[i];
  86906. if(depth<=0){
  86907. /*console.log("Got contact point ",point.toString(),
  86908. ", depth=",depth,
  86909. "contact normal=",separatingNormal.toString(),
  86910. "plane",planeNormalWS.toString(),
  86911. "planeConstant",planeEqWS);*/
  86912. var p = {
  86913. point:point,
  86914. normal:planeNormalWS,
  86915. depth: depth,
  86916. };
  86917. result.push(p);
  86918. }
  86919. }
  86920. }
  86921. };
  86922. /**
  86923. * Clip a face in a hull against the back of a plane.
  86924. * @method clipFaceAgainstPlane
  86925. * @param {Array} inVertices
  86926. * @param {Array} outVertices
  86927. * @param {Vec3} planeNormal
  86928. * @param {Number} planeConstant The constant in the mathematical plane equation
  86929. */
  86930. ConvexPolyhedron.prototype.clipFaceAgainstPlane = function(inVertices,outVertices, planeNormal, planeConstant){
  86931. var n_dot_first, n_dot_last;
  86932. var numVerts = inVertices.length;
  86933. if(numVerts < 2){
  86934. return outVertices;
  86935. }
  86936. var firstVertex = inVertices[inVertices.length-1],
  86937. lastVertex = inVertices[0];
  86938. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  86939. for(var vi = 0; vi < numVerts; vi++){
  86940. lastVertex = inVertices[vi];
  86941. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  86942. if(n_dot_first < 0){
  86943. if(n_dot_last < 0){
  86944. // Start < 0, end < 0, so output lastVertex
  86945. var newv = new Vec3();
  86946. newv.copy(lastVertex);
  86947. outVertices.push(newv);
  86948. } else {
  86949. // Start < 0, end >= 0, so output intersection
  86950. var newv = new Vec3();
  86951. firstVertex.lerp(lastVertex,
  86952. n_dot_first / (n_dot_first - n_dot_last),
  86953. newv);
  86954. outVertices.push(newv);
  86955. }
  86956. } else {
  86957. if(n_dot_last<0){
  86958. // Start >= 0, end < 0 so output intersection and end
  86959. var newv = new Vec3();
  86960. firstVertex.lerp(lastVertex,
  86961. n_dot_first / (n_dot_first - n_dot_last),
  86962. newv);
  86963. outVertices.push(newv);
  86964. outVertices.push(lastVertex);
  86965. }
  86966. }
  86967. firstVertex = lastVertex;
  86968. n_dot_first = n_dot_last;
  86969. }
  86970. return outVertices;
  86971. };
  86972. // Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  86973. ConvexPolyhedron.prototype.computeWorldVertices = function(position,quat){
  86974. var N = this.vertices.length;
  86975. while(this.worldVertices.length < N){
  86976. this.worldVertices.push( new Vec3() );
  86977. }
  86978. var verts = this.vertices,
  86979. worldVerts = this.worldVertices;
  86980. for(var i=0; i!==N; i++){
  86981. quat.vmult( verts[i] , worldVerts[i] );
  86982. position.vadd( worldVerts[i] , worldVerts[i] );
  86983. }
  86984. this.worldVerticesNeedsUpdate = false;
  86985. };
  86986. var computeLocalAABB_worldVert = new Vec3();
  86987. ConvexPolyhedron.prototype.computeLocalAABB = function(aabbmin,aabbmax){
  86988. var n = this.vertices.length,
  86989. vertices = this.vertices,
  86990. worldVert = computeLocalAABB_worldVert;
  86991. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86992. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86993. for(var i=0; i<n; i++){
  86994. var v = vertices[i];
  86995. if (v.x < aabbmin.x){
  86996. aabbmin.x = v.x;
  86997. } else if(v.x > aabbmax.x){
  86998. aabbmax.x = v.x;
  86999. }
  87000. if (v.y < aabbmin.y){
  87001. aabbmin.y = v.y;
  87002. } else if(v.y > aabbmax.y){
  87003. aabbmax.y = v.y;
  87004. }
  87005. if (v.z < aabbmin.z){
  87006. aabbmin.z = v.z;
  87007. } else if(v.z > aabbmax.z){
  87008. aabbmax.z = v.z;
  87009. }
  87010. }
  87011. };
  87012. /**
  87013. * Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  87014. * @method computeWorldFaceNormals
  87015. * @param {Quaternion} quat
  87016. */
  87017. ConvexPolyhedron.prototype.computeWorldFaceNormals = function(quat){
  87018. var N = this.faceNormals.length;
  87019. while(this.worldFaceNormals.length < N){
  87020. this.worldFaceNormals.push( new Vec3() );
  87021. }
  87022. var normals = this.faceNormals,
  87023. worldNormals = this.worldFaceNormals;
  87024. for(var i=0; i!==N; i++){
  87025. quat.vmult( normals[i] , worldNormals[i] );
  87026. }
  87027. this.worldFaceNormalsNeedsUpdate = false;
  87028. };
  87029. /**
  87030. * @method updateBoundingSphereRadius
  87031. */
  87032. ConvexPolyhedron.prototype.updateBoundingSphereRadius = function(){
  87033. // Assume points are distributed with local (0,0,0) as center
  87034. var max2 = 0;
  87035. var verts = this.vertices;
  87036. for(var i=0, N=verts.length; i!==N; i++) {
  87037. var norm2 = verts[i].norm2();
  87038. if(norm2 > max2){
  87039. max2 = norm2;
  87040. }
  87041. }
  87042. this.boundingSphereRadius = Math.sqrt(max2);
  87043. };
  87044. var tempWorldVertex = new Vec3();
  87045. /**
  87046. * @method calculateWorldAABB
  87047. * @param {Vec3} pos
  87048. * @param {Quaternion} quat
  87049. * @param {Vec3} min
  87050. * @param {Vec3} max
  87051. */
  87052. ConvexPolyhedron.prototype.calculateWorldAABB = function(pos,quat,min,max){
  87053. var n = this.vertices.length, verts = this.vertices;
  87054. var minx,miny,minz,maxx,maxy,maxz;
  87055. for(var i=0; i<n; i++){
  87056. tempWorldVertex.copy(verts[i]);
  87057. quat.vmult(tempWorldVertex,tempWorldVertex);
  87058. pos.vadd(tempWorldVertex,tempWorldVertex);
  87059. var v = tempWorldVertex;
  87060. if (v.x < minx || minx===undefined){
  87061. minx = v.x;
  87062. } else if(v.x > maxx || maxx===undefined){
  87063. maxx = v.x;
  87064. }
  87065. if (v.y < miny || miny===undefined){
  87066. miny = v.y;
  87067. } else if(v.y > maxy || maxy===undefined){
  87068. maxy = v.y;
  87069. }
  87070. if (v.z < minz || minz===undefined){
  87071. minz = v.z;
  87072. } else if(v.z > maxz || maxz===undefined){
  87073. maxz = v.z;
  87074. }
  87075. }
  87076. min.set(minx,miny,minz);
  87077. max.set(maxx,maxy,maxz);
  87078. };
  87079. /**
  87080. * Get approximate convex volume
  87081. * @method volume
  87082. * @return {Number}
  87083. */
  87084. ConvexPolyhedron.prototype.volume = function(){
  87085. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  87086. };
  87087. /**
  87088. * Get an average of all the vertices positions
  87089. * @method getAveragePointLocal
  87090. * @param {Vec3} target
  87091. * @return {Vec3}
  87092. */
  87093. ConvexPolyhedron.prototype.getAveragePointLocal = function(target){
  87094. target = target || new Vec3();
  87095. var n = this.vertices.length,
  87096. verts = this.vertices;
  87097. for(var i=0; i<n; i++){
  87098. target.vadd(verts[i],target);
  87099. }
  87100. target.mult(1/n,target);
  87101. return target;
  87102. };
  87103. /**
  87104. * Transform all local points. Will change the .vertices
  87105. * @method transformAllPoints
  87106. * @param {Vec3} offset
  87107. * @param {Quaternion} quat
  87108. */
  87109. ConvexPolyhedron.prototype.transformAllPoints = function(offset,quat){
  87110. var n = this.vertices.length,
  87111. verts = this.vertices;
  87112. // Apply rotation
  87113. if(quat){
  87114. // Rotate vertices
  87115. for(var i=0; i<n; i++){
  87116. var v = verts[i];
  87117. quat.vmult(v,v);
  87118. }
  87119. // Rotate face normals
  87120. for(var i=0; i<this.faceNormals.length; i++){
  87121. var v = this.faceNormals[i];
  87122. quat.vmult(v,v);
  87123. }
  87124. /*
  87125. // Rotate edges
  87126. for(var i=0; i<this.uniqueEdges.length; i++){
  87127. var v = this.uniqueEdges[i];
  87128. quat.vmult(v,v);
  87129. }*/
  87130. }
  87131. // Apply offset
  87132. if(offset){
  87133. for(var i=0; i<n; i++){
  87134. var v = verts[i];
  87135. v.vadd(offset,v);
  87136. }
  87137. }
  87138. };
  87139. /**
  87140. * 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.
  87141. * @method pointIsInside
  87142. * @param {Vec3} p A point given in local coordinates
  87143. * @return {Boolean}
  87144. */
  87145. var ConvexPolyhedron_pointIsInside = new Vec3();
  87146. var ConvexPolyhedron_vToP = new Vec3();
  87147. var ConvexPolyhedron_vToPointInside = new Vec3();
  87148. ConvexPolyhedron.prototype.pointIsInside = function(p){
  87149. var n = this.vertices.length,
  87150. verts = this.vertices,
  87151. faces = this.faces,
  87152. normals = this.faceNormals;
  87153. var positiveResult = null;
  87154. var N = this.faces.length;
  87155. var pointInside = ConvexPolyhedron_pointIsInside;
  87156. this.getAveragePointLocal(pointInside);
  87157. for(var i=0; i<N; i++){
  87158. var numVertices = this.faces[i].length;
  87159. var n = normals[i];
  87160. var v = verts[faces[i][0]]; // We only need one point in the face
  87161. // This dot product determines which side of the edge the point is
  87162. var vToP = ConvexPolyhedron_vToP;
  87163. p.vsub(v,vToP);
  87164. var r1 = n.dot(vToP);
  87165. var vToPointInside = ConvexPolyhedron_vToPointInside;
  87166. pointInside.vsub(v,vToPointInside);
  87167. var r2 = n.dot(vToPointInside);
  87168. if((r1<0 && r2>0) || (r1>0 && r2<0)){
  87169. return false; // Encountered some other sign. Exit.
  87170. } else {
  87171. }
  87172. }
  87173. // If we got here, all dot products were of the same sign.
  87174. return positiveResult ? 1 : -1;
  87175. };
  87176. /**
  87177. * 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.
  87178. * @static
  87179. * @method project
  87180. * @param {ConvexPolyhedron} hull
  87181. * @param {Vec3} axis
  87182. * @param {Vec3} pos
  87183. * @param {Quaternion} quat
  87184. * @param {array} result result[0] and result[1] will be set to maximum and minimum, respectively.
  87185. */
  87186. var project_worldVertex = new Vec3();
  87187. var project_localAxis = new Vec3();
  87188. var project_localOrigin = new Vec3();
  87189. ConvexPolyhedron.project = function(hull, axis, pos, quat, result){
  87190. var n = hull.vertices.length,
  87191. worldVertex = project_worldVertex,
  87192. localAxis = project_localAxis,
  87193. max = 0,
  87194. min = 0,
  87195. localOrigin = project_localOrigin,
  87196. vs = hull.vertices;
  87197. localOrigin.setZero();
  87198. // Transform the axis to local
  87199. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  87200. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  87201. var add = localOrigin.dot(localAxis);
  87202. min = max = vs[0].dot(localAxis);
  87203. for(var i = 1; i < n; i++){
  87204. var val = vs[i].dot(localAxis);
  87205. if(val > max){
  87206. max = val;
  87207. }
  87208. if(val < min){
  87209. min = val;
  87210. }
  87211. }
  87212. min -= add;
  87213. max -= add;
  87214. if(min > max){
  87215. // Inconsistent - swap
  87216. var temp = min;
  87217. min = max;
  87218. max = temp;
  87219. }
  87220. // Output
  87221. result[0] = max;
  87222. result[1] = min;
  87223. };
  87224. },{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(_dereq_,module,exports){
  87225. module.exports = Cylinder;
  87226. var Shape = _dereq_('./Shape');
  87227. var Vec3 = _dereq_('../math/Vec3');
  87228. var Quaternion = _dereq_('../math/Quaternion');
  87229. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  87230. /**
  87231. * @class Cylinder
  87232. * @constructor
  87233. * @extends ConvexPolyhedron
  87234. * @author schteppe / https://github.com/schteppe
  87235. * @param {Number} radiusTop
  87236. * @param {Number} radiusBottom
  87237. * @param {Number} height
  87238. * @param {Number} numSegments The number of segments to build the cylinder out of
  87239. */
  87240. function Cylinder( radiusTop, radiusBottom, height , numSegments ) {
  87241. var N = numSegments,
  87242. verts = [],
  87243. axes = [],
  87244. faces = [],
  87245. bottomface = [],
  87246. topface = [],
  87247. cos = Math.cos,
  87248. sin = Math.sin;
  87249. // First bottom point
  87250. verts.push(new Vec3(radiusBottom*cos(0),
  87251. radiusBottom*sin(0),
  87252. -height*0.5));
  87253. bottomface.push(0);
  87254. // First top point
  87255. verts.push(new Vec3(radiusTop*cos(0),
  87256. radiusTop*sin(0),
  87257. height*0.5));
  87258. topface.push(1);
  87259. for(var i=0; i<N; i++){
  87260. var theta = 2*Math.PI/N * (i+1);
  87261. var thetaN = 2*Math.PI/N * (i+0.5);
  87262. if(i<N-1){
  87263. // Bottom
  87264. verts.push(new Vec3(radiusBottom*cos(theta),
  87265. radiusBottom*sin(theta),
  87266. -height*0.5));
  87267. bottomface.push(2*i+2);
  87268. // Top
  87269. verts.push(new Vec3(radiusTop*cos(theta),
  87270. radiusTop*sin(theta),
  87271. height*0.5));
  87272. topface.push(2*i+3);
  87273. // Face
  87274. faces.push([2*i+2, 2*i+3, 2*i+1,2*i]);
  87275. } else {
  87276. faces.push([0,1, 2*i+1, 2*i]); // Connect
  87277. }
  87278. // Axis: we can cut off half of them if we have even number of segments
  87279. if(N % 2 === 1 || i < N / 2){
  87280. axes.push(new Vec3(cos(thetaN), sin(thetaN), 0));
  87281. }
  87282. }
  87283. faces.push(topface);
  87284. axes.push(new Vec3(0,0,1));
  87285. // Reorder bottom face
  87286. var temp = [];
  87287. for(var i=0; i<bottomface.length; i++){
  87288. temp.push(bottomface[bottomface.length - i - 1]);
  87289. }
  87290. faces.push(temp);
  87291. this.type = Shape.types.CONVEXPOLYHEDRON;
  87292. ConvexPolyhedron.call( this, verts, faces, axes );
  87293. }
  87294. Cylinder.prototype = new ConvexPolyhedron();
  87295. },{"../math/Quaternion":28,"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],40:[function(_dereq_,module,exports){
  87296. var Shape = _dereq_('./Shape');
  87297. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  87298. var Vec3 = _dereq_('../math/Vec3');
  87299. var Utils = _dereq_('../utils/Utils');
  87300. module.exports = Heightfield;
  87301. /**
  87302. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  87303. * @class Heightfield
  87304. * @extends Shape
  87305. * @constructor
  87306. * @param {Array} data An array of Y values that will be used to construct the terrain.
  87307. * @param {object} options
  87308. * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
  87309. * @param {Number} [options.maxValue] Maximum value.
  87310. * @param {Number} [options.elementSize=0.1] World spacing between the data points in X direction.
  87311. * @todo Should be possible to use along all axes, not just y
  87312. *
  87313. * @example
  87314. * // Generate some height data (y-values).
  87315. * var data = [];
  87316. * for(var i = 0; i < 1000; i++){
  87317. * var y = 0.5 * Math.cos(0.2 * i);
  87318. * data.push(y);
  87319. * }
  87320. *
  87321. * // Create the heightfield shape
  87322. * var heightfieldShape = new Heightfield(data, {
  87323. * elementSize: 1 // Distance between the data points in X and Y directions
  87324. * });
  87325. * var heightfieldBody = new Body();
  87326. * heightfieldBody.addShape(heightfieldShape);
  87327. * world.addBody(heightfieldBody);
  87328. */
  87329. function Heightfield(data, options){
  87330. options = Utils.defaults(options, {
  87331. maxValue : null,
  87332. minValue : null,
  87333. elementSize : 1
  87334. });
  87335. /**
  87336. * An array of numbers, or height values, that are spread out along the x axis.
  87337. * @property {array} data
  87338. */
  87339. this.data = data;
  87340. /**
  87341. * Max value of the data
  87342. * @property {number} maxValue
  87343. */
  87344. this.maxValue = options.maxValue;
  87345. /**
  87346. * Max value of the data
  87347. * @property {number} minValue
  87348. */
  87349. this.minValue = options.minValue;
  87350. /**
  87351. * The width of each element
  87352. * @property {number} elementSize
  87353. * @todo elementSizeX and Y
  87354. */
  87355. this.elementSize = options.elementSize;
  87356. if(options.minValue === null){
  87357. this.updateMinValue();
  87358. }
  87359. if(options.maxValue === null){
  87360. this.updateMaxValue();
  87361. }
  87362. this.cacheEnabled = true;
  87363. Shape.call(this);
  87364. this.pillarConvex = new ConvexPolyhedron();
  87365. this.pillarOffset = new Vec3();
  87366. this.type = Shape.types.HEIGHTFIELD;
  87367. this.updateBoundingSphereRadius();
  87368. // "i_j_isUpper" => { convex: ..., offset: ... }
  87369. // for example:
  87370. // _cachedPillars["0_2_1"]
  87371. this._cachedPillars = {};
  87372. }
  87373. Heightfield.prototype = new Shape();
  87374. /**
  87375. * Call whenever you change the data array.
  87376. * @method update
  87377. */
  87378. Heightfield.prototype.update = function(){
  87379. this._cachedPillars = {};
  87380. };
  87381. /**
  87382. * Update the .minValue property
  87383. * @method updateMinValue
  87384. */
  87385. Heightfield.prototype.updateMinValue = function(){
  87386. var data = this.data;
  87387. var minValue = data[0][0];
  87388. for(var i=0; i !== data.length; i++){
  87389. for(var j=0; j !== data[i].length; j++){
  87390. var v = data[i][j];
  87391. if(v < minValue){
  87392. minValue = v;
  87393. }
  87394. }
  87395. }
  87396. this.minValue = minValue;
  87397. };
  87398. /**
  87399. * Update the .maxValue property
  87400. * @method updateMaxValue
  87401. */
  87402. Heightfield.prototype.updateMaxValue = function(){
  87403. var data = this.data;
  87404. var maxValue = data[0][0];
  87405. for(var i=0; i !== data.length; i++){
  87406. for(var j=0; j !== data[i].length; j++){
  87407. var v = data[i][j];
  87408. if(v > maxValue){
  87409. maxValue = v;
  87410. }
  87411. }
  87412. }
  87413. this.maxValue = maxValue;
  87414. };
  87415. /**
  87416. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  87417. * @method setHeightValueAtIndex
  87418. * @param {integer} xi
  87419. * @param {integer} yi
  87420. * @param {number} value
  87421. */
  87422. Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){
  87423. var data = this.data;
  87424. data[xi][yi] = value;
  87425. // Invalidate cache
  87426. this.clearCachedConvexTrianglePillar(xi, yi, false);
  87427. if(xi > 0){
  87428. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  87429. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  87430. }
  87431. if(yi > 0){
  87432. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  87433. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  87434. }
  87435. if(yi > 0 && xi > 0){
  87436. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  87437. }
  87438. };
  87439. /**
  87440. * Get max/min in a rectangle in the matrix data
  87441. * @method getRectMinMax
  87442. * @param {integer} iMinX
  87443. * @param {integer} iMinY
  87444. * @param {integer} iMaxX
  87445. * @param {integer} iMaxY
  87446. * @param {array} [result] An array to store the results in.
  87447. * @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  87448. */
  87449. Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) {
  87450. result = result || [];
  87451. // Get max and min of the data
  87452. var data = this.data,
  87453. max = this.minValue; // Set first value
  87454. for(var i = iMinX; i <= iMaxX; i++){
  87455. for(var j = iMinY; j <= iMaxY; j++){
  87456. var height = data[i][j];
  87457. if(height > max){
  87458. max = height;
  87459. }
  87460. }
  87461. }
  87462. result[0] = this.minValue;
  87463. result[1] = max;
  87464. };
  87465. /**
  87466. * 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.
  87467. * @method getIndexOfPosition
  87468. * @param {number} x
  87469. * @param {number} y
  87470. * @param {array} result Two-element array
  87471. * @param {boolean} clamp If the position should be clamped to the heightfield edge.
  87472. * @return {boolean}
  87473. */
  87474. Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) {
  87475. // Get the index of the data points to test against
  87476. var w = this.elementSize;
  87477. var data = this.data;
  87478. var xi = Math.floor(x / w);
  87479. var yi = Math.floor(y / w);
  87480. result[0] = xi;
  87481. result[1] = yi;
  87482. if(clamp){
  87483. // Clamp index to edges
  87484. if(xi < 0){ xi = 0; }
  87485. if(yi < 0){ yi = 0; }
  87486. if(xi >= data.length - 1){ xi = data.length - 1; }
  87487. if(yi >= data[0].length - 1){ yi = data[0].length - 1; }
  87488. }
  87489. // Bail out if we are out of the terrain
  87490. if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){
  87491. return false;
  87492. }
  87493. return true;
  87494. };
  87495. Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){
  87496. var idx = [];
  87497. this.getIndexOfPosition(x, y, idx, edgeClamp);
  87498. // TODO: get upper or lower triangle, then use barycentric interpolation to get the height in the triangle.
  87499. var minmax = [];
  87500. this.getRectMinMax(idx[0], idx[1] + 1, idx[0], idx[1] + 1, minmax);
  87501. return (minmax[0] + minmax[1]) / 2; // average
  87502. };
  87503. Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){
  87504. return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0);
  87505. };
  87506. Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  87507. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  87508. };
  87509. Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){
  87510. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  87511. convex: convex,
  87512. offset: offset
  87513. };
  87514. };
  87515. Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  87516. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  87517. };
  87518. /**
  87519. * Get a triangle in the terrain in the form of a triangular convex shape.
  87520. * @method getConvexTrianglePillar
  87521. * @param {integer} i
  87522. * @param {integer} j
  87523. * @param {boolean} getUpperTriangle
  87524. */
  87525. Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  87526. var result = this.pillarConvex;
  87527. var offsetResult = this.pillarOffset;
  87528. if(this.cacheEnabled){
  87529. var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  87530. if(data){
  87531. this.pillarConvex = data.convex;
  87532. this.pillarOffset = data.offset;
  87533. return;
  87534. }
  87535. result = new ConvexPolyhedron();
  87536. offsetResult = new Vec3();
  87537. this.pillarConvex = result;
  87538. this.pillarOffset = offsetResult;
  87539. }
  87540. var data = this.data;
  87541. var elementSize = this.elementSize;
  87542. var faces = result.faces;
  87543. // Reuse verts if possible
  87544. result.vertices.length = 6;
  87545. for (var i = 0; i < 6; i++) {
  87546. if(!result.vertices[i]){
  87547. result.vertices[i] = new Vec3();
  87548. }
  87549. }
  87550. // Reuse faces if possible
  87551. faces.length = 5;
  87552. for (var i = 0; i < 5; i++) {
  87553. if(!faces[i]){
  87554. faces[i] = [];
  87555. }
  87556. }
  87557. var verts = result.vertices;
  87558. var h = (Math.min(
  87559. data[xi][yi],
  87560. data[xi+1][yi],
  87561. data[xi][yi+1],
  87562. data[xi+1][yi+1]
  87563. ) - this.minValue ) / 2 + this.minValue;
  87564. if (!getUpperTriangle) {
  87565. // Center of the triangle pillar - all polygons are given relative to this one
  87566. offsetResult.set(
  87567. (xi + 0.25) * elementSize, // sort of center of a triangle
  87568. (yi + 0.25) * elementSize,
  87569. h // vertical center
  87570. );
  87571. // Top triangle verts
  87572. verts[0].set(
  87573. -0.25 * elementSize,
  87574. -0.25 * elementSize,
  87575. data[xi][yi] - h
  87576. );
  87577. verts[1].set(
  87578. 0.75 * elementSize,
  87579. -0.25 * elementSize,
  87580. data[xi + 1][yi] - h
  87581. );
  87582. verts[2].set(
  87583. -0.25 * elementSize,
  87584. 0.75 * elementSize,
  87585. data[xi][yi + 1] - h
  87586. );
  87587. // bottom triangle verts
  87588. verts[3].set(
  87589. -0.25 * elementSize,
  87590. -0.25 * elementSize,
  87591. -h-1
  87592. );
  87593. verts[4].set(
  87594. 0.75 * elementSize,
  87595. -0.25 * elementSize,
  87596. -h-1
  87597. );
  87598. verts[5].set(
  87599. -0.25 * elementSize,
  87600. 0.75 * elementSize,
  87601. -h-1
  87602. );
  87603. // top triangle
  87604. faces[0][0] = 0;
  87605. faces[0][1] = 1;
  87606. faces[0][2] = 2;
  87607. // bottom triangle
  87608. faces[1][0] = 5;
  87609. faces[1][1] = 4;
  87610. faces[1][2] = 3;
  87611. // -x facing quad
  87612. faces[2][0] = 0;
  87613. faces[2][1] = 2;
  87614. faces[2][2] = 5;
  87615. faces[2][3] = 3;
  87616. // -y facing quad
  87617. faces[3][0] = 1;
  87618. faces[3][1] = 0;
  87619. faces[3][2] = 3;
  87620. faces[3][3] = 4;
  87621. // +xy facing quad
  87622. faces[4][0] = 4;
  87623. faces[4][1] = 5;
  87624. faces[4][2] = 2;
  87625. faces[4][3] = 1;
  87626. } else {
  87627. // Center of the triangle pillar - all polygons are given relative to this one
  87628. offsetResult.set(
  87629. (xi + 0.75) * elementSize, // sort of center of a triangle
  87630. (yi + 0.75) * elementSize,
  87631. h // vertical center
  87632. );
  87633. // Top triangle verts
  87634. verts[0].set(
  87635. 0.25 * elementSize,
  87636. 0.25 * elementSize,
  87637. data[xi + 1][yi + 1] - h
  87638. );
  87639. verts[1].set(
  87640. -0.75 * elementSize,
  87641. 0.25 * elementSize,
  87642. data[xi][yi + 1] - h
  87643. );
  87644. verts[2].set(
  87645. 0.25 * elementSize,
  87646. -0.75 * elementSize,
  87647. data[xi + 1][yi] - h
  87648. );
  87649. // bottom triangle verts
  87650. verts[3].set(
  87651. 0.25 * elementSize,
  87652. 0.25 * elementSize,
  87653. - h-1
  87654. );
  87655. verts[4].set(
  87656. -0.75 * elementSize,
  87657. 0.25 * elementSize,
  87658. - h-1
  87659. );
  87660. verts[5].set(
  87661. 0.25 * elementSize,
  87662. -0.75 * elementSize,
  87663. - h-1
  87664. );
  87665. // Top triangle
  87666. faces[0][0] = 0;
  87667. faces[0][1] = 1;
  87668. faces[0][2] = 2;
  87669. // bottom triangle
  87670. faces[1][0] = 5;
  87671. faces[1][1] = 4;
  87672. faces[1][2] = 3;
  87673. // +x facing quad
  87674. faces[2][0] = 2;
  87675. faces[2][1] = 5;
  87676. faces[2][2] = 3;
  87677. faces[2][3] = 0;
  87678. // +y facing quad
  87679. faces[3][0] = 3;
  87680. faces[3][1] = 4;
  87681. faces[3][2] = 1;
  87682. faces[3][3] = 0;
  87683. // -xy facing quad
  87684. faces[4][0] = 1;
  87685. faces[4][1] = 4;
  87686. faces[4][2] = 5;
  87687. faces[4][3] = 2;
  87688. }
  87689. result.computeNormals();
  87690. result.computeEdges();
  87691. result.updateBoundingSphereRadius();
  87692. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  87693. };
  87694. Heightfield.prototype.calculateLocalInertia = function(mass, target){
  87695. target = target || new Vec3();
  87696. target.set(0, 0, 0);
  87697. return target;
  87698. };
  87699. Heightfield.prototype.volume = function(){
  87700. return Number.MAX_VALUE; // The terrain is infinite
  87701. };
  87702. Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){
  87703. // TODO: do it properly
  87704. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87705. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87706. };
  87707. Heightfield.prototype.updateBoundingSphereRadius = function(){
  87708. // Use the bounding box of the min/max values
  87709. var data = this.data,
  87710. s = this.elementSize;
  87711. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm();
  87712. };
  87713. },{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(_dereq_,module,exports){
  87714. module.exports = Particle;
  87715. var Shape = _dereq_('./Shape');
  87716. var Vec3 = _dereq_('../math/Vec3');
  87717. /**
  87718. * Particle shape.
  87719. * @class Particle
  87720. * @constructor
  87721. * @author schteppe
  87722. * @extends Shape
  87723. */
  87724. function Particle(){
  87725. Shape.call(this);
  87726. this.type = Shape.types.PARTICLE;
  87727. }
  87728. Particle.prototype = new Shape();
  87729. Particle.prototype.constructor = Particle;
  87730. /**
  87731. * @method calculateLocalInertia
  87732. * @param {Number} mass
  87733. * @param {Vec3} target
  87734. * @return {Vec3}
  87735. */
  87736. Particle.prototype.calculateLocalInertia = function(mass,target){
  87737. target = target || new Vec3();
  87738. target.set(0, 0, 0);
  87739. return target;
  87740. };
  87741. Particle.prototype.volume = function(){
  87742. return 0;
  87743. };
  87744. Particle.prototype.updateBoundingSphereRadius = function(){
  87745. this.boundingSphereRadius = 0;
  87746. };
  87747. Particle.prototype.calculateWorldAABB = function(pos,quat,min,max){
  87748. // Get each axis max
  87749. min.copy(pos);
  87750. max.copy(pos);
  87751. };
  87752. },{"../math/Vec3":30,"./Shape":43}],42:[function(_dereq_,module,exports){
  87753. module.exports = Plane;
  87754. var Shape = _dereq_('./Shape');
  87755. var Vec3 = _dereq_('../math/Vec3');
  87756. /**
  87757. * 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.
  87758. * @class Plane
  87759. * @constructor
  87760. * @extends Shape
  87761. * @author schteppe
  87762. */
  87763. function Plane(){
  87764. Shape.call(this);
  87765. this.type = Shape.types.PLANE;
  87766. // World oriented normal
  87767. this.worldNormal = new Vec3();
  87768. this.worldNormalNeedsUpdate = true;
  87769. this.boundingSphereRadius = Number.MAX_VALUE;
  87770. }
  87771. Plane.prototype = new Shape();
  87772. Plane.prototype.constructor = Plane;
  87773. Plane.prototype.computeWorldNormal = function(quat){
  87774. var n = this.worldNormal;
  87775. n.set(0,0,1);
  87776. quat.vmult(n,n);
  87777. this.worldNormalNeedsUpdate = false;
  87778. };
  87779. Plane.prototype.calculateLocalInertia = function(mass,target){
  87780. target = target || new Vec3();
  87781. return target;
  87782. };
  87783. Plane.prototype.volume = function(){
  87784. return Number.MAX_VALUE; // The plane is infinite...
  87785. };
  87786. var tempNormal = new Vec3();
  87787. Plane.prototype.calculateWorldAABB = function(pos, quat, min, max){
  87788. // The plane AABB is infinite, except if the normal is pointing along any axis
  87789. tempNormal.set(0,0,1); // Default plane normal is z
  87790. quat.vmult(tempNormal,tempNormal);
  87791. var maxVal = Number.MAX_VALUE;
  87792. min.set(-maxVal, -maxVal, -maxVal);
  87793. max.set(maxVal, maxVal, maxVal);
  87794. if(tempNormal.x === 1){ max.x = pos.x; }
  87795. if(tempNormal.y === 1){ max.y = pos.y; }
  87796. if(tempNormal.z === 1){ max.z = pos.z; }
  87797. if(tempNormal.x === -1){ min.x = pos.x; }
  87798. if(tempNormal.y === -1){ min.y = pos.y; }
  87799. if(tempNormal.z === -1){ min.z = pos.z; }
  87800. };
  87801. Plane.prototype.updateBoundingSphereRadius = function(){
  87802. this.boundingSphereRadius = Number.MAX_VALUE;
  87803. };
  87804. },{"../math/Vec3":30,"./Shape":43}],43:[function(_dereq_,module,exports){
  87805. module.exports = Shape;
  87806. var Shape = _dereq_('./Shape');
  87807. var Vec3 = _dereq_('../math/Vec3');
  87808. var Quaternion = _dereq_('../math/Quaternion');
  87809. var Material = _dereq_('../material/Material');
  87810. /**
  87811. * Base class for shapes
  87812. * @class Shape
  87813. * @constructor
  87814. * @author schteppe
  87815. * @todo Should have a mechanism for caching bounding sphere radius instead of calculating it each time
  87816. */
  87817. function Shape(){
  87818. /**
  87819. * Identifyer of the Shape.
  87820. * @property {number} id
  87821. */
  87822. this.id = Shape.idCounter++;
  87823. /**
  87824. * The type of this shape. Must be set to an int > 0 by subclasses.
  87825. * @property type
  87826. * @type {Number}
  87827. * @see Shape.types
  87828. */
  87829. this.type = 0;
  87830. /**
  87831. * The local bounding sphere radius of this shape.
  87832. * @property {Number} boundingSphereRadius
  87833. */
  87834. this.boundingSphereRadius = 0;
  87835. /**
  87836. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  87837. * @property {boolean} collisionResponse
  87838. */
  87839. this.collisionResponse = true;
  87840. /**
  87841. * @property {Material} material
  87842. */
  87843. this.material = null;
  87844. }
  87845. Shape.prototype.constructor = Shape;
  87846. /**
  87847. * Computes the bounding sphere radius. The result is stored in the property .boundingSphereRadius
  87848. * @method updateBoundingSphereRadius
  87849. * @return {Number}
  87850. */
  87851. Shape.prototype.updateBoundingSphereRadius = function(){
  87852. throw "computeBoundingSphereRadius() not implemented for shape type "+this.type;
  87853. };
  87854. /**
  87855. * Get the volume of this shape
  87856. * @method volume
  87857. * @return {Number}
  87858. */
  87859. Shape.prototype.volume = function(){
  87860. throw "volume() not implemented for shape type "+this.type;
  87861. };
  87862. /**
  87863. * Calculates the inertia in the local frame for this shape.
  87864. * @method calculateLocalInertia
  87865. * @return {Vec3}
  87866. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  87867. */
  87868. Shape.prototype.calculateLocalInertia = function(mass,target){
  87869. throw "calculateLocalInertia() not implemented for shape type "+this.type;
  87870. };
  87871. Shape.idCounter = 0;
  87872. /**
  87873. * The available shape types.
  87874. * @static
  87875. * @property types
  87876. * @type {Object}
  87877. */
  87878. Shape.types = {
  87879. SPHERE:1,
  87880. PLANE:2,
  87881. BOX:4,
  87882. COMPOUND:8,
  87883. CONVEXPOLYHEDRON:16,
  87884. HEIGHTFIELD:32,
  87885. PARTICLE:64,
  87886. CYLINDER:128,
  87887. TRIMESH:256
  87888. };
  87889. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"./Shape":43}],44:[function(_dereq_,module,exports){
  87890. module.exports = Sphere;
  87891. var Shape = _dereq_('./Shape');
  87892. var Vec3 = _dereq_('../math/Vec3');
  87893. /**
  87894. * Spherical shape
  87895. * @class Sphere
  87896. * @constructor
  87897. * @extends Shape
  87898. * @param {Number} radius The radius of the sphere, a non-negative number.
  87899. * @author schteppe / http://github.com/schteppe
  87900. */
  87901. function Sphere(radius){
  87902. Shape.call(this);
  87903. /**
  87904. * @property {Number} radius
  87905. */
  87906. this.radius = radius!==undefined ? Number(radius) : 1.0;
  87907. this.type = Shape.types.SPHERE;
  87908. if(this.radius < 0){
  87909. throw new Error('The sphere radius cannot be negative.');
  87910. }
  87911. this.updateBoundingSphereRadius();
  87912. }
  87913. Sphere.prototype = new Shape();
  87914. Sphere.prototype.constructor = Sphere;
  87915. Sphere.prototype.calculateLocalInertia = function(mass,target){
  87916. target = target || new Vec3();
  87917. var I = 2.0*mass*this.radius*this.radius/5.0;
  87918. target.x = I;
  87919. target.y = I;
  87920. target.z = I;
  87921. return target;
  87922. };
  87923. Sphere.prototype.volume = function(){
  87924. return 4.0 * Math.PI * this.radius / 3.0;
  87925. };
  87926. Sphere.prototype.updateBoundingSphereRadius = function(){
  87927. this.boundingSphereRadius = this.radius;
  87928. };
  87929. Sphere.prototype.calculateWorldAABB = function(pos,quat,min,max){
  87930. var r = this.radius;
  87931. var axes = ['x','y','z'];
  87932. for(var i=0; i<axes.length; i++){
  87933. var ax = axes[i];
  87934. min[ax] = pos[ax] - r;
  87935. max[ax] = pos[ax] + r;
  87936. }
  87937. };
  87938. },{"../math/Vec3":30,"./Shape":43}],45:[function(_dereq_,module,exports){
  87939. module.exports = Trimesh;
  87940. var Shape = _dereq_('./Shape');
  87941. var Vec3 = _dereq_('../math/Vec3');
  87942. var Quaternion = _dereq_('../math/Quaternion');
  87943. var Transform = _dereq_('../math/Transform');
  87944. var AABB = _dereq_('../collision/AABB');
  87945. var Octree = _dereq_('../utils/Octree');
  87946. /**
  87947. * @class Trimesh
  87948. * @constructor
  87949. * @param {array} vertices
  87950. * @param {array} indices
  87951. * @extends Shape
  87952. * @example
  87953. * // How to make a mesh with a single triangle
  87954. * var vertices = [
  87955. * 0, 0, 0, // vertex 0
  87956. * 1, 0, 0, // vertex 1
  87957. * 0, 1, 0 // vertex 2
  87958. * ];
  87959. * var indices = [
  87960. * 0, 1, 2 // triangle 0
  87961. * ];
  87962. * var trimeshShape = new Trimesh(vertices, indices);
  87963. */
  87964. function Trimesh(vertices, indices) {
  87965. Shape.call(this);
  87966. this.type = Shape.types.TRIMESH;
  87967. /**
  87968. * @property vertices
  87969. * @type {Array}
  87970. */
  87971. this.vertices = new Float32Array(vertices);
  87972. /**
  87973. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  87974. * @property indices
  87975. * @type {Array}
  87976. */
  87977. this.indices = new Int16Array(indices);
  87978. /**
  87979. * The normals data.
  87980. * @property normals
  87981. * @type {Array}
  87982. */
  87983. this.normals = new Float32Array(indices.length);
  87984. /**
  87985. * The local AABB of the mesh.
  87986. * @property aabb
  87987. * @type {Array}
  87988. */
  87989. this.aabb = new AABB();
  87990. /**
  87991. * References to vertex pairs, making up all unique edges in the trimesh.
  87992. * @property {array} edges
  87993. */
  87994. this.edges = null;
  87995. /**
  87996. * Local scaling of the mesh. Use .setScale() to set it.
  87997. * @property {Vec3} scale
  87998. */
  87999. this.scale = new Vec3(1, 1, 1);
  88000. /**
  88001. * The indexed triangles. Use .updateTree() to update it.
  88002. * @property {Octree} tree
  88003. */
  88004. this.tree = new Octree();
  88005. this.updateEdges();
  88006. this.updateNormals();
  88007. this.updateAABB();
  88008. this.updateBoundingSphereRadius();
  88009. this.updateTree();
  88010. }
  88011. Trimesh.prototype = new Shape();
  88012. Trimesh.prototype.constructor = Trimesh;
  88013. var computeNormals_n = new Vec3();
  88014. /**
  88015. * @method updateTree
  88016. */
  88017. Trimesh.prototype.updateTree = function(){
  88018. var tree = this.tree;
  88019. tree.reset();
  88020. tree.aabb.copy(this.aabb);
  88021. var scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  88022. tree.aabb.lowerBound.x *= 1 / scale.x;
  88023. tree.aabb.lowerBound.y *= 1 / scale.y;
  88024. tree.aabb.lowerBound.z *= 1 / scale.z;
  88025. tree.aabb.upperBound.x *= 1 / scale.x;
  88026. tree.aabb.upperBound.y *= 1 / scale.y;
  88027. tree.aabb.upperBound.z *= 1 / scale.z;
  88028. // Insert all triangles
  88029. var triangleAABB = new AABB();
  88030. var a = new Vec3();
  88031. var b = new Vec3();
  88032. var c = new Vec3();
  88033. var points = [a, b, c];
  88034. for (var i = 0; i < this.indices.length / 3; i++) {
  88035. //this.getTriangleVertices(i, a, b, c);
  88036. // Get unscaled triangle verts
  88037. var i3 = i * 3;
  88038. this._getUnscaledVertex(this.indices[i3], a);
  88039. this._getUnscaledVertex(this.indices[i3 + 1], b);
  88040. this._getUnscaledVertex(this.indices[i3 + 2], c);
  88041. triangleAABB.setFromPoints(points);
  88042. tree.insert(triangleAABB, i);
  88043. }
  88044. tree.removeEmptyNodes();
  88045. };
  88046. var unscaledAABB = new AABB();
  88047. /**
  88048. * Get triangles in a local AABB from the trimesh.
  88049. * @method getTrianglesInAABB
  88050. * @param {AABB} aabb
  88051. * @param {array} result An array of integers, referencing the queried triangles.
  88052. */
  88053. Trimesh.prototype.getTrianglesInAABB = function(aabb, result){
  88054. unscaledAABB.copy(aabb);
  88055. // Scale it to local
  88056. var scale = this.scale;
  88057. var isx = scale.x;
  88058. var isy = scale.y;
  88059. var isz = scale.z;
  88060. var l = unscaledAABB.lowerBound;
  88061. var u = unscaledAABB.upperBound;
  88062. l.x /= isx;
  88063. l.y /= isy;
  88064. l.z /= isz;
  88065. u.x /= isx;
  88066. u.y /= isy;
  88067. u.z /= isz;
  88068. return this.tree.aabbQuery(unscaledAABB, result);
  88069. };
  88070. /**
  88071. * @method setScale
  88072. * @param {Vec3} scale
  88073. */
  88074. Trimesh.prototype.setScale = function(scale){
  88075. var wasUniform = this.scale.x === this.scale.y === this.scale.z;
  88076. var isUniform = scale.x === scale.y === scale.z;
  88077. if(!(wasUniform && isUniform)){
  88078. // Non-uniform scaling. Need to update normals.
  88079. this.updateNormals();
  88080. }
  88081. this.scale.copy(scale);
  88082. this.updateAABB();
  88083. this.updateBoundingSphereRadius();
  88084. };
  88085. /**
  88086. * Compute the normals of the faces. Will save in the .normals array.
  88087. * @method updateNormals
  88088. */
  88089. Trimesh.prototype.updateNormals = function(){
  88090. var n = computeNormals_n;
  88091. // Generate normals
  88092. var normals = this.normals;
  88093. for(var i=0; i < this.indices.length / 3; i++){
  88094. var i3 = i * 3;
  88095. var a = this.indices[i3],
  88096. b = this.indices[i3 + 1],
  88097. c = this.indices[i3 + 2];
  88098. this.getVertex(a, va);
  88099. this.getVertex(b, vb);
  88100. this.getVertex(c, vc);
  88101. Trimesh.computeNormal(vb, va, vc, n);
  88102. normals[i3] = n.x;
  88103. normals[i3 + 1] = n.y;
  88104. normals[i3 + 2] = n.z;
  88105. }
  88106. };
  88107. /**
  88108. * Update the .edges property
  88109. * @method updateEdges
  88110. */
  88111. Trimesh.prototype.updateEdges = function(){
  88112. var edges = {};
  88113. var add = function(indexA, indexB){
  88114. var key = a < b ? a + '_' + b : b + '_' + a;
  88115. edges[key] = true;
  88116. };
  88117. for(var i=0; i < this.indices.length / 3; i++){
  88118. var i3 = i * 3;
  88119. var a = this.indices[i3],
  88120. b = this.indices[i3 + 1],
  88121. c = this.indices[i3 + 2];
  88122. add(a,b);
  88123. add(b,c);
  88124. add(c,a);
  88125. }
  88126. var keys = Object.keys(edges);
  88127. this.edges = new Int16Array(keys.length * 2);
  88128. for (var i = 0; i < keys.length; i++) {
  88129. var indices = keys[i].split('_');
  88130. this.edges[2 * i] = parseInt(indices[0], 10);
  88131. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  88132. }
  88133. };
  88134. /**
  88135. * Get an edge vertex
  88136. * @method getEdgeVertex
  88137. * @param {number} edgeIndex
  88138. * @param {number} firstOrSecond 0 or 1, depending on which one of the vertices you need.
  88139. * @param {Vec3} vertexStore Where to store the result
  88140. */
  88141. Trimesh.prototype.getEdgeVertex = function(edgeIndex, firstOrSecond, vertexStore){
  88142. var vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  88143. this.getVertex(vertexIndex, vertexStore);
  88144. };
  88145. var getEdgeVector_va = new Vec3();
  88146. var getEdgeVector_vb = new Vec3();
  88147. /**
  88148. * Get a vector along an edge.
  88149. * @method getEdgeVector
  88150. * @param {number} edgeIndex
  88151. * @param {Vec3} vectorStore
  88152. */
  88153. Trimesh.prototype.getEdgeVector = function(edgeIndex, vectorStore){
  88154. var va = getEdgeVector_va;
  88155. var vb = getEdgeVector_vb;
  88156. this.getEdgeVertex(edgeIndex, 0, va);
  88157. this.getEdgeVertex(edgeIndex, 1, vb);
  88158. vb.vsub(va, vectorStore);
  88159. };
  88160. /**
  88161. * Get face normal given 3 vertices
  88162. * @static
  88163. * @method computeNormal
  88164. * @param {Vec3} va
  88165. * @param {Vec3} vb
  88166. * @param {Vec3} vc
  88167. * @param {Vec3} target
  88168. */
  88169. var cb = new Vec3();
  88170. var ab = new Vec3();
  88171. Trimesh.computeNormal = function ( va, vb, vc, target ) {
  88172. vb.vsub(va,ab);
  88173. vc.vsub(vb,cb);
  88174. cb.cross(ab,target);
  88175. if ( !target.isZero() ) {
  88176. target.normalize();
  88177. }
  88178. };
  88179. var va = new Vec3();
  88180. var vb = new Vec3();
  88181. var vc = new Vec3();
  88182. /**
  88183. * Get vertex i.
  88184. * @method getVertex
  88185. * @param {number} i
  88186. * @param {Vec3} out
  88187. * @return {Vec3} The "out" vector object
  88188. */
  88189. Trimesh.prototype.getVertex = function(i, out){
  88190. var scale = this.scale;
  88191. this._getUnscaledVertex(i, out);
  88192. out.x *= scale.x;
  88193. out.y *= scale.y;
  88194. out.z *= scale.z;
  88195. return out;
  88196. };
  88197. /**
  88198. * Get raw vertex i
  88199. * @private
  88200. * @method _getUnscaledVertex
  88201. * @param {number} i
  88202. * @param {Vec3} out
  88203. * @return {Vec3} The "out" vector object
  88204. */
  88205. Trimesh.prototype._getUnscaledVertex = function(i, out){
  88206. var i3 = i * 3;
  88207. var vertices = this.vertices;
  88208. return out.set(
  88209. vertices[i3],
  88210. vertices[i3 + 1],
  88211. vertices[i3 + 2]
  88212. );
  88213. };
  88214. /**
  88215. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  88216. * @method getWorldVertex
  88217. * @param {number} i
  88218. * @param {Vec3} pos
  88219. * @param {Quaternion} quat
  88220. * @param {Vec3} out
  88221. * @return {Vec3} The "out" vector object
  88222. */
  88223. Trimesh.prototype.getWorldVertex = function(i, pos, quat, out){
  88224. this.getVertex(i, out);
  88225. Transform.pointToWorldFrame(pos, quat, out, out);
  88226. return out;
  88227. };
  88228. /**
  88229. * Get the three vertices for triangle i.
  88230. * @method getTriangleVertices
  88231. * @param {number} i
  88232. * @param {Vec3} a
  88233. * @param {Vec3} b
  88234. * @param {Vec3} c
  88235. */
  88236. Trimesh.prototype.getTriangleVertices = function(i, a, b, c){
  88237. var i3 = i * 3;
  88238. this.getVertex(this.indices[i3], a);
  88239. this.getVertex(this.indices[i3 + 1], b);
  88240. this.getVertex(this.indices[i3 + 2], c);
  88241. };
  88242. /**
  88243. * Compute the normal of triangle i.
  88244. * @method getNormal
  88245. * @param {Number} i
  88246. * @param {Vec3} target
  88247. * @return {Vec3} The "target" vector object
  88248. */
  88249. Trimesh.prototype.getNormal = function(i, target){
  88250. var i3 = i * 3;
  88251. return target.set(
  88252. this.normals[i3],
  88253. this.normals[i3 + 1],
  88254. this.normals[i3 + 2]
  88255. );
  88256. };
  88257. var cli_aabb = new AABB();
  88258. /**
  88259. * @method calculateLocalInertia
  88260. * @param {Number} mass
  88261. * @param {Vec3} target
  88262. * @return {Vec3} The "target" vector object
  88263. */
  88264. Trimesh.prototype.calculateLocalInertia = function(mass,target){
  88265. // Approximate with box inertia
  88266. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  88267. this.computeLocalAABB(cli_aabb);
  88268. var x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x,
  88269. y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y,
  88270. z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  88271. return target.set(
  88272. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z ),
  88273. 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z ),
  88274. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x )
  88275. );
  88276. };
  88277. var computeLocalAABB_worldVert = new Vec3();
  88278. /**
  88279. * Compute the local AABB for the trimesh
  88280. * @method computeLocalAABB
  88281. * @param {AABB} aabb
  88282. */
  88283. Trimesh.prototype.computeLocalAABB = function(aabb){
  88284. var l = aabb.lowerBound,
  88285. u = aabb.upperBound,
  88286. n = this.vertices.length,
  88287. vertices = this.vertices,
  88288. v = computeLocalAABB_worldVert;
  88289. this.getVertex(0, v);
  88290. l.copy(v);
  88291. u.copy(v);
  88292. for(var i=0; i !== n; i++){
  88293. this.getVertex(i, v);
  88294. if(v.x < l.x){
  88295. l.x = v.x;
  88296. } else if(v.x > u.x){
  88297. u.x = v.x;
  88298. }
  88299. if(v.y < l.y){
  88300. l.y = v.y;
  88301. } else if(v.y > u.y){
  88302. u.y = v.y;
  88303. }
  88304. if(v.z < l.z){
  88305. l.z = v.z;
  88306. } else if(v.z > u.z){
  88307. u.z = v.z;
  88308. }
  88309. }
  88310. };
  88311. /**
  88312. * Update the .aabb property
  88313. * @method updateAABB
  88314. */
  88315. Trimesh.prototype.updateAABB = function(){
  88316. this.computeLocalAABB(this.aabb);
  88317. };
  88318. /**
  88319. * Will update the .boundingSphereRadius property
  88320. * @method updateBoundingSphereRadius
  88321. */
  88322. Trimesh.prototype.updateBoundingSphereRadius = function(){
  88323. // Assume points are distributed with local (0,0,0) as center
  88324. var max2 = 0;
  88325. var vertices = this.vertices;
  88326. var v = new Vec3();
  88327. for(var i=0, N=vertices.length / 3; i !== N; i++) {
  88328. this.getVertex(i, v);
  88329. var norm2 = v.norm2();
  88330. if(norm2 > max2){
  88331. max2 = norm2;
  88332. }
  88333. }
  88334. this.boundingSphereRadius = Math.sqrt(max2);
  88335. };
  88336. var tempWorldVertex = new Vec3();
  88337. var calculateWorldAABB_frame = new Transform();
  88338. var calculateWorldAABB_aabb = new AABB();
  88339. /**
  88340. * @method calculateWorldAABB
  88341. * @param {Vec3} pos
  88342. * @param {Quaternion} quat
  88343. * @param {Vec3} min
  88344. * @param {Vec3} max
  88345. */
  88346. Trimesh.prototype.calculateWorldAABB = function(pos,quat,min,max){
  88347. /*
  88348. var n = this.vertices.length / 3,
  88349. verts = this.vertices;
  88350. var minx,miny,minz,maxx,maxy,maxz;
  88351. var v = tempWorldVertex;
  88352. for(var i=0; i<n; i++){
  88353. this.getVertex(i, v);
  88354. quat.vmult(v, v);
  88355. pos.vadd(v, v);
  88356. if (v.x < minx || minx===undefined){
  88357. minx = v.x;
  88358. } else if(v.x > maxx || maxx===undefined){
  88359. maxx = v.x;
  88360. }
  88361. if (v.y < miny || miny===undefined){
  88362. miny = v.y;
  88363. } else if(v.y > maxy || maxy===undefined){
  88364. maxy = v.y;
  88365. }
  88366. if (v.z < minz || minz===undefined){
  88367. minz = v.z;
  88368. } else if(v.z > maxz || maxz===undefined){
  88369. maxz = v.z;
  88370. }
  88371. }
  88372. min.set(minx,miny,minz);
  88373. max.set(maxx,maxy,maxz);
  88374. */
  88375. // Faster approximation using local AABB
  88376. var frame = calculateWorldAABB_frame;
  88377. var result = calculateWorldAABB_aabb;
  88378. frame.position = pos;
  88379. frame.quaternion = quat;
  88380. this.aabb.toWorldFrame(frame, result);
  88381. min.copy(result.lowerBound);
  88382. max.copy(result.upperBound);
  88383. };
  88384. /**
  88385. * Get approximate volume
  88386. * @method volume
  88387. * @return {Number}
  88388. */
  88389. Trimesh.prototype.volume = function(){
  88390. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  88391. };
  88392. /**
  88393. * Create a Trimesh instance, shaped as a torus.
  88394. * @static
  88395. * @method createTorus
  88396. * @param {number} [radius=1]
  88397. * @param {number} [tube=0.5]
  88398. * @param {number} [radialSegments=8]
  88399. * @param {number} [tubularSegments=6]
  88400. * @param {number} [arc=6.283185307179586]
  88401. * @return {Trimesh} A torus
  88402. */
  88403. Trimesh.createTorus = function (radius, tube, radialSegments, tubularSegments, arc) {
  88404. radius = radius || 1;
  88405. tube = tube || 0.5;
  88406. radialSegments = radialSegments || 8;
  88407. tubularSegments = tubularSegments || 6;
  88408. arc = arc || Math.PI * 2;
  88409. var vertices = [];
  88410. var indices = [];
  88411. for ( var j = 0; j <= radialSegments; j ++ ) {
  88412. for ( var i = 0; i <= tubularSegments; i ++ ) {
  88413. var u = i / tubularSegments * arc;
  88414. var v = j / radialSegments * Math.PI * 2;
  88415. var x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  88416. var y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  88417. var z = tube * Math.sin( v );
  88418. vertices.push( x, y, z );
  88419. }
  88420. }
  88421. for ( var j = 1; j <= radialSegments; j ++ ) {
  88422. for ( var i = 1; i <= tubularSegments; i ++ ) {
  88423. var a = ( tubularSegments + 1 ) * j + i - 1;
  88424. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  88425. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  88426. var d = ( tubularSegments + 1 ) * j + i;
  88427. indices.push(a, b, d);
  88428. indices.push(b, c, d);
  88429. }
  88430. }
  88431. return new Trimesh(vertices, indices);
  88432. };
  88433. },{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(_dereq_,module,exports){
  88434. module.exports = GSSolver;
  88435. var Vec3 = _dereq_('../math/Vec3');
  88436. var Quaternion = _dereq_('../math/Quaternion');
  88437. var Solver = _dereq_('./Solver');
  88438. /**
  88439. * Constraint equation Gauss-Seidel solver.
  88440. * @class GSSolver
  88441. * @constructor
  88442. * @todo The spook parameters should be specified for each constraint, not globally.
  88443. * @author schteppe / https://github.com/schteppe
  88444. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  88445. * @extends Solver
  88446. */
  88447. function GSSolver(){
  88448. Solver.call(this);
  88449. /**
  88450. * 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.
  88451. * @property iterations
  88452. * @type {Number}
  88453. * @todo write more about solver and iterations in the wiki
  88454. */
  88455. this.iterations = 10;
  88456. /**
  88457. * When tolerance is reached, the system is assumed to be converged.
  88458. * @property tolerance
  88459. * @type {Number}
  88460. */
  88461. this.tolerance = 1e-7;
  88462. }
  88463. GSSolver.prototype = new Solver();
  88464. var GSSolver_solve_lambda = []; // Just temporary number holders that we want to reuse each solve.
  88465. var GSSolver_solve_invCs = [];
  88466. var GSSolver_solve_Bs = [];
  88467. GSSolver.prototype.solve = function(dt,world){
  88468. var iter = 0,
  88469. maxIter = this.iterations,
  88470. tolSquared = this.tolerance*this.tolerance,
  88471. equations = this.equations,
  88472. Neq = equations.length,
  88473. bodies = world.bodies,
  88474. Nbodies = bodies.length,
  88475. h = dt,
  88476. q, B, invC, deltalambda, deltalambdaTot, GWlambda, lambdaj;
  88477. // Update solve mass
  88478. if(Neq !== 0){
  88479. for(var i=0; i!==Nbodies; i++){
  88480. bodies[i].updateSolveMassProperties();
  88481. }
  88482. }
  88483. // Things that does not change during iteration can be computed once
  88484. var invCs = GSSolver_solve_invCs,
  88485. Bs = GSSolver_solve_Bs,
  88486. lambda = GSSolver_solve_lambda;
  88487. invCs.length = Neq;
  88488. Bs.length = Neq;
  88489. lambda.length = Neq;
  88490. for(var i=0; i!==Neq; i++){
  88491. var c = equations[i];
  88492. lambda[i] = 0.0;
  88493. Bs[i] = c.computeB(h);
  88494. invCs[i] = 1.0 / c.computeC();
  88495. }
  88496. if(Neq !== 0){
  88497. // Reset vlambda
  88498. for(var i=0; i!==Nbodies; i++){
  88499. var b=bodies[i],
  88500. vlambda=b.vlambda,
  88501. wlambda=b.wlambda;
  88502. vlambda.set(0,0,0);
  88503. if(wlambda){
  88504. wlambda.set(0,0,0);
  88505. }
  88506. }
  88507. // Iterate over equations
  88508. for(iter=0; iter!==maxIter; iter++){
  88509. // Accumulate the total error for each iteration.
  88510. deltalambdaTot = 0.0;
  88511. for(var j=0; j!==Neq; j++){
  88512. var c = equations[j];
  88513. // Compute iteration
  88514. B = Bs[j];
  88515. invC = invCs[j];
  88516. lambdaj = lambda[j];
  88517. GWlambda = c.computeGWlambda();
  88518. deltalambda = invC * ( B - GWlambda - c.eps * lambdaj );
  88519. // Clamp if we are not within the min/max interval
  88520. if(lambdaj + deltalambda < c.minForce){
  88521. deltalambda = c.minForce - lambdaj;
  88522. } else if(lambdaj + deltalambda > c.maxForce){
  88523. deltalambda = c.maxForce - lambdaj;
  88524. }
  88525. lambda[j] += deltalambda;
  88526. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  88527. c.addToWlambda(deltalambda);
  88528. }
  88529. // If the total error is small enough - stop iterate
  88530. if(deltalambdaTot*deltalambdaTot < tolSquared){
  88531. break;
  88532. }
  88533. }
  88534. // Add result to velocity
  88535. for(var i=0; i!==Nbodies; i++){
  88536. var b=bodies[i],
  88537. v=b.velocity,
  88538. w=b.angularVelocity;
  88539. v.vadd(b.vlambda, v);
  88540. if(w){
  88541. w.vadd(b.wlambda, w);
  88542. }
  88543. }
  88544. }
  88545. return iter;
  88546. };
  88547. },{"../math/Quaternion":28,"../math/Vec3":30,"./Solver":47}],47:[function(_dereq_,module,exports){
  88548. module.exports = Solver;
  88549. /**
  88550. * Constraint equation solver base class.
  88551. * @class Solver
  88552. * @constructor
  88553. * @author schteppe / https://github.com/schteppe
  88554. */
  88555. function Solver(){
  88556. /**
  88557. * All equations to be solved
  88558. * @property {Array} equations
  88559. */
  88560. this.equations = [];
  88561. }
  88562. /**
  88563. * Should be implemented in subclasses!
  88564. * @method solve
  88565. * @param {Number} dt
  88566. * @param {World} world
  88567. */
  88568. Solver.prototype.solve = function(dt,world){
  88569. // Should return the number of iterations done!
  88570. return 0;
  88571. };
  88572. /**
  88573. * Add an equation
  88574. * @method addEquation
  88575. * @param {Equation} eq
  88576. */
  88577. Solver.prototype.addEquation = function(eq){
  88578. if (eq.enabled) {
  88579. this.equations.push(eq);
  88580. }
  88581. };
  88582. /**
  88583. * Remove an equation
  88584. * @method removeEquation
  88585. * @param {Equation} eq
  88586. */
  88587. Solver.prototype.removeEquation = function(eq){
  88588. var eqs = this.equations;
  88589. var i = eqs.indexOf(eq);
  88590. if(i !== -1){
  88591. eqs.splice(i,1);
  88592. }
  88593. };
  88594. /**
  88595. * Add all equations
  88596. * @method removeAllEquations
  88597. */
  88598. Solver.prototype.removeAllEquations = function(){
  88599. this.equations.length = 0;
  88600. };
  88601. },{}],48:[function(_dereq_,module,exports){
  88602. module.exports = SplitSolver;
  88603. var Vec3 = _dereq_('../math/Vec3');
  88604. var Quaternion = _dereq_('../math/Quaternion');
  88605. var Solver = _dereq_('./Solver');
  88606. var Body = _dereq_('../objects/Body');
  88607. /**
  88608. * Splits the equations into islands and solves them independently. Can improve performance.
  88609. * @class SplitSolver
  88610. * @constructor
  88611. * @extends Solver
  88612. * @param {Solver} subsolver
  88613. */
  88614. function SplitSolver(subsolver){
  88615. Solver.call(this);
  88616. this.iterations = 10;
  88617. this.tolerance = 1e-7;
  88618. this.subsolver = subsolver;
  88619. this.nodes = [];
  88620. this.nodePool = [];
  88621. // Create needed nodes, reuse if possible
  88622. while(this.nodePool.length < 128){
  88623. this.nodePool.push(this.createNode());
  88624. }
  88625. }
  88626. SplitSolver.prototype = new Solver();
  88627. // Returns the number of subsystems
  88628. var SplitSolver_solve_nodes = []; // All allocated node objects
  88629. var SplitSolver_solve_nodePool = []; // All allocated node objects
  88630. var SplitSolver_solve_eqs = []; // Temp array
  88631. var SplitSolver_solve_bds = []; // Temp array
  88632. var SplitSolver_solve_dummyWorld = {bodies:[]}; // Temp object
  88633. var STATIC = Body.STATIC;
  88634. function getUnvisitedNode(nodes){
  88635. var Nnodes = nodes.length;
  88636. for(var i=0; i!==Nnodes; i++){
  88637. var node = nodes[i];
  88638. if(!node.visited && !(node.body.type & STATIC)){
  88639. return node;
  88640. }
  88641. }
  88642. return false;
  88643. }
  88644. var queue = [];
  88645. function bfs(root,visitFunc,bds,eqs){
  88646. queue.push(root);
  88647. root.visited = true;
  88648. visitFunc(root,bds,eqs);
  88649. while(queue.length) {
  88650. var node = queue.pop();
  88651. // Loop over unvisited child nodes
  88652. var child;
  88653. while((child = getUnvisitedNode(node.children))) {
  88654. child.visited = true;
  88655. visitFunc(child,bds,eqs);
  88656. queue.push(child);
  88657. }
  88658. }
  88659. }
  88660. function visitFunc(node,bds,eqs){
  88661. bds.push(node.body);
  88662. var Neqs = node.eqs.length;
  88663. for(var i=0; i!==Neqs; i++){
  88664. var eq = node.eqs[i];
  88665. if(eqs.indexOf(eq) === -1){
  88666. eqs.push(eq);
  88667. }
  88668. }
  88669. }
  88670. SplitSolver.prototype.createNode = function(){
  88671. return { body:null, children:[], eqs:[], visited:false };
  88672. };
  88673. /**
  88674. * Solve the subsystems
  88675. * @method solve
  88676. * @param {Number} dt
  88677. * @param {World} world
  88678. */
  88679. SplitSolver.prototype.solve = function(dt,world){
  88680. var nodes=SplitSolver_solve_nodes,
  88681. nodePool=this.nodePool,
  88682. bodies=world.bodies,
  88683. equations=this.equations,
  88684. Neq=equations.length,
  88685. Nbodies=bodies.length,
  88686. subsolver=this.subsolver;
  88687. // Create needed nodes, reuse if possible
  88688. while(nodePool.length < Nbodies){
  88689. nodePool.push(this.createNode());
  88690. }
  88691. nodes.length = Nbodies;
  88692. for (var i = 0; i < Nbodies; i++) {
  88693. nodes[i] = nodePool[i];
  88694. }
  88695. // Reset node values
  88696. for(var i=0; i!==Nbodies; i++){
  88697. var node = nodes[i];
  88698. node.body = bodies[i];
  88699. node.children.length = 0;
  88700. node.eqs.length = 0;
  88701. node.visited = false;
  88702. }
  88703. for(var k=0; k!==Neq; k++){
  88704. var eq=equations[k],
  88705. i=bodies.indexOf(eq.bi),
  88706. j=bodies.indexOf(eq.bj),
  88707. ni=nodes[i],
  88708. nj=nodes[j];
  88709. ni.children.push(nj);
  88710. ni.eqs.push(eq);
  88711. nj.children.push(ni);
  88712. nj.eqs.push(eq);
  88713. }
  88714. var child, n=0, eqs=SplitSolver_solve_eqs;
  88715. subsolver.tolerance = this.tolerance;
  88716. subsolver.iterations = this.iterations;
  88717. var dummyWorld = SplitSolver_solve_dummyWorld;
  88718. while((child = getUnvisitedNode(nodes))){
  88719. eqs.length = 0;
  88720. dummyWorld.bodies.length = 0;
  88721. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  88722. var Neqs = eqs.length;
  88723. eqs = eqs.sort(sortById);
  88724. for(var i=0; i!==Neqs; i++){
  88725. subsolver.addEquation(eqs[i]);
  88726. }
  88727. var iter = subsolver.solve(dt,dummyWorld);
  88728. subsolver.removeAllEquations();
  88729. n++;
  88730. }
  88731. return n;
  88732. };
  88733. function sortById(a, b){
  88734. return b.id - a.id;
  88735. }
  88736. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"./Solver":47}],49:[function(_dereq_,module,exports){
  88737. /**
  88738. * Base class for objects that dispatches events.
  88739. * @class EventTarget
  88740. * @constructor
  88741. */
  88742. var EventTarget = function () {
  88743. };
  88744. module.exports = EventTarget;
  88745. EventTarget.prototype = {
  88746. constructor: EventTarget,
  88747. /**
  88748. * Add an event listener
  88749. * @method addEventListener
  88750. * @param {String} type
  88751. * @param {Function} listener
  88752. * @return {EventTarget} The self object, for chainability.
  88753. */
  88754. addEventListener: function ( type, listener ) {
  88755. if ( this._listeners === undefined ){ this._listeners = {}; }
  88756. var listeners = this._listeners;
  88757. if ( listeners[ type ] === undefined ) {
  88758. listeners[ type ] = [];
  88759. }
  88760. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  88761. listeners[ type ].push( listener );
  88762. }
  88763. return this;
  88764. },
  88765. /**
  88766. * Check if an event listener is added
  88767. * @method hasEventListener
  88768. * @param {String} type
  88769. * @param {Function} listener
  88770. * @return {Boolean}
  88771. */
  88772. hasEventListener: function ( type, listener ) {
  88773. if ( this._listeners === undefined ){ return false; }
  88774. var listeners = this._listeners;
  88775. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  88776. return true;
  88777. }
  88778. return false;
  88779. },
  88780. /**
  88781. * Remove an event listener
  88782. * @method removeEventListener
  88783. * @param {String} type
  88784. * @param {Function} listener
  88785. * @return {EventTarget} The self object, for chainability.
  88786. */
  88787. removeEventListener: function ( type, listener ) {
  88788. if ( this._listeners === undefined ){ return this; }
  88789. var listeners = this._listeners;
  88790. if ( listeners[type] === undefined ){ return this; }
  88791. var index = listeners[ type ].indexOf( listener );
  88792. if ( index !== - 1 ) {
  88793. listeners[ type ].splice( index, 1 );
  88794. }
  88795. return this;
  88796. },
  88797. /**
  88798. * Emit an event.
  88799. * @method dispatchEvent
  88800. * @param {Object} event
  88801. * @param {String} event.type
  88802. * @return {EventTarget} The self object, for chainability.
  88803. */
  88804. dispatchEvent: function ( event ) {
  88805. if ( this._listeners === undefined ){ return this; }
  88806. var listeners = this._listeners;
  88807. var listenerArray = listeners[ event.type ];
  88808. if ( listenerArray !== undefined ) {
  88809. event.target = this;
  88810. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  88811. listenerArray[ i ].call( this, event );
  88812. }
  88813. }
  88814. return this;
  88815. }
  88816. };
  88817. },{}],50:[function(_dereq_,module,exports){
  88818. var AABB = _dereq_('../collision/AABB');
  88819. var Vec3 = _dereq_('../math/Vec3');
  88820. module.exports = Octree;
  88821. /**
  88822. * @class OctreeNode
  88823. * @param {object} [options]
  88824. * @param {Octree} [options.root]
  88825. * @param {AABB} [options.aabb]
  88826. */
  88827. function OctreeNode(options){
  88828. options = options || {};
  88829. /**
  88830. * The root node
  88831. * @property {OctreeNode} root
  88832. */
  88833. this.root = options.root || null;
  88834. /**
  88835. * Boundary of this node
  88836. * @property {AABB} aabb
  88837. */
  88838. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  88839. /**
  88840. * Contained data at the current node level.
  88841. * @property {Array} data
  88842. */
  88843. this.data = [];
  88844. /**
  88845. * Children to this node
  88846. * @property {Array} children
  88847. */
  88848. this.children = [];
  88849. }
  88850. /**
  88851. * @class Octree
  88852. * @param {AABB} aabb The total AABB of the tree
  88853. * @param {object} [options]
  88854. * @param {number} [options.maxDepth=8]
  88855. * @extends OctreeNode
  88856. */
  88857. function Octree(aabb, options){
  88858. options = options || {};
  88859. options.root = null;
  88860. options.aabb = aabb;
  88861. OctreeNode.call(this, options);
  88862. /**
  88863. * Maximum subdivision depth
  88864. * @property {number} maxDepth
  88865. */
  88866. this.maxDepth = typeof(options.maxDepth) !== 'undefined' ? options.maxDepth : 8;
  88867. }
  88868. Octree.prototype = new OctreeNode();
  88869. OctreeNode.prototype.reset = function(aabb, options){
  88870. this.children.length = this.data.length = 0;
  88871. };
  88872. /**
  88873. * Insert data into this node
  88874. * @method insert
  88875. * @param {AABB} aabb
  88876. * @param {object} elementData
  88877. * @return {boolean} True if successful, otherwise false
  88878. */
  88879. OctreeNode.prototype.insert = function(aabb, elementData, level){
  88880. var nodeData = this.data;
  88881. level = level || 0;
  88882. // Ignore objects that do not belong in this node
  88883. if (!this.aabb.contains(aabb)){
  88884. return false; // object cannot be added
  88885. }
  88886. var children = this.children;
  88887. if(level < (this.maxDepth || this.root.maxDepth)){
  88888. // Subdivide if there are no children yet
  88889. var subdivided = false;
  88890. if (!children.length){
  88891. this.subdivide();
  88892. subdivided = true;
  88893. }
  88894. // add to whichever node will accept it
  88895. for (var i = 0; i !== 8; i++) {
  88896. if (children[i].insert(aabb, elementData, level + 1)){
  88897. return true;
  88898. }
  88899. }
  88900. if(subdivided){
  88901. // No children accepted! Might as well just remove em since they contain none
  88902. children.length = 0;
  88903. }
  88904. }
  88905. // Too deep, or children didnt want it. add it in current node
  88906. nodeData.push(elementData);
  88907. return true;
  88908. };
  88909. var halfDiagonal = new Vec3();
  88910. /**
  88911. * Create 8 equally sized children nodes and put them in the .children array.
  88912. * @method subdivide
  88913. */
  88914. OctreeNode.prototype.subdivide = function() {
  88915. var aabb = this.aabb;
  88916. var l = aabb.lowerBound;
  88917. var u = aabb.upperBound;
  88918. var children = this.children;
  88919. children.push(
  88920. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,0) }) }),
  88921. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,0) }) }),
  88922. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,0) }) }),
  88923. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,1) }) }),
  88924. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,1) }) }),
  88925. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,1) }) }),
  88926. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,1) }) }),
  88927. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,0) }) })
  88928. );
  88929. u.vsub(l, halfDiagonal);
  88930. halfDiagonal.scale(0.5, halfDiagonal);
  88931. var root = this.root || this;
  88932. for (var i = 0; i !== 8; i++) {
  88933. var child = children[i];
  88934. // Set current node as root
  88935. child.root = root;
  88936. // Compute bounds
  88937. var lowerBound = child.aabb.lowerBound;
  88938. lowerBound.x *= halfDiagonal.x;
  88939. lowerBound.y *= halfDiagonal.y;
  88940. lowerBound.z *= halfDiagonal.z;
  88941. lowerBound.vadd(l, lowerBound);
  88942. // Upper bound is always lower bound + halfDiagonal
  88943. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  88944. }
  88945. };
  88946. /**
  88947. * Get all data, potentially within an AABB
  88948. * @method aabbQuery
  88949. * @param {AABB} aabb
  88950. * @param {array} result
  88951. * @return {array} The "result" object
  88952. */
  88953. OctreeNode.prototype.aabbQuery = function(aabb, result) {
  88954. var nodeData = this.data;
  88955. // abort if the range does not intersect this node
  88956. // if (!this.aabb.overlaps(aabb)){
  88957. // return result;
  88958. // }
  88959. // Add objects at this level
  88960. // Array.prototype.push.apply(result, nodeData);
  88961. // Add child data
  88962. // @todo unwrap recursion into a queue / loop, that's faster in JS
  88963. var children = this.children;
  88964. // for (var i = 0, N = this.children.length; i !== N; i++) {
  88965. // children[i].aabbQuery(aabb, result);
  88966. // }
  88967. var queue = [this];
  88968. while (queue.length) {
  88969. var node = queue.pop();
  88970. if (node.aabb.overlaps(aabb)){
  88971. Array.prototype.push.apply(result, node.data);
  88972. }
  88973. Array.prototype.push.apply(queue, node.children);
  88974. }
  88975. return result;
  88976. };
  88977. var tmpAABB = new AABB();
  88978. /**
  88979. * Get all data, potentially intersected by a ray.
  88980. * @method rayQuery
  88981. * @param {Ray} ray
  88982. * @param {Transform} treeTransform
  88983. * @param {array} result
  88984. * @return {array} The "result" object
  88985. */
  88986. OctreeNode.prototype.rayQuery = function(ray, treeTransform, result) {
  88987. // Use aabb query for now.
  88988. // @todo implement real ray query which needs less lookups
  88989. ray.getAABB(tmpAABB);
  88990. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  88991. this.aabbQuery(tmpAABB, result);
  88992. return result;
  88993. };
  88994. /**
  88995. * @method removeEmptyNodes
  88996. */
  88997. OctreeNode.prototype.removeEmptyNodes = function() {
  88998. var queue = [this];
  88999. while (queue.length) {
  89000. var node = queue.pop();
  89001. for (var i = node.children.length - 1; i >= 0; i--) {
  89002. if(!node.children[i].data.length){
  89003. node.children.splice(i, 1);
  89004. }
  89005. }
  89006. Array.prototype.push.apply(queue, node.children);
  89007. }
  89008. };
  89009. },{"../collision/AABB":3,"../math/Vec3":30}],51:[function(_dereq_,module,exports){
  89010. module.exports = Pool;
  89011. /**
  89012. * For pooling objects that can be reused.
  89013. * @class Pool
  89014. * @constructor
  89015. */
  89016. function Pool(){
  89017. /**
  89018. * The pooled objects
  89019. * @property {Array} objects
  89020. */
  89021. this.objects = [];
  89022. /**
  89023. * Constructor of the objects
  89024. * @property {mixed} type
  89025. */
  89026. this.type = Object;
  89027. }
  89028. /**
  89029. * Release an object after use
  89030. * @method release
  89031. * @param {Object} obj
  89032. */
  89033. Pool.prototype.release = function(){
  89034. var Nargs = arguments.length;
  89035. for(var i=0; i!==Nargs; i++){
  89036. this.objects.push(arguments[i]);
  89037. }
  89038. };
  89039. /**
  89040. * Get an object
  89041. * @method get
  89042. * @return {mixed}
  89043. */
  89044. Pool.prototype.get = function(){
  89045. if(this.objects.length===0){
  89046. return this.constructObject();
  89047. } else {
  89048. return this.objects.pop();
  89049. }
  89050. };
  89051. /**
  89052. * Construct an object. Should be implmented in each subclass.
  89053. * @method constructObject
  89054. * @return {mixed}
  89055. */
  89056. Pool.prototype.constructObject = function(){
  89057. throw new Error("constructObject() not implemented in this Pool subclass yet!");
  89058. };
  89059. },{}],52:[function(_dereq_,module,exports){
  89060. module.exports = TupleDictionary;
  89061. /**
  89062. * @class TupleDictionary
  89063. * @constructor
  89064. */
  89065. function TupleDictionary() {
  89066. /**
  89067. * The data storage
  89068. * @property data
  89069. * @type {Object}
  89070. */
  89071. this.data = { keys:[] };
  89072. }
  89073. /**
  89074. * @method get
  89075. * @param {Number} i
  89076. * @param {Number} j
  89077. * @return {Number}
  89078. */
  89079. TupleDictionary.prototype.get = function(i, j) {
  89080. if (i > j) {
  89081. // swap
  89082. var temp = j;
  89083. j = i;
  89084. i = temp;
  89085. }
  89086. return this.data[i+'-'+j];
  89087. };
  89088. /**
  89089. * @method set
  89090. * @param {Number} i
  89091. * @param {Number} j
  89092. * @param {Number} value
  89093. */
  89094. TupleDictionary.prototype.set = function(i, j, value) {
  89095. if (i > j) {
  89096. var temp = j;
  89097. j = i;
  89098. i = temp;
  89099. }
  89100. var key = i+'-'+j;
  89101. // Check if key already exists
  89102. if(!this.get(i,j)){
  89103. this.data.keys.push(key);
  89104. }
  89105. this.data[key] = value;
  89106. };
  89107. /**
  89108. * @method reset
  89109. */
  89110. TupleDictionary.prototype.reset = function() {
  89111. var data = this.data,
  89112. keys = data.keys;
  89113. while(keys.length > 0){
  89114. var key = keys.pop();
  89115. delete data[key];
  89116. }
  89117. };
  89118. },{}],53:[function(_dereq_,module,exports){
  89119. function Utils(){}
  89120. module.exports = Utils;
  89121. /**
  89122. * Extend an options object with default values.
  89123. * @static
  89124. * @method defaults
  89125. * @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
  89126. * @param {object} defaults An object containing default values.
  89127. * @return {object} The modified options object.
  89128. */
  89129. Utils.defaults = function(options, defaults){
  89130. options = options || {};
  89131. for(var key in defaults){
  89132. if(!(key in options)){
  89133. options[key] = defaults[key];
  89134. }
  89135. }
  89136. return options;
  89137. };
  89138. },{}],54:[function(_dereq_,module,exports){
  89139. module.exports = Vec3Pool;
  89140. var Vec3 = _dereq_('../math/Vec3');
  89141. var Pool = _dereq_('./Pool');
  89142. /**
  89143. * @class Vec3Pool
  89144. * @constructor
  89145. * @extends Pool
  89146. */
  89147. function Vec3Pool(){
  89148. Pool.call(this);
  89149. this.type = Vec3;
  89150. }
  89151. Vec3Pool.prototype = new Pool();
  89152. /**
  89153. * Construct a vector
  89154. * @method constructObject
  89155. * @return {Vec3}
  89156. */
  89157. Vec3Pool.prototype.constructObject = function(){
  89158. return new Vec3();
  89159. };
  89160. },{"../math/Vec3":30,"./Pool":51}],55:[function(_dereq_,module,exports){
  89161. module.exports = Narrowphase;
  89162. var AABB = _dereq_('../collision/AABB');
  89163. var Shape = _dereq_('../shapes/Shape');
  89164. var Ray = _dereq_('../collision/Ray');
  89165. var Vec3 = _dereq_('../math/Vec3');
  89166. var Transform = _dereq_('../math/Transform');
  89167. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  89168. var Quaternion = _dereq_('../math/Quaternion');
  89169. var Solver = _dereq_('../solver/Solver');
  89170. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  89171. var ContactEquation = _dereq_('../equations/ContactEquation');
  89172. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  89173. /**
  89174. * Helper class for the World. Generates ContactEquations.
  89175. * @class Narrowphase
  89176. * @constructor
  89177. * @todo Sphere-ConvexPolyhedron contacts
  89178. * @todo Contact reduction
  89179. * @todo should move methods to prototype
  89180. */
  89181. function Narrowphase(world){
  89182. /**
  89183. * Internal storage of pooled contact points.
  89184. * @property {Array} contactPointPool
  89185. */
  89186. this.contactPointPool = [];
  89187. this.frictionEquationPool = [];
  89188. this.result = [];
  89189. this.frictionResult = [];
  89190. /**
  89191. * Pooled vectors.
  89192. * @property {Vec3Pool} v3pool
  89193. */
  89194. this.v3pool = new Vec3Pool();
  89195. this.world = world;
  89196. this.currentContactMaterial = null;
  89197. /**
  89198. * @property {Boolean} enableFrictionReduction
  89199. */
  89200. this.enableFrictionReduction = false;
  89201. }
  89202. /**
  89203. * Make a contact object, by using the internal pool or creating a new one.
  89204. * @method createContactEquation
  89205. * @return {ContactEquation}
  89206. */
  89207. Narrowphase.prototype.createContactEquation = function(bi, bj, si, sj, rsi, rsj){
  89208. var c;
  89209. if(this.contactPointPool.length){
  89210. c = this.contactPointPool.pop();
  89211. c.bi = bi;
  89212. c.bj = bj;
  89213. } else {
  89214. c = new ContactEquation(bi, bj);
  89215. }
  89216. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  89217. var cm = this.currentContactMaterial;
  89218. c.restitution = cm.restitution;
  89219. c.setSpookParams(
  89220. cm.contactEquationStiffness,
  89221. cm.contactEquationRelaxation,
  89222. this.world.dt
  89223. );
  89224. var matA = si.material || bi.material;
  89225. var matB = sj.material || bj.material;
  89226. if(matA && matB && matA.restitution >= 0 && matB.restitution >= 0){
  89227. c.restitution = matA.restitution * matB.restitution;
  89228. }
  89229. c.si = rsi || si;
  89230. c.sj = rsj || sj;
  89231. return c;
  89232. };
  89233. Narrowphase.prototype.createFrictionEquationsFromContact = function(contactEquation, outArray){
  89234. var bodyA = contactEquation.bi;
  89235. var bodyB = contactEquation.bj;
  89236. var shapeA = contactEquation.si;
  89237. var shapeB = contactEquation.sj;
  89238. var world = this.world;
  89239. var cm = this.currentContactMaterial;
  89240. // If friction or restitution were specified in the material, use them
  89241. var friction = cm.friction;
  89242. var matA = shapeA.material || bodyA.material;
  89243. var matB = shapeB.material || bodyB.material;
  89244. if(matA && matB && matA.friction >= 0 && matB.friction >= 0){
  89245. friction = matA.friction * matB.friction;
  89246. }
  89247. if(friction > 0){
  89248. // Create 2 tangent equations
  89249. var mug = friction * world.gravity.length();
  89250. var reducedMass = (bodyA.invMass + bodyB.invMass);
  89251. if(reducedMass > 0){
  89252. reducedMass = 1/reducedMass;
  89253. }
  89254. var pool = this.frictionEquationPool;
  89255. var c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  89256. var c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  89257. c1.bi = c2.bi = bodyA;
  89258. c1.bj = c2.bj = bodyB;
  89259. c1.minForce = c2.minForce = -mug*reducedMass;
  89260. c1.maxForce = c2.maxForce = mug*reducedMass;
  89261. // Copy over the relative vectors
  89262. c1.ri.copy(contactEquation.ri);
  89263. c1.rj.copy(contactEquation.rj);
  89264. c2.ri.copy(contactEquation.ri);
  89265. c2.rj.copy(contactEquation.rj);
  89266. // Construct tangents
  89267. contactEquation.ni.tangents(c1.t, c2.t);
  89268. // Set spook params
  89269. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  89270. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  89271. c1.enabled = c2.enabled = contactEquation.enabled;
  89272. outArray.push(c1, c2);
  89273. return true;
  89274. }
  89275. return false;
  89276. };
  89277. var averageNormal = new Vec3();
  89278. var averageContactPointA = new Vec3();
  89279. var averageContactPointB = new Vec3();
  89280. // Take the average N latest contact point on the plane.
  89281. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
  89282. // The last contactEquation
  89283. var c = this.result[this.result.length - 1];
  89284. // Create the result: two "average" friction equations
  89285. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  89286. return;
  89287. }
  89288. var f1 = this.frictionResult[this.frictionResult.length - 2];
  89289. var f2 = this.frictionResult[this.frictionResult.length - 1];
  89290. averageNormal.setZero();
  89291. averageContactPointA.setZero();
  89292. averageContactPointB.setZero();
  89293. var bodyA = c.bi;
  89294. var bodyB = c.bj;
  89295. for(var i=0; i!==numContacts; i++){
  89296. c = this.result[this.result.length - 1 - i];
  89297. if(c.bodyA !== bodyA){
  89298. averageNormal.vadd(c.ni, averageNormal); // vec2.add(eq.t, eq.t, c.normalA);
  89299. averageContactPointA.vadd(c.ri, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  89300. averageContactPointB.vadd(c.rj, averageContactPointB);
  89301. } else {
  89302. averageNormal.vsub(c.ni, averageNormal); // vec2.sub(eq.t, eq.t, c.normalA);
  89303. averageContactPointA.vadd(c.rj, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  89304. averageContactPointB.vadd(c.ri, averageContactPointB);
  89305. }
  89306. }
  89307. var invNumContacts = 1 / numContacts;
  89308. averageContactPointA.scale(invNumContacts, f1.ri); // vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts);
  89309. averageContactPointB.scale(invNumContacts, f1.rj); // vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts);
  89310. f2.ri.copy(f1.ri); // Should be the same
  89311. f2.rj.copy(f1.rj);
  89312. averageNormal.normalize();
  89313. averageNormal.tangents(f1.t, f2.t);
  89314. // return eq;
  89315. };
  89316. var tmpVec1 = new Vec3();
  89317. var tmpVec2 = new Vec3();
  89318. var tmpQuat1 = new Quaternion();
  89319. var tmpQuat2 = new Quaternion();
  89320. /**
  89321. * Generate all contacts between a list of body pairs
  89322. * @method getContacts
  89323. * @param {array} p1 Array of body indices
  89324. * @param {array} p2 Array of body indices
  89325. * @param {World} world
  89326. * @param {array} result Array to store generated contacts
  89327. * @param {array} oldcontacts Optional. Array of reusable contact objects
  89328. */
  89329. Narrowphase.prototype.getContacts = function(p1, p2, world, result, oldcontacts, frictionResult, frictionPool){
  89330. // Save old contact objects
  89331. this.contactPointPool = oldcontacts;
  89332. this.frictionEquationPool = frictionPool;
  89333. this.result = result;
  89334. this.frictionResult = frictionResult;
  89335. var qi = tmpQuat1;
  89336. var qj = tmpQuat2;
  89337. var xi = tmpVec1;
  89338. var xj = tmpVec2;
  89339. for(var k=0, N=p1.length; k!==N; k++){
  89340. // Get current collision bodies
  89341. var bi = p1[k],
  89342. bj = p2[k];
  89343. // Get contact material
  89344. var bodyContactMaterial = null;
  89345. if(bi.material && bj.material){
  89346. bodyContactMaterial = world.getContactMaterial(bi.material,bj.material) || null;
  89347. }
  89348. for (var i = 0; i < bi.shapes.length; i++) {
  89349. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  89350. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  89351. xi.vadd(bi.position, xi);
  89352. var si = bi.shapes[i];
  89353. for (var j = 0; j < bj.shapes.length; j++) {
  89354. // Compute world transform of shapes
  89355. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  89356. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  89357. xj.vadd(bj.position, xj);
  89358. var sj = bj.shapes[j];
  89359. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  89360. continue;
  89361. }
  89362. // Get collision material
  89363. var shapeContactMaterial = null;
  89364. if(si.material && sj.material){
  89365. shapeContactMaterial = world.getContactMaterial(si.material,sj.material) || null;
  89366. }
  89367. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial;
  89368. // Get contacts
  89369. var resolver = this[si.type | sj.type];
  89370. if(resolver){
  89371. if (si.type < sj.type) {
  89372. resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj);
  89373. } else {
  89374. resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj);
  89375. }
  89376. }
  89377. }
  89378. }
  89379. }
  89380. };
  89381. var numWarnings = 0;
  89382. var maxWarnings = 10;
  89383. function warn(msg){
  89384. if(numWarnings > maxWarnings){
  89385. return;
  89386. }
  89387. numWarnings++;
  89388. console.warn(msg);
  89389. }
  89390. Narrowphase.prototype[Shape.types.BOX | Shape.types.BOX] =
  89391. Narrowphase.prototype.boxBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  89392. si.convexPolyhedronRepresentation.material = si.material;
  89393. sj.convexPolyhedronRepresentation.material = sj.material;
  89394. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  89395. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  89396. this.convexConvex(si.convexPolyhedronRepresentation,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj);
  89397. };
  89398. Narrowphase.prototype[Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON] =
  89399. Narrowphase.prototype.boxConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  89400. si.convexPolyhedronRepresentation.material = si.material;
  89401. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  89402. this.convexConvex(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  89403. };
  89404. Narrowphase.prototype[Shape.types.BOX | Shape.types.PARTICLE] =
  89405. Narrowphase.prototype.boxParticle = function(si,sj,xi,xj,qi,qj,bi,bj){
  89406. si.convexPolyhedronRepresentation.material = si.material;
  89407. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  89408. this.convexParticle(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  89409. };
  89410. /**
  89411. * @method sphereSphere
  89412. * @param {Shape} si
  89413. * @param {Shape} sj
  89414. * @param {Vec3} xi
  89415. * @param {Vec3} xj
  89416. * @param {Quaternion} qi
  89417. * @param {Quaternion} qj
  89418. * @param {Body} bi
  89419. * @param {Body} bj
  89420. */
  89421. Narrowphase.prototype[Shape.types.SPHERE] =
  89422. Narrowphase.prototype.sphereSphere = function(si,sj,xi,xj,qi,qj,bi,bj){
  89423. // We will have only one contact in this case
  89424. var r = this.createContactEquation(bi,bj,si,sj);
  89425. // Contact normal
  89426. xj.vsub(xi, r.ni);
  89427. r.ni.normalize();
  89428. // Contact point locations
  89429. r.ri.copy(r.ni);
  89430. r.rj.copy(r.ni);
  89431. r.ri.mult(si.radius, r.ri);
  89432. r.rj.mult(-sj.radius, r.rj);
  89433. r.ri.vadd(xi, r.ri);
  89434. r.ri.vsub(bi.position, r.ri);
  89435. r.rj.vadd(xj, r.rj);
  89436. r.rj.vsub(bj.position, r.rj);
  89437. this.result.push(r);
  89438. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89439. };
  89440. /**
  89441. * @method planeTrimesh
  89442. * @param {Shape} si
  89443. * @param {Shape} sj
  89444. * @param {Vec3} xi
  89445. * @param {Vec3} xj
  89446. * @param {Quaternion} qi
  89447. * @param {Quaternion} qj
  89448. * @param {Body} bi
  89449. * @param {Body} bj
  89450. */
  89451. var planeTrimesh_normal = new Vec3();
  89452. var planeTrimesh_relpos = new Vec3();
  89453. var planeTrimesh_projected = new Vec3();
  89454. Narrowphase.prototype[Shape.types.PLANE | Shape.types.TRIMESH] =
  89455. Narrowphase.prototype.planeTrimesh = function(
  89456. planeShape,
  89457. trimeshShape,
  89458. planePos,
  89459. trimeshPos,
  89460. planeQuat,
  89461. trimeshQuat,
  89462. planeBody,
  89463. trimeshBody
  89464. ){
  89465. // Make contacts!
  89466. var v = new Vec3();
  89467. var normal = planeTrimesh_normal;
  89468. normal.set(0,0,1);
  89469. planeQuat.vmult(normal,normal); // Turn normal according to plane
  89470. for(var i=0; i<trimeshShape.vertices.length / 3; i++){
  89471. // Get world vertex from trimesh
  89472. trimeshShape.getVertex(i, v);
  89473. // Safe up
  89474. var v2 = new Vec3();
  89475. v2.copy(v);
  89476. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  89477. // Check plane side
  89478. var relpos = planeTrimesh_relpos;
  89479. v.vsub(planePos, relpos);
  89480. var dot = normal.dot(relpos);
  89481. if(dot <= 0.0){
  89482. var r = this.createContactEquation(planeBody,trimeshBody,planeShape,trimeshShape);
  89483. r.ni.copy(normal); // Contact normal is the plane normal
  89484. // Get vertex position projected on plane
  89485. var projected = planeTrimesh_projected;
  89486. normal.scale(relpos.dot(normal), projected);
  89487. v.vsub(projected,projected);
  89488. // ri is the projected world position minus plane position
  89489. r.ri.copy(projected);
  89490. r.ri.vsub(planeBody.position, r.ri);
  89491. r.rj.copy(v);
  89492. r.rj.vsub(trimeshBody.position, r.rj);
  89493. // Store result
  89494. this.result.push(r);
  89495. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89496. }
  89497. }
  89498. };
  89499. /**
  89500. * @method sphereTrimesh
  89501. * @param {Shape} sphereShape
  89502. * @param {Shape} trimeshShape
  89503. * @param {Vec3} spherePos
  89504. * @param {Vec3} trimeshPos
  89505. * @param {Quaternion} sphereQuat
  89506. * @param {Quaternion} trimeshQuat
  89507. * @param {Body} sphereBody
  89508. * @param {Body} trimeshBody
  89509. */
  89510. var sphereTrimesh_normal = new Vec3();
  89511. var sphereTrimesh_relpos = new Vec3();
  89512. var sphereTrimesh_projected = new Vec3();
  89513. var sphereTrimesh_v = new Vec3();
  89514. var sphereTrimesh_v2 = new Vec3();
  89515. var sphereTrimesh_edgeVertexA = new Vec3();
  89516. var sphereTrimesh_edgeVertexB = new Vec3();
  89517. var sphereTrimesh_edgeVector = new Vec3();
  89518. var sphereTrimesh_edgeVectorUnit = new Vec3();
  89519. var sphereTrimesh_localSpherePos = new Vec3();
  89520. var sphereTrimesh_tmp = new Vec3();
  89521. var sphereTrimesh_va = new Vec3();
  89522. var sphereTrimesh_vb = new Vec3();
  89523. var sphereTrimesh_vc = new Vec3();
  89524. var sphereTrimesh_localSphereAABB = new AABB();
  89525. var sphereTrimesh_triangles = [];
  89526. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.TRIMESH] =
  89527. Narrowphase.prototype.sphereTrimesh = function (
  89528. sphereShape,
  89529. trimeshShape,
  89530. spherePos,
  89531. trimeshPos,
  89532. sphereQuat,
  89533. trimeshQuat,
  89534. sphereBody,
  89535. trimeshBody
  89536. ) {
  89537. var edgeVertexA = sphereTrimesh_edgeVertexA;
  89538. var edgeVertexB = sphereTrimesh_edgeVertexB;
  89539. var edgeVector = sphereTrimesh_edgeVector;
  89540. var edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  89541. var localSpherePos = sphereTrimesh_localSpherePos;
  89542. var tmp = sphereTrimesh_tmp;
  89543. var localSphereAABB = sphereTrimesh_localSphereAABB;
  89544. var v2 = sphereTrimesh_v2;
  89545. var relpos = sphereTrimesh_relpos;
  89546. var triangles = sphereTrimesh_triangles;
  89547. // Convert sphere position to local in the trimesh
  89548. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos);
  89549. // Get the aabb of the sphere locally in the trimesh
  89550. var sphereRadius = sphereShape.radius;
  89551. localSphereAABB.lowerBound.set(
  89552. localSpherePos.x - sphereRadius,
  89553. localSpherePos.y - sphereRadius,
  89554. localSpherePos.z - sphereRadius
  89555. );
  89556. localSphereAABB.upperBound.set(
  89557. localSpherePos.x + sphereRadius,
  89558. localSpherePos.y + sphereRadius,
  89559. localSpherePos.z + sphereRadius
  89560. );
  89561. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles);
  89562. //for (var i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  89563. // Vertices
  89564. var v = sphereTrimesh_v;
  89565. var radiusSquared = sphereShape.radius * sphereShape.radius;
  89566. for(var i=0; i<triangles.length; i++){
  89567. for (var j = 0; j < 3; j++) {
  89568. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v);
  89569. // Check vertex overlap in sphere
  89570. v.vsub(localSpherePos, relpos);
  89571. if(relpos.norm2() <= radiusSquared){
  89572. // Safe up
  89573. v2.copy(v);
  89574. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  89575. v.vsub(spherePos, relpos);
  89576. var r = this.createContactEquation(sphereBody,trimeshBody,sphereShape,trimeshShape);
  89577. r.ni.copy(relpos);
  89578. r.ni.normalize();
  89579. // ri is the vector from sphere center to the sphere surface
  89580. r.ri.copy(r.ni);
  89581. r.ri.scale(sphereShape.radius, r.ri);
  89582. r.ri.vadd(spherePos, r.ri);
  89583. r.ri.vsub(sphereBody.position, r.ri);
  89584. r.rj.copy(v);
  89585. r.rj.vsub(trimeshBody.position, r.rj);
  89586. // Store result
  89587. this.result.push(r);
  89588. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89589. }
  89590. }
  89591. }
  89592. // Check all edges
  89593. for(var i=0; i<triangles.length; i++){
  89594. for (var j = 0; j < 3; j++) {
  89595. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  89596. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + ((j+1)%3)], edgeVertexB);
  89597. edgeVertexB.vsub(edgeVertexA, edgeVector);
  89598. // Project sphere position to the edge
  89599. localSpherePos.vsub(edgeVertexB, tmp);
  89600. var positionAlongEdgeB = tmp.dot(edgeVector);
  89601. localSpherePos.vsub(edgeVertexA, tmp);
  89602. var positionAlongEdgeA = tmp.dot(edgeVector);
  89603. if(positionAlongEdgeA > 0 && positionAlongEdgeB < 0){
  89604. // Now check the orthogonal distance from edge to sphere center
  89605. localSpherePos.vsub(edgeVertexA, tmp);
  89606. edgeVectorUnit.copy(edgeVector);
  89607. edgeVectorUnit.normalize();
  89608. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  89609. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  89610. tmp.vadd(edgeVertexA, tmp);
  89611. // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  89612. var dist = tmp.distanceTo(localSpherePos);
  89613. if(dist < sphereShape.radius){
  89614. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  89615. tmp.vsub(localSpherePos, r.ni);
  89616. r.ni.normalize();
  89617. r.ni.scale(sphereShape.radius, r.ri);
  89618. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  89619. tmp.vsub(trimeshBody.position, r.rj);
  89620. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  89621. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  89622. this.result.push(r);
  89623. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89624. }
  89625. }
  89626. }
  89627. }
  89628. // Triangle faces
  89629. var va = sphereTrimesh_va;
  89630. var vb = sphereTrimesh_vb;
  89631. var vc = sphereTrimesh_vc;
  89632. var normal = sphereTrimesh_normal;
  89633. for(var i=0, N = triangles.length; i !== N; i++){
  89634. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  89635. trimeshShape.getNormal(triangles[i], normal);
  89636. localSpherePos.vsub(va, tmp);
  89637. var dist = tmp.dot(normal);
  89638. normal.scale(dist, tmp);
  89639. localSpherePos.vsub(tmp, tmp);
  89640. // tmp is now the sphere position projected to the triangle plane
  89641. dist = tmp.distanceTo(localSpherePos);
  89642. if(Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius){
  89643. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  89644. tmp.vsub(localSpherePos, r.ni);
  89645. r.ni.normalize();
  89646. r.ni.scale(sphereShape.radius, r.ri);
  89647. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  89648. tmp.vsub(trimeshBody.position, r.rj);
  89649. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  89650. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  89651. this.result.push(r);
  89652. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89653. }
  89654. }
  89655. triangles.length = 0;
  89656. };
  89657. var point_on_plane_to_sphere = new Vec3();
  89658. var plane_to_sphere_ortho = new Vec3();
  89659. /**
  89660. * @method spherePlane
  89661. * @param {Shape} si
  89662. * @param {Shape} sj
  89663. * @param {Vec3} xi
  89664. * @param {Vec3} xj
  89665. * @param {Quaternion} qi
  89666. * @param {Quaternion} qj
  89667. * @param {Body} bi
  89668. * @param {Body} bj
  89669. */
  89670. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.PLANE] =
  89671. Narrowphase.prototype.spherePlane = function(si,sj,xi,xj,qi,qj,bi,bj){
  89672. // We will have one contact in this case
  89673. var r = this.createContactEquation(bi,bj,si,sj);
  89674. // Contact normal
  89675. r.ni.set(0,0,1);
  89676. qj.vmult(r.ni, r.ni);
  89677. r.ni.negate(r.ni); // body i is the sphere, flip normal
  89678. r.ni.normalize(); // Needed?
  89679. // Vector from sphere center to contact point
  89680. r.ni.mult(si.radius, r.ri);
  89681. // Project down sphere on plane
  89682. xi.vsub(xj, point_on_plane_to_sphere);
  89683. r.ni.mult(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  89684. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho,r.rj); // The sphere position projected to plane
  89685. if(-point_on_plane_to_sphere.dot(r.ni) <= si.radius){
  89686. // Make it relative to the body
  89687. var ri = r.ri;
  89688. var rj = r.rj;
  89689. ri.vadd(xi, ri);
  89690. ri.vsub(bi.position, ri);
  89691. rj.vadd(xj, rj);
  89692. rj.vsub(bj.position, rj);
  89693. this.result.push(r);
  89694. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89695. }
  89696. };
  89697. // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  89698. var pointInPolygon_edge = new Vec3();
  89699. var pointInPolygon_edge_x_normal = new Vec3();
  89700. var pointInPolygon_vtp = new Vec3();
  89701. function pointInPolygon(verts, normal, p){
  89702. var positiveResult = null;
  89703. var N = verts.length;
  89704. for(var i=0; i!==N; i++){
  89705. var v = verts[i];
  89706. // Get edge to the next vertex
  89707. var edge = pointInPolygon_edge;
  89708. verts[(i+1) % (N)].vsub(v,edge);
  89709. // Get cross product between polygon normal and the edge
  89710. var edge_x_normal = pointInPolygon_edge_x_normal;
  89711. //var edge_x_normal = new Vec3();
  89712. edge.cross(normal,edge_x_normal);
  89713. // Get vector between point and current vertex
  89714. var vertex_to_p = pointInPolygon_vtp;
  89715. p.vsub(v,vertex_to_p);
  89716. // This dot product determines which side of the edge the point is
  89717. var r = edge_x_normal.dot(vertex_to_p);
  89718. // If all such dot products have same sign, we are inside the polygon.
  89719. if(positiveResult===null || (r>0 && positiveResult===true) || (r<=0 && positiveResult===false)){
  89720. if(positiveResult===null){
  89721. positiveResult = r>0;
  89722. }
  89723. continue;
  89724. } else {
  89725. return false; // Encountered some other sign. Exit.
  89726. }
  89727. }
  89728. // If we got here, all dot products were of the same sign.
  89729. return true;
  89730. }
  89731. var box_to_sphere = new Vec3();
  89732. var sphereBox_ns = new Vec3();
  89733. var sphereBox_ns1 = new Vec3();
  89734. var sphereBox_ns2 = new Vec3();
  89735. var sphereBox_sides = [new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3()];
  89736. var sphereBox_sphere_to_corner = new Vec3();
  89737. var sphereBox_side_ns = new Vec3();
  89738. var sphereBox_side_ns1 = new Vec3();
  89739. var sphereBox_side_ns2 = new Vec3();
  89740. /**
  89741. * @method sphereBox
  89742. * @param {Shape} si
  89743. * @param {Shape} sj
  89744. * @param {Vec3} xi
  89745. * @param {Vec3} xj
  89746. * @param {Quaternion} qi
  89747. * @param {Quaternion} qj
  89748. * @param {Body} bi
  89749. * @param {Body} bj
  89750. */
  89751. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.BOX] =
  89752. Narrowphase.prototype.sphereBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  89753. var v3pool = this.v3pool;
  89754. // we refer to the box as body j
  89755. var sides = sphereBox_sides;
  89756. xi.vsub(xj,box_to_sphere);
  89757. sj.getSideNormals(sides,qj);
  89758. var R = si.radius;
  89759. var penetrating_sides = [];
  89760. // Check side (plane) intersections
  89761. var found = false;
  89762. // Store the resulting side penetration info
  89763. var side_ns = sphereBox_side_ns;
  89764. var side_ns1 = sphereBox_side_ns1;
  89765. var side_ns2 = sphereBox_side_ns2;
  89766. var side_h = null;
  89767. var side_penetrations = 0;
  89768. var side_dot1 = 0;
  89769. var side_dot2 = 0;
  89770. var side_distance = null;
  89771. for(var idx=0,nsides=sides.length; idx!==nsides && found===false; idx++){
  89772. // Get the plane side normal (ns)
  89773. var ns = sphereBox_ns;
  89774. ns.copy(sides[idx]);
  89775. var h = ns.norm();
  89776. ns.normalize();
  89777. // The normal/distance dot product tells which side of the plane we are
  89778. var dot = box_to_sphere.dot(ns);
  89779. if(dot<h+R && dot>0){
  89780. // Intersects plane. Now check the other two dimensions
  89781. var ns1 = sphereBox_ns1;
  89782. var ns2 = sphereBox_ns2;
  89783. ns1.copy(sides[(idx+1)%3]);
  89784. ns2.copy(sides[(idx+2)%3]);
  89785. var h1 = ns1.norm();
  89786. var h2 = ns2.norm();
  89787. ns1.normalize();
  89788. ns2.normalize();
  89789. var dot1 = box_to_sphere.dot(ns1);
  89790. var dot2 = box_to_sphere.dot(ns2);
  89791. if(dot1<h1 && dot1>-h1 && dot2<h2 && dot2>-h2){
  89792. var dist = Math.abs(dot-h-R);
  89793. if(side_distance===null || dist < side_distance){
  89794. side_distance = dist;
  89795. side_dot1 = dot1;
  89796. side_dot2 = dot2;
  89797. side_h = h;
  89798. side_ns.copy(ns);
  89799. side_ns1.copy(ns1);
  89800. side_ns2.copy(ns2);
  89801. side_penetrations++;
  89802. }
  89803. }
  89804. }
  89805. }
  89806. if(side_penetrations){
  89807. found = true;
  89808. var r = this.createContactEquation(bi,bj,si,sj);
  89809. side_ns.mult(-R,r.ri); // Sphere r
  89810. r.ni.copy(side_ns);
  89811. r.ni.negate(r.ni); // Normal should be out of sphere
  89812. side_ns.mult(side_h,side_ns);
  89813. side_ns1.mult(side_dot1,side_ns1);
  89814. side_ns.vadd(side_ns1,side_ns);
  89815. side_ns2.mult(side_dot2,side_ns2);
  89816. side_ns.vadd(side_ns2,r.rj);
  89817. // Make relative to bodies
  89818. r.ri.vadd(xi, r.ri);
  89819. r.ri.vsub(bi.position, r.ri);
  89820. r.rj.vadd(xj, r.rj);
  89821. r.rj.vsub(bj.position, r.rj);
  89822. this.result.push(r);
  89823. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89824. }
  89825. // Check corners
  89826. var rj = v3pool.get();
  89827. var sphere_to_corner = sphereBox_sphere_to_corner;
  89828. for(var j=0; j!==2 && !found; j++){
  89829. for(var k=0; k!==2 && !found; k++){
  89830. for(var l=0; l!==2 && !found; l++){
  89831. rj.set(0,0,0);
  89832. if(j){
  89833. rj.vadd(sides[0],rj);
  89834. } else {
  89835. rj.vsub(sides[0],rj);
  89836. }
  89837. if(k){
  89838. rj.vadd(sides[1],rj);
  89839. } else {
  89840. rj.vsub(sides[1],rj);
  89841. }
  89842. if(l){
  89843. rj.vadd(sides[2],rj);
  89844. } else {
  89845. rj.vsub(sides[2],rj);
  89846. }
  89847. // World position of corner
  89848. xj.vadd(rj,sphere_to_corner);
  89849. sphere_to_corner.vsub(xi,sphere_to_corner);
  89850. if(sphere_to_corner.norm2() < R*R){
  89851. found = true;
  89852. var r = this.createContactEquation(bi,bj,si,sj);
  89853. r.ri.copy(sphere_to_corner);
  89854. r.ri.normalize();
  89855. r.ni.copy(r.ri);
  89856. r.ri.mult(R,r.ri);
  89857. r.rj.copy(rj);
  89858. // Make relative to bodies
  89859. r.ri.vadd(xi, r.ri);
  89860. r.ri.vsub(bi.position, r.ri);
  89861. r.rj.vadd(xj, r.rj);
  89862. r.rj.vsub(bj.position, r.rj);
  89863. this.result.push(r);
  89864. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89865. }
  89866. }
  89867. }
  89868. }
  89869. v3pool.release(rj);
  89870. rj = null;
  89871. // Check edges
  89872. var edgeTangent = v3pool.get();
  89873. var edgeCenter = v3pool.get();
  89874. var r = v3pool.get(); // r = edge center to sphere center
  89875. var orthogonal = v3pool.get();
  89876. var dist = v3pool.get();
  89877. var Nsides = sides.length;
  89878. for(var j=0; j!==Nsides && !found; j++){
  89879. for(var k=0; k!==Nsides && !found; k++){
  89880. if(j%3 !== k%3){
  89881. // Get edge tangent
  89882. sides[k].cross(sides[j],edgeTangent);
  89883. edgeTangent.normalize();
  89884. sides[j].vadd(sides[k], edgeCenter);
  89885. r.copy(xi);
  89886. r.vsub(edgeCenter,r);
  89887. r.vsub(xj,r);
  89888. var orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  89889. edgeTangent.mult(orthonorm,orthogonal); // Vector from edge center to sphere center in the tangent direction
  89890. // Find the third side orthogonal to this one
  89891. var l = 0;
  89892. while(l===j%3 || l===k%3){
  89893. l++;
  89894. }
  89895. // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  89896. dist.copy(xi);
  89897. dist.vsub(orthogonal,dist);
  89898. dist.vsub(edgeCenter,dist);
  89899. dist.vsub(xj,dist);
  89900. // Distances in tangent direction and distance in the plane orthogonal to it
  89901. var tdist = Math.abs(orthonorm);
  89902. var ndist = dist.norm();
  89903. if(tdist < sides[l].norm() && ndist<R){
  89904. found = true;
  89905. var res = this.createContactEquation(bi,bj,si,sj);
  89906. edgeCenter.vadd(orthogonal,res.rj); // box rj
  89907. res.rj.copy(res.rj);
  89908. dist.negate(res.ni);
  89909. res.ni.normalize();
  89910. res.ri.copy(res.rj);
  89911. res.ri.vadd(xj,res.ri);
  89912. res.ri.vsub(xi,res.ri);
  89913. res.ri.normalize();
  89914. res.ri.mult(R,res.ri);
  89915. // Make relative to bodies
  89916. res.ri.vadd(xi, res.ri);
  89917. res.ri.vsub(bi.position, res.ri);
  89918. res.rj.vadd(xj, res.rj);
  89919. res.rj.vsub(bj.position, res.rj);
  89920. this.result.push(res);
  89921. this.createFrictionEquationsFromContact(res, this.frictionResult);
  89922. }
  89923. }
  89924. }
  89925. }
  89926. v3pool.release(edgeTangent,edgeCenter,r,orthogonal,dist);
  89927. };
  89928. var convex_to_sphere = new Vec3();
  89929. var sphereConvex_edge = new Vec3();
  89930. var sphereConvex_edgeUnit = new Vec3();
  89931. var sphereConvex_sphereToCorner = new Vec3();
  89932. var sphereConvex_worldCorner = new Vec3();
  89933. var sphereConvex_worldNormal = new Vec3();
  89934. var sphereConvex_worldPoint = new Vec3();
  89935. var sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  89936. var sphereConvex_penetrationVec = new Vec3();
  89937. var sphereConvex_sphereToWorldPoint = new Vec3();
  89938. /**
  89939. * @method sphereConvex
  89940. * @param {Shape} si
  89941. * @param {Shape} sj
  89942. * @param {Vec3} xi
  89943. * @param {Vec3} xj
  89944. * @param {Quaternion} qi
  89945. * @param {Quaternion} qj
  89946. * @param {Body} bi
  89947. * @param {Body} bj
  89948. */
  89949. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON] =
  89950. Narrowphase.prototype.sphereConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  89951. var v3pool = this.v3pool;
  89952. xi.vsub(xj,convex_to_sphere);
  89953. var normals = sj.faceNormals;
  89954. var faces = sj.faces;
  89955. var verts = sj.vertices;
  89956. var R = si.radius;
  89957. var penetrating_sides = [];
  89958. // if(convex_to_sphere.norm2() > si.boundingSphereRadius + sj.boundingSphereRadius){
  89959. // return;
  89960. // }
  89961. // Check corners
  89962. for(var i=0; i!==verts.length; i++){
  89963. var v = verts[i];
  89964. // World position of corner
  89965. var worldCorner = sphereConvex_worldCorner;
  89966. qj.vmult(v,worldCorner);
  89967. xj.vadd(worldCorner,worldCorner);
  89968. var sphere_to_corner = sphereConvex_sphereToCorner;
  89969. worldCorner.vsub(xi, sphere_to_corner);
  89970. if(sphere_to_corner.norm2() < R * R){
  89971. found = true;
  89972. var r = this.createContactEquation(bi,bj,si,sj);
  89973. r.ri.copy(sphere_to_corner);
  89974. r.ri.normalize();
  89975. r.ni.copy(r.ri);
  89976. r.ri.mult(R,r.ri);
  89977. worldCorner.vsub(xj,r.rj);
  89978. // Should be relative to the body.
  89979. r.ri.vadd(xi, r.ri);
  89980. r.ri.vsub(bi.position, r.ri);
  89981. // Should be relative to the body.
  89982. r.rj.vadd(xj, r.rj);
  89983. r.rj.vsub(bj.position, r.rj);
  89984. this.result.push(r);
  89985. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89986. return;
  89987. }
  89988. }
  89989. // Check side (plane) intersections
  89990. var found = false;
  89991. for(var i=0, nfaces=faces.length; i!==nfaces && found===false; i++){
  89992. var normal = normals[i];
  89993. var face = faces[i];
  89994. // Get world-transformed normal of the face
  89995. var worldNormal = sphereConvex_worldNormal;
  89996. qj.vmult(normal,worldNormal);
  89997. // Get a world vertex from the face
  89998. var worldPoint = sphereConvex_worldPoint;
  89999. qj.vmult(verts[face[0]],worldPoint);
  90000. worldPoint.vadd(xj,worldPoint);
  90001. // Get a point on the sphere, closest to the face normal
  90002. var worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  90003. worldNormal.mult(-R, worldSpherePointClosestToPlane);
  90004. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane);
  90005. // Vector from a face point to the closest point on the sphere
  90006. var penetrationVec = sphereConvex_penetrationVec;
  90007. worldSpherePointClosestToPlane.vsub(worldPoint,penetrationVec);
  90008. // The penetration. Negative value means overlap.
  90009. var penetration = penetrationVec.dot(worldNormal);
  90010. var worldPointToSphere = sphereConvex_sphereToWorldPoint;
  90011. xi.vsub(worldPoint, worldPointToSphere);
  90012. if(penetration < 0 && worldPointToSphere.dot(worldNormal)>0){
  90013. // Intersects plane. Now check if the sphere is inside the face polygon
  90014. var faceVerts = []; // Face vertices, in world coords
  90015. for(var j=0, Nverts=face.length; j!==Nverts; j++){
  90016. var worldVertex = v3pool.get();
  90017. qj.vmult(verts[face[j]], worldVertex);
  90018. xj.vadd(worldVertex,worldVertex);
  90019. faceVerts.push(worldVertex);
  90020. }
  90021. if(pointInPolygon(faceVerts,worldNormal,xi)){ // Is the sphere center in the face polygon?
  90022. found = true;
  90023. var r = this.createContactEquation(bi,bj,si,sj);
  90024. worldNormal.mult(-R, r.ri); // Contact offset, from sphere center to contact
  90025. worldNormal.negate(r.ni); // Normal pointing out of sphere
  90026. var penetrationVec2 = v3pool.get();
  90027. worldNormal.mult(-penetration, penetrationVec2);
  90028. var penetrationSpherePoint = v3pool.get();
  90029. worldNormal.mult(-R, penetrationSpherePoint);
  90030. //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  90031. xi.vsub(xj,r.rj);
  90032. r.rj.vadd(penetrationSpherePoint,r.rj);
  90033. r.rj.vadd(penetrationVec2 , r.rj);
  90034. // Should be relative to the body.
  90035. r.rj.vadd(xj, r.rj);
  90036. r.rj.vsub(bj.position, r.rj);
  90037. // Should be relative to the body.
  90038. r.ri.vadd(xi, r.ri);
  90039. r.ri.vsub(bi.position, r.ri);
  90040. v3pool.release(penetrationVec2);
  90041. v3pool.release(penetrationSpherePoint);
  90042. this.result.push(r);
  90043. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90044. // Release world vertices
  90045. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  90046. v3pool.release(faceVerts[j]);
  90047. }
  90048. return; // We only expect *one* face contact
  90049. } else {
  90050. // Edge?
  90051. for(var j=0; j!==face.length; j++){
  90052. // Get two world transformed vertices
  90053. var v1 = v3pool.get();
  90054. var v2 = v3pool.get();
  90055. qj.vmult(verts[face[(j+1)%face.length]], v1);
  90056. qj.vmult(verts[face[(j+2)%face.length]], v2);
  90057. xj.vadd(v1, v1);
  90058. xj.vadd(v2, v2);
  90059. // Construct edge vector
  90060. var edge = sphereConvex_edge;
  90061. v2.vsub(v1,edge);
  90062. // Construct the same vector, but normalized
  90063. var edgeUnit = sphereConvex_edgeUnit;
  90064. edge.unit(edgeUnit);
  90065. // p is xi projected onto the edge
  90066. var p = v3pool.get();
  90067. var v1_to_xi = v3pool.get();
  90068. xi.vsub(v1, v1_to_xi);
  90069. var dot = v1_to_xi.dot(edgeUnit);
  90070. edgeUnit.mult(dot, p);
  90071. p.vadd(v1, p);
  90072. // Compute a vector from p to the center of the sphere
  90073. var xi_to_p = v3pool.get();
  90074. p.vsub(xi, xi_to_p);
  90075. // Collision if the edge-sphere distance is less than the radius
  90076. // AND if p is in between v1 and v2
  90077. if(dot > 0 && dot*dot<edge.norm2() && xi_to_p.norm2() < R*R){ // Collision if the edge-sphere distance is less than the radius
  90078. // Edge contact!
  90079. var r = this.createContactEquation(bi,bj,si,sj);
  90080. p.vsub(xj,r.rj);
  90081. p.vsub(xi,r.ni);
  90082. r.ni.normalize();
  90083. r.ni.mult(R,r.ri);
  90084. // Should be relative to the body.
  90085. r.rj.vadd(xj, r.rj);
  90086. r.rj.vsub(bj.position, r.rj);
  90087. // Should be relative to the body.
  90088. r.ri.vadd(xi, r.ri);
  90089. r.ri.vsub(bi.position, r.ri);
  90090. this.result.push(r);
  90091. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90092. // Release world vertices
  90093. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  90094. v3pool.release(faceVerts[j]);
  90095. }
  90096. v3pool.release(v1);
  90097. v3pool.release(v2);
  90098. v3pool.release(p);
  90099. v3pool.release(xi_to_p);
  90100. v3pool.release(v1_to_xi);
  90101. return;
  90102. }
  90103. v3pool.release(v1);
  90104. v3pool.release(v2);
  90105. v3pool.release(p);
  90106. v3pool.release(xi_to_p);
  90107. v3pool.release(v1_to_xi);
  90108. }
  90109. }
  90110. // Release world vertices
  90111. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  90112. v3pool.release(faceVerts[j]);
  90113. }
  90114. }
  90115. }
  90116. };
  90117. var planeBox_normal = new Vec3();
  90118. var plane_to_corner = new Vec3();
  90119. /**
  90120. * @method planeBox
  90121. * @param {Array} result
  90122. * @param {Shape} si
  90123. * @param {Shape} sj
  90124. * @param {Vec3} xi
  90125. * @param {Vec3} xj
  90126. * @param {Quaternion} qi
  90127. * @param {Quaternion} qj
  90128. * @param {Body} bi
  90129. * @param {Body} bj
  90130. */
  90131. Narrowphase.prototype[Shape.types.PLANE | Shape.types.BOX] =
  90132. Narrowphase.prototype.planeBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  90133. sj.convexPolyhedronRepresentation.material = sj.material;
  90134. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  90135. this.planeConvex(si,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj);
  90136. };
  90137. var planeConvex_v = new Vec3();
  90138. var planeConvex_normal = new Vec3();
  90139. var planeConvex_relpos = new Vec3();
  90140. var planeConvex_projected = new Vec3();
  90141. /**
  90142. * @method planeConvex
  90143. * @param {Shape} si
  90144. * @param {Shape} sj
  90145. * @param {Vec3} xi
  90146. * @param {Vec3} xj
  90147. * @param {Quaternion} qi
  90148. * @param {Quaternion} qj
  90149. * @param {Body} bi
  90150. * @param {Body} bj
  90151. */
  90152. Narrowphase.prototype[Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON] =
  90153. Narrowphase.prototype.planeConvex = function(
  90154. planeShape,
  90155. convexShape,
  90156. planePosition,
  90157. convexPosition,
  90158. planeQuat,
  90159. convexQuat,
  90160. planeBody,
  90161. convexBody
  90162. ){
  90163. // Simply return the points behind the plane.
  90164. var worldVertex = planeConvex_v,
  90165. worldNormal = planeConvex_normal;
  90166. worldNormal.set(0,0,1);
  90167. planeQuat.vmult(worldNormal,worldNormal); // Turn normal according to plane orientation
  90168. var numContacts = 0;
  90169. var relpos = planeConvex_relpos;
  90170. for(var i = 0; i !== convexShape.vertices.length; i++){
  90171. // Get world convex vertex
  90172. worldVertex.copy(convexShape.vertices[i]);
  90173. convexQuat.vmult(worldVertex, worldVertex);
  90174. convexPosition.vadd(worldVertex, worldVertex);
  90175. worldVertex.vsub(planePosition, relpos);
  90176. var dot = worldNormal.dot(relpos);
  90177. if(dot <= 0.0){
  90178. var r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape);
  90179. // Get vertex position projected on plane
  90180. var projected = planeConvex_projected;
  90181. worldNormal.mult(worldNormal.dot(relpos),projected);
  90182. worldVertex.vsub(projected, projected);
  90183. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  90184. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  90185. // rj is now just the vector from the convex center to the vertex
  90186. worldVertex.vsub(convexPosition, r.rj);
  90187. // Make it relative to the body
  90188. r.ri.vadd(planePosition, r.ri);
  90189. r.ri.vsub(planeBody.position, r.ri);
  90190. r.rj.vadd(convexPosition, r.rj);
  90191. r.rj.vsub(convexBody.position, r.rj);
  90192. this.result.push(r);
  90193. numContacts++;
  90194. if(!this.enableFrictionReduction){
  90195. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90196. }
  90197. }
  90198. }
  90199. if(this.enableFrictionReduction && numContacts){
  90200. this.createFrictionFromAverage(numContacts);
  90201. }
  90202. };
  90203. var convexConvex_sepAxis = new Vec3();
  90204. var convexConvex_q = new Vec3();
  90205. /**
  90206. * @method convexConvex
  90207. * @param {Shape} si
  90208. * @param {Shape} sj
  90209. * @param {Vec3} xi
  90210. * @param {Vec3} xj
  90211. * @param {Quaternion} qi
  90212. * @param {Quaternion} qj
  90213. * @param {Body} bi
  90214. * @param {Body} bj
  90215. */
  90216. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON] =
  90217. Narrowphase.prototype.convexConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  90218. var sepAxis = convexConvex_sepAxis;
  90219. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  90220. return;
  90221. }
  90222. if(si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){
  90223. var res = [];
  90224. var q = convexConvex_q;
  90225. si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);
  90226. var numContacts = 0;
  90227. for(var j = 0; j !== res.length; j++){
  90228. var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  90229. ri = r.ri,
  90230. rj = r.rj;
  90231. sepAxis.negate(r.ni);
  90232. res[j].normal.negate(q);
  90233. q.mult(res[j].depth, q);
  90234. res[j].point.vadd(q, ri);
  90235. rj.copy(res[j].point);
  90236. // Contact points are in world coordinates. Transform back to relative
  90237. ri.vsub(xi,ri);
  90238. rj.vsub(xj,rj);
  90239. // Make relative to bodies
  90240. ri.vadd(xi, ri);
  90241. ri.vsub(bi.position, ri);
  90242. rj.vadd(xj, rj);
  90243. rj.vsub(bj.position, rj);
  90244. this.result.push(r);
  90245. numContacts++;
  90246. if(!this.enableFrictionReduction){
  90247. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90248. }
  90249. }
  90250. if(this.enableFrictionReduction && numContacts){
  90251. this.createFrictionFromAverage(numContacts);
  90252. }
  90253. }
  90254. };
  90255. /**
  90256. * @method convexTrimesh
  90257. * @param {Array} result
  90258. * @param {Shape} si
  90259. * @param {Shape} sj
  90260. * @param {Vec3} xi
  90261. * @param {Vec3} xj
  90262. * @param {Quaternion} qi
  90263. * @param {Quaternion} qj
  90264. * @param {Body} bi
  90265. * @param {Body} bj
  90266. */
  90267. // Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.TRIMESH] =
  90268. // Narrowphase.prototype.convexTrimesh = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  90269. // var sepAxis = convexConvex_sepAxis;
  90270. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  90271. // return;
  90272. // }
  90273. // // Construct a temp hull for each triangle
  90274. // var hullB = new ConvexPolyhedron();
  90275. // hullB.faces = [[0,1,2]];
  90276. // var va = new Vec3();
  90277. // var vb = new Vec3();
  90278. // var vc = new Vec3();
  90279. // hullB.vertices = [
  90280. // va,
  90281. // vb,
  90282. // vc
  90283. // ];
  90284. // for (var i = 0; i < sj.indices.length / 3; i++) {
  90285. // var triangleNormal = new Vec3();
  90286. // sj.getNormal(i, triangleNormal);
  90287. // hullB.faceNormals = [triangleNormal];
  90288. // sj.getTriangleVertices(i, va, vb, vc);
  90289. // var d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  90290. // if(!d){
  90291. // triangleNormal.scale(-1, triangleNormal);
  90292. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  90293. // if(!d){
  90294. // continue;
  90295. // }
  90296. // }
  90297. // var res = [];
  90298. // var q = convexConvex_q;
  90299. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  90300. // for(var j = 0; j !== res.length; j++){
  90301. // var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  90302. // ri = r.ri,
  90303. // rj = r.rj;
  90304. // r.ni.copy(triangleNormal);
  90305. // r.ni.negate(r.ni);
  90306. // res[j].normal.negate(q);
  90307. // q.mult(res[j].depth, q);
  90308. // res[j].point.vadd(q, ri);
  90309. // rj.copy(res[j].point);
  90310. // // Contact points are in world coordinates. Transform back to relative
  90311. // ri.vsub(xi,ri);
  90312. // rj.vsub(xj,rj);
  90313. // // Make relative to bodies
  90314. // ri.vadd(xi, ri);
  90315. // ri.vsub(bi.position, ri);
  90316. // rj.vadd(xj, rj);
  90317. // rj.vsub(bj.position, rj);
  90318. // result.push(r);
  90319. // }
  90320. // }
  90321. // };
  90322. var particlePlane_normal = new Vec3();
  90323. var particlePlane_relpos = new Vec3();
  90324. var particlePlane_projected = new Vec3();
  90325. /**
  90326. * @method particlePlane
  90327. * @param {Array} result
  90328. * @param {Shape} si
  90329. * @param {Shape} sj
  90330. * @param {Vec3} xi
  90331. * @param {Vec3} xj
  90332. * @param {Quaternion} qi
  90333. * @param {Quaternion} qj
  90334. * @param {Body} bi
  90335. * @param {Body} bj
  90336. */
  90337. Narrowphase.prototype[Shape.types.PLANE | Shape.types.PARTICLE] =
  90338. Narrowphase.prototype.planeParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  90339. var normal = particlePlane_normal;
  90340. normal.set(0,0,1);
  90341. bj.quaternion.vmult(normal,normal); // Turn normal according to plane orientation
  90342. var relpos = particlePlane_relpos;
  90343. xi.vsub(bj.position,relpos);
  90344. var dot = normal.dot(relpos);
  90345. if(dot <= 0.0){
  90346. var r = this.createContactEquation(bi,bj,si,sj);
  90347. r.ni.copy(normal); // Contact normal is the plane normal
  90348. r.ni.negate(r.ni);
  90349. r.ri.set(0,0,0); // Center of particle
  90350. // Get particle position projected on plane
  90351. var projected = particlePlane_projected;
  90352. normal.mult(normal.dot(xi),projected);
  90353. xi.vsub(projected,projected);
  90354. //projected.vadd(bj.position,projected);
  90355. // rj is now the projected world position minus plane position
  90356. r.rj.copy(projected);
  90357. this.result.push(r);
  90358. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90359. }
  90360. };
  90361. var particleSphere_normal = new Vec3();
  90362. /**
  90363. * @method particleSphere
  90364. * @param {Array} result
  90365. * @param {Shape} si
  90366. * @param {Shape} sj
  90367. * @param {Vec3} xi
  90368. * @param {Vec3} xj
  90369. * @param {Quaternion} qi
  90370. * @param {Quaternion} qj
  90371. * @param {Body} bi
  90372. * @param {Body} bj
  90373. */
  90374. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.SPHERE] =
  90375. Narrowphase.prototype.sphereParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  90376. // The normal is the unit vector from sphere center to particle center
  90377. var normal = particleSphere_normal;
  90378. normal.set(0,0,1);
  90379. xi.vsub(xj,normal);
  90380. var lengthSquared = normal.norm2();
  90381. if(lengthSquared <= sj.radius * sj.radius){
  90382. var r = this.createContactEquation(bi,bj,si,sj);
  90383. normal.normalize();
  90384. r.rj.copy(normal);
  90385. r.rj.mult(sj.radius,r.rj);
  90386. r.ni.copy(normal); // Contact normal
  90387. r.ni.negate(r.ni);
  90388. r.ri.set(0,0,0); // Center of particle
  90389. this.result.push(r);
  90390. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90391. }
  90392. };
  90393. // WIP
  90394. var cqj = new Quaternion();
  90395. var convexParticle_local = new Vec3();
  90396. var convexParticle_normal = new Vec3();
  90397. var convexParticle_penetratedFaceNormal = new Vec3();
  90398. var convexParticle_vertexToParticle = new Vec3();
  90399. var convexParticle_worldPenetrationVec = new Vec3();
  90400. /**
  90401. * @method convexParticle
  90402. * @param {Array} result
  90403. * @param {Shape} si
  90404. * @param {Shape} sj
  90405. * @param {Vec3} xi
  90406. * @param {Vec3} xj
  90407. * @param {Quaternion} qi
  90408. * @param {Quaternion} qj
  90409. * @param {Body} bi
  90410. * @param {Body} bj
  90411. */
  90412. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON] =
  90413. Narrowphase.prototype.convexParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  90414. var penetratedFaceIndex = -1;
  90415. var penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  90416. var worldPenetrationVec = convexParticle_worldPenetrationVec;
  90417. var minPenetration = null;
  90418. var numDetectedFaces = 0;
  90419. // Convert particle position xi to local coords in the convex
  90420. var local = convexParticle_local;
  90421. local.copy(xi);
  90422. local.vsub(xj,local); // Convert position to relative the convex origin
  90423. qj.conjugate(cqj);
  90424. cqj.vmult(local,local);
  90425. if(sj.pointIsInside(local)){
  90426. if(sj.worldVerticesNeedsUpdate){
  90427. sj.computeWorldVertices(xj,qj);
  90428. }
  90429. if(sj.worldFaceNormalsNeedsUpdate){
  90430. sj.computeWorldFaceNormals(qj);
  90431. }
  90432. // For each world polygon in the polyhedra
  90433. for(var i=0,nfaces=sj.faces.length; i!==nfaces; i++){
  90434. // Construct world face vertices
  90435. var verts = [ sj.worldVertices[ sj.faces[i][0] ] ];
  90436. var normal = sj.worldFaceNormals[i];
  90437. // Check how much the particle penetrates the polygon plane.
  90438. xi.vsub(verts[0],convexParticle_vertexToParticle);
  90439. var penetration = -normal.dot(convexParticle_vertexToParticle);
  90440. if(minPenetration===null || Math.abs(penetration)<Math.abs(minPenetration)){
  90441. minPenetration = penetration;
  90442. penetratedFaceIndex = i;
  90443. penetratedFaceNormal.copy(normal);
  90444. numDetectedFaces++;
  90445. }
  90446. }
  90447. if(penetratedFaceIndex!==-1){
  90448. // Setup contact
  90449. var r = this.createContactEquation(bi,bj,si,sj);
  90450. penetratedFaceNormal.mult(minPenetration, worldPenetrationVec);
  90451. // rj is the particle position projected to the face
  90452. worldPenetrationVec.vadd(xi,worldPenetrationVec);
  90453. worldPenetrationVec.vsub(xj,worldPenetrationVec);
  90454. r.rj.copy(worldPenetrationVec);
  90455. //var projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  90456. //projectedToFace.copy(r.rj);
  90457. //qj.vmult(r.rj,r.rj);
  90458. penetratedFaceNormal.negate( r.ni ); // Contact normal
  90459. r.ri.set(0,0,0); // Center of particle
  90460. var ri = r.ri,
  90461. rj = r.rj;
  90462. // Make relative to bodies
  90463. ri.vadd(xi, ri);
  90464. ri.vsub(bi.position, ri);
  90465. rj.vadd(xj, rj);
  90466. rj.vsub(bj.position, rj);
  90467. this.result.push(r);
  90468. this.createFrictionEquationsFromContact(r, this.frictionResult);
  90469. } else {
  90470. console.warn("Point found inside convex, but did not find penetrating face!");
  90471. }
  90472. }
  90473. };
  90474. Narrowphase.prototype[Shape.types.BOX | Shape.types.HEIGHTFIELD] =
  90475. Narrowphase.prototype.boxHeightfield = function (si,sj,xi,xj,qi,qj,bi,bj){
  90476. si.convexPolyhedronRepresentation.material = si.material;
  90477. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  90478. this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj);
  90479. };
  90480. var convexHeightfield_tmp1 = new Vec3();
  90481. var convexHeightfield_tmp2 = new Vec3();
  90482. var convexHeightfield_faceList = [0];
  90483. /**
  90484. * @method convexHeightfield
  90485. */
  90486. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD] =
  90487. Narrowphase.prototype.convexHeightfield = function (
  90488. convexShape,
  90489. hfShape,
  90490. convexPos,
  90491. hfPos,
  90492. convexQuat,
  90493. hfQuat,
  90494. convexBody,
  90495. hfBody
  90496. ){
  90497. var data = hfShape.data,
  90498. w = hfShape.elementSize,
  90499. radius = convexShape.boundingSphereRadius,
  90500. worldPillarOffset = convexHeightfield_tmp2,
  90501. faceList = convexHeightfield_faceList;
  90502. // Get sphere position to heightfield local!
  90503. var localConvexPos = convexHeightfield_tmp1;
  90504. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos);
  90505. // Get the index of the data points to test against
  90506. var iMinX = Math.floor((localConvexPos.x - radius) / w) - 1,
  90507. iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1,
  90508. iMinY = Math.floor((localConvexPos.y - radius) / w) - 1,
  90509. iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1;
  90510. // Bail out if we are out of the terrain
  90511. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length){
  90512. return;
  90513. }
  90514. // Clamp index to edges
  90515. if(iMinX < 0){ iMinX = 0; }
  90516. if(iMaxX < 0){ iMaxX = 0; }
  90517. if(iMinY < 0){ iMinY = 0; }
  90518. if(iMaxY < 0){ iMaxY = 0; }
  90519. if(iMinX >= data.length){ iMinX = data.length - 1; }
  90520. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  90521. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  90522. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  90523. var minMax = [];
  90524. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  90525. var min = minMax[0];
  90526. var max = minMax[1];
  90527. // Bail out if we're cant touch the bounding height box
  90528. if(localConvexPos.z - radius > max || localConvexPos.z + radius < min){
  90529. return;
  90530. }
  90531. for(var i = iMinX; i < iMaxX; i++){
  90532. for(var j = iMinY; j < iMaxY; j++){
  90533. // Lower triangle
  90534. hfShape.getConvexTrianglePillar(i, j, false);
  90535. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  90536. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  90537. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  90538. }
  90539. // Upper triangle
  90540. hfShape.getConvexTrianglePillar(i, j, true);
  90541. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  90542. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  90543. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  90544. }
  90545. }
  90546. }
  90547. };
  90548. var sphereHeightfield_tmp1 = new Vec3();
  90549. var sphereHeightfield_tmp2 = new Vec3();
  90550. /**
  90551. * @method sphereHeightfield
  90552. */
  90553. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.HEIGHTFIELD] =
  90554. Narrowphase.prototype.sphereHeightfield = function (
  90555. sphereShape,
  90556. hfShape,
  90557. spherePos,
  90558. hfPos,
  90559. sphereQuat,
  90560. hfQuat,
  90561. sphereBody,
  90562. hfBody
  90563. ){
  90564. var data = hfShape.data,
  90565. radius = sphereShape.radius,
  90566. w = hfShape.elementSize,
  90567. worldPillarOffset = sphereHeightfield_tmp2;
  90568. // Get sphere position to heightfield local!
  90569. var localSpherePos = sphereHeightfield_tmp1;
  90570. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos);
  90571. // Get the index of the data points to test against
  90572. var iMinX = Math.floor((localSpherePos.x - radius) / w) - 1,
  90573. iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1,
  90574. iMinY = Math.floor((localSpherePos.y - radius) / w) - 1,
  90575. iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1;
  90576. // Bail out if we are out of the terrain
  90577. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMaxY > data[0].length){
  90578. return;
  90579. }
  90580. // Clamp index to edges
  90581. if(iMinX < 0){ iMinX = 0; }
  90582. if(iMaxX < 0){ iMaxX = 0; }
  90583. if(iMinY < 0){ iMinY = 0; }
  90584. if(iMaxY < 0){ iMaxY = 0; }
  90585. if(iMinX >= data.length){ iMinX = data.length - 1; }
  90586. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  90587. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  90588. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  90589. var minMax = [];
  90590. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  90591. var min = minMax[0];
  90592. var max = minMax[1];
  90593. // Bail out if we're cant touch the bounding height box
  90594. if(localSpherePos.z - radius > max || localSpherePos.z + radius < min){
  90595. return;
  90596. }
  90597. var result = this.result;
  90598. for(var i = iMinX; i < iMaxX; i++){
  90599. for(var j = iMinY; j < iMaxY; j++){
  90600. var numContactsBefore = result.length;
  90601. // Lower triangle
  90602. hfShape.getConvexTrianglePillar(i, j, false);
  90603. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  90604. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  90605. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  90606. }
  90607. // Upper triangle
  90608. hfShape.getConvexTrianglePillar(i, j, true);
  90609. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  90610. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  90611. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  90612. }
  90613. var numContacts = result.length - numContactsBefore;
  90614. if(numContacts > 2){
  90615. return;
  90616. }
  90617. /*
  90618. // Skip all but 1
  90619. for (var k = 0; k < numContacts - 1; k++) {
  90620. result.pop();
  90621. }
  90622. */
  90623. }
  90624. }
  90625. };
  90626. },{"../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){
  90627. /* global performance */
  90628. module.exports = World;
  90629. var Shape = _dereq_('../shapes/Shape');
  90630. var Vec3 = _dereq_('../math/Vec3');
  90631. var Quaternion = _dereq_('../math/Quaternion');
  90632. var GSSolver = _dereq_('../solver/GSSolver');
  90633. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  90634. var ContactEquation = _dereq_('../equations/ContactEquation');
  90635. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  90636. var Narrowphase = _dereq_('./Narrowphase');
  90637. var EventTarget = _dereq_('../utils/EventTarget');
  90638. var ArrayCollisionMatrix = _dereq_('../collision/ArrayCollisionMatrix');
  90639. var Material = _dereq_('../material/Material');
  90640. var ContactMaterial = _dereq_('../material/ContactMaterial');
  90641. var Body = _dereq_('../objects/Body');
  90642. var TupleDictionary = _dereq_('../utils/TupleDictionary');
  90643. var RaycastResult = _dereq_('../collision/RaycastResult');
  90644. var AABB = _dereq_('../collision/AABB');
  90645. var Ray = _dereq_('../collision/Ray');
  90646. var NaiveBroadphase = _dereq_('../collision/NaiveBroadphase');
  90647. /**
  90648. * The physics world
  90649. * @class World
  90650. * @constructor
  90651. * @extends EventTarget
  90652. */
  90653. function World(){
  90654. EventTarget.apply(this);
  90655. /**
  90656. * 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.
  90657. * @property {Number} dt
  90658. */
  90659. this.dt = -1;
  90660. /**
  90661. * Makes bodies go to sleep when they've been inactive
  90662. * @property allowSleep
  90663. * @type {Boolean}
  90664. */
  90665. this.allowSleep = false;
  90666. /**
  90667. * All the current contacts (instances of ContactEquation) in the world.
  90668. * @property contacts
  90669. * @type {Array}
  90670. */
  90671. this.contacts = [];
  90672. this.frictionEquations = [];
  90673. /**
  90674. * 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).
  90675. * @property quatNormalizeSkip
  90676. * @type {Number}
  90677. */
  90678. this.quatNormalizeSkip = 0;
  90679. /**
  90680. * Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false.
  90681. * @property quatNormalizeFast
  90682. * @type {Boolean}
  90683. * @see Quaternion.normalizeFast
  90684. * @see Quaternion.normalize
  90685. */
  90686. this.quatNormalizeFast = false;
  90687. /**
  90688. * The wall-clock time since simulation start
  90689. * @property time
  90690. * @type {Number}
  90691. */
  90692. this.time = 0.0;
  90693. /**
  90694. * Number of timesteps taken since start
  90695. * @property stepnumber
  90696. * @type {Number}
  90697. */
  90698. this.stepnumber = 0;
  90699. /// Default and last timestep sizes
  90700. this.default_dt = 1/60;
  90701. this.nextId = 0;
  90702. /**
  90703. * @property gravity
  90704. * @type {Vec3}
  90705. */
  90706. this.gravity = new Vec3();
  90707. /**
  90708. * @property broadphase
  90709. * @type {Broadphase}
  90710. */
  90711. this.broadphase = new NaiveBroadphase();
  90712. /**
  90713. * @property bodies
  90714. * @type {Array}
  90715. */
  90716. this.bodies = [];
  90717. /**
  90718. * @property solver
  90719. * @type {Solver}
  90720. */
  90721. this.solver = new GSSolver();
  90722. /**
  90723. * @property constraints
  90724. * @type {Array}
  90725. */
  90726. this.constraints = [];
  90727. /**
  90728. * @property narrowphase
  90729. * @type {Narrowphase}
  90730. */
  90731. this.narrowphase = new Narrowphase(this);
  90732. /**
  90733. * @property {ArrayCollisionMatrix} collisionMatrix
  90734. * @type {ArrayCollisionMatrix}
  90735. */
  90736. this.collisionMatrix = new ArrayCollisionMatrix();
  90737. /**
  90738. * CollisionMatrix from the previous step.
  90739. * @property {ArrayCollisionMatrix} collisionMatrixPrevious
  90740. * @type {ArrayCollisionMatrix}
  90741. */
  90742. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  90743. /**
  90744. * All added materials
  90745. * @property materials
  90746. * @type {Array}
  90747. */
  90748. this.materials = [];
  90749. /**
  90750. * @property contactmaterials
  90751. * @type {Array}
  90752. */
  90753. this.contactmaterials = [];
  90754. /**
  90755. * Used to look up a ContactMaterial given two instances of Material.
  90756. * @property {TupleDictionary} contactMaterialTable
  90757. */
  90758. this.contactMaterialTable = new TupleDictionary();
  90759. this.defaultMaterial = new Material("default");
  90760. /**
  90761. * This contact material is used if no suitable contactmaterial is found for a contact.
  90762. * @property defaultContactMaterial
  90763. * @type {ContactMaterial}
  90764. */
  90765. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 });
  90766. /**
  90767. * @property doProfiling
  90768. * @type {Boolean}
  90769. */
  90770. this.doProfiling = false;
  90771. /**
  90772. * @property profile
  90773. * @type {Object}
  90774. */
  90775. this.profile = {
  90776. solve:0,
  90777. makeContactConstraints:0,
  90778. broadphase:0,
  90779. integrate:0,
  90780. narrowphase:0,
  90781. };
  90782. /**
  90783. * @property subsystems
  90784. * @type {Array}
  90785. */
  90786. this.subsystems = [];
  90787. this.addBodyEvent = {
  90788. type:"addBody",
  90789. body : null,
  90790. };
  90791. this.removeBodyEvent = {
  90792. type:"removeBody",
  90793. body : null,
  90794. };
  90795. }
  90796. World.prototype = new EventTarget();
  90797. // Temp stuff
  90798. var tmpAABB1 = new AABB();
  90799. var tmpArray1 = [];
  90800. var tmpRay = new Ray();
  90801. /**
  90802. * Get the contact material between materials m1 and m2
  90803. * @method getContactMaterial
  90804. * @param {Material} m1
  90805. * @param {Material} m2
  90806. * @return {ContactMaterial} The contact material if it was found.
  90807. */
  90808. World.prototype.getContactMaterial = function(m1,m2){
  90809. return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]];
  90810. };
  90811. /**
  90812. * Get number of objects in the world.
  90813. * @method numObjects
  90814. * @return {Number}
  90815. * @deprecated
  90816. */
  90817. World.prototype.numObjects = function(){
  90818. return this.bodies.length;
  90819. };
  90820. /**
  90821. * Store old collision state info
  90822. * @method collisionMatrixTick
  90823. */
  90824. World.prototype.collisionMatrixTick = function(){
  90825. var temp = this.collisionMatrixPrevious;
  90826. this.collisionMatrixPrevious = this.collisionMatrix;
  90827. this.collisionMatrix = temp;
  90828. this.collisionMatrix.reset();
  90829. };
  90830. /**
  90831. * Add a rigid body to the simulation.
  90832. * @method add
  90833. * @param {Body} body
  90834. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  90835. * @todo Adding an array of bodies should be possible. This would save some loops too
  90836. * @deprecated Use .addBody instead
  90837. */
  90838. World.prototype.add = World.prototype.addBody = function(body){
  90839. if(this.bodies.indexOf(body) !== -1){
  90840. return;
  90841. }
  90842. body.index = this.bodies.length;
  90843. this.bodies.push(body);
  90844. body.world = this;
  90845. body.initPosition.copy(body.position);
  90846. body.initVelocity.copy(body.velocity);
  90847. body.timeLastSleepy = this.time;
  90848. if(body instanceof Body){
  90849. body.initAngularVelocity.copy(body.angularVelocity);
  90850. body.initQuaternion.copy(body.quaternion);
  90851. }
  90852. this.collisionMatrix.setNumObjects(this.bodies.length);
  90853. this.addBodyEvent.body = body;
  90854. this.dispatchEvent(this.addBodyEvent);
  90855. };
  90856. /**
  90857. * Add a constraint to the simulation.
  90858. * @method addConstraint
  90859. * @param {Constraint} c
  90860. */
  90861. World.prototype.addConstraint = function(c){
  90862. this.constraints.push(c);
  90863. };
  90864. /**
  90865. * Removes a constraint
  90866. * @method removeConstraint
  90867. * @param {Constraint} c
  90868. */
  90869. World.prototype.removeConstraint = function(c){
  90870. var idx = this.constraints.indexOf(c);
  90871. if(idx!==-1){
  90872. this.constraints.splice(idx,1);
  90873. }
  90874. };
  90875. /**
  90876. * Raycast test
  90877. * @method rayTest
  90878. * @param {Vec3} from
  90879. * @param {Vec3} to
  90880. * @param {Function|RaycastResult} result
  90881. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  90882. */
  90883. World.prototype.rayTest = function(from, to, result){
  90884. if(result instanceof RaycastResult){
  90885. // Do raycastclosest
  90886. this.raycastClosest(from, to, {
  90887. skipBackfaces: true
  90888. }, result);
  90889. } else {
  90890. // Do raycastAll
  90891. this.raycastAll(from, to, {
  90892. skipBackfaces: true
  90893. }, result);
  90894. }
  90895. };
  90896. /**
  90897. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  90898. * @method raycastAll
  90899. * @param {Vec3} from
  90900. * @param {Vec3} to
  90901. * @param {Object} options
  90902. * @param {number} [options.collisionFilterMask=-1]
  90903. * @param {number} [options.collisionFilterGroup=-1]
  90904. * @param {boolean} [options.skipBackfaces=false]
  90905. * @param {boolean} [options.checkCollisionResponse=true]
  90906. * @param {Function} callback
  90907. * @return {boolean} True if any body was hit.
  90908. */
  90909. World.prototype.raycastAll = function(from, to, options, callback){
  90910. options.mode = Ray.ALL;
  90911. options.from = from;
  90912. options.to = to;
  90913. options.callback = callback;
  90914. return tmpRay.intersectWorld(this, options);
  90915. };
  90916. /**
  90917. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  90918. * @method raycastAny
  90919. * @param {Vec3} from
  90920. * @param {Vec3} to
  90921. * @param {Object} options
  90922. * @param {number} [options.collisionFilterMask=-1]
  90923. * @param {number} [options.collisionFilterGroup=-1]
  90924. * @param {boolean} [options.skipBackfaces=false]
  90925. * @param {boolean} [options.checkCollisionResponse=true]
  90926. * @param {RaycastResult} result
  90927. * @return {boolean} True if any body was hit.
  90928. */
  90929. World.prototype.raycastAny = function(from, to, options, result){
  90930. options.mode = Ray.ANY;
  90931. options.from = from;
  90932. options.to = to;
  90933. options.result = result;
  90934. return tmpRay.intersectWorld(this, options);
  90935. };
  90936. /**
  90937. * Ray cast, and return information of the closest hit.
  90938. * @method raycastClosest
  90939. * @param {Vec3} from
  90940. * @param {Vec3} to
  90941. * @param {Object} options
  90942. * @param {number} [options.collisionFilterMask=-1]
  90943. * @param {number} [options.collisionFilterGroup=-1]
  90944. * @param {boolean} [options.skipBackfaces=false]
  90945. * @param {boolean} [options.checkCollisionResponse=true]
  90946. * @param {RaycastResult} result
  90947. * @return {boolean} True if any body was hit.
  90948. */
  90949. World.prototype.raycastClosest = function(from, to, options, result){
  90950. options.mode = Ray.CLOSEST;
  90951. options.from = from;
  90952. options.to = to;
  90953. options.result = result;
  90954. return tmpRay.intersectWorld(this, options);
  90955. };
  90956. /**
  90957. * Remove a rigid body from the simulation.
  90958. * @method remove
  90959. * @param {Body} body
  90960. * @deprecated Use .removeBody instead
  90961. */
  90962. World.prototype.remove = function(body){
  90963. body.world = null;
  90964. var n = this.bodies.length-1,
  90965. bodies = this.bodies,
  90966. idx = bodies.indexOf(body);
  90967. if(idx !== -1){
  90968. bodies.splice(idx, 1); // Todo: should use a garbage free method
  90969. // Recompute index
  90970. for(var i=0; i!==bodies.length; i++){
  90971. bodies[i].index = i;
  90972. }
  90973. this.collisionMatrix.setNumObjects(n);
  90974. this.removeBodyEvent.body = body;
  90975. this.dispatchEvent(this.removeBodyEvent);
  90976. }
  90977. };
  90978. /**
  90979. * Remove a rigid body from the simulation.
  90980. * @method removeBody
  90981. * @param {Body} body
  90982. */
  90983. World.prototype.removeBody = World.prototype.remove;
  90984. /**
  90985. * Adds a material to the World.
  90986. * @method addMaterial
  90987. * @param {Material} m
  90988. * @todo Necessary?
  90989. */
  90990. World.prototype.addMaterial = function(m){
  90991. this.materials.push(m);
  90992. };
  90993. /**
  90994. * Adds a contact material to the World
  90995. * @method addContactMaterial
  90996. * @param {ContactMaterial} cmat
  90997. */
  90998. World.prototype.addContactMaterial = function(cmat) {
  90999. // Add contact material
  91000. this.contactmaterials.push(cmat);
  91001. // Add current contact material to the material table
  91002. this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat);
  91003. };
  91004. // performance.now()
  91005. if(typeof performance === 'undefined'){
  91006. performance = {};
  91007. }
  91008. if(!performance.now){
  91009. var nowOffset = Date.now();
  91010. if (performance.timing && performance.timing.navigationStart){
  91011. nowOffset = performance.timing.navigationStart;
  91012. }
  91013. performance.now = function(){
  91014. return Date.now() - nowOffset;
  91015. };
  91016. }
  91017. var step_tmp1 = new Vec3();
  91018. /**
  91019. * Step the physics world forward in time.
  91020. *
  91021. * 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.
  91022. *
  91023. * @method step
  91024. * @param {Number} dt The fixed time step size to use.
  91025. * @param {Number} [timeSinceLastCalled] The time elapsed since the function was last called.
  91026. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
  91027. *
  91028. * @example
  91029. * // fixed timestepping without interpolation
  91030. * world.step(1/60);
  91031. *
  91032. * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  91033. */
  91034. World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){
  91035. maxSubSteps = maxSubSteps || 10;
  91036. timeSinceLastCalled = timeSinceLastCalled || 0;
  91037. if(timeSinceLastCalled === 0){ // Fixed, simple stepping
  91038. this.internalStep(dt);
  91039. // Increment time
  91040. this.time += dt;
  91041. } else {
  91042. // Compute the number of fixed steps we should have taken since the last step
  91043. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  91044. internalSteps = Math.min(internalSteps,maxSubSteps);
  91045. // Do some fixed steps to catch up
  91046. var t0 = performance.now();
  91047. for(var i=0; i!==internalSteps; i++){
  91048. this.internalStep(dt);
  91049. if(performance.now() - t0 > dt * 1000){
  91050. // We are slower than real-time. Better bail out.
  91051. break;
  91052. }
  91053. }
  91054. // Increment internal clock
  91055. this.time += timeSinceLastCalled;
  91056. // Compute "Left over" time step
  91057. var h = this.time % dt;
  91058. var h_div_dt = h / dt;
  91059. var interpvelo = step_tmp1;
  91060. var bodies = this.bodies;
  91061. for(var j=0; j !== bodies.length; j++){
  91062. var b = bodies[j];
  91063. if(b.type !== Body.STATIC && b.sleepState !== Body.SLEEPING){
  91064. // Interpolate
  91065. b.position.vsub(b.previousPosition, interpvelo);
  91066. interpvelo.scale(h_div_dt, interpvelo);
  91067. b.position.vadd(interpvelo, b.interpolatedPosition);
  91068. // TODO: interpolate quaternion
  91069. // b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt;
  91070. } else {
  91071. // For static bodies, just copy. Who else will do it?
  91072. b.interpolatedPosition.copy(b.position);
  91073. b.interpolatedQuaternion.copy(b.quaternion);
  91074. }
  91075. }
  91076. }
  91077. };
  91078. /**
  91079. * Step the simulation
  91080. * @method step
  91081. * @param {Number} dt
  91082. */
  91083. var World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory
  91084. World_step_preStepEvent = {type:"preStep"},
  91085. World_step_collideEvent = {type:"collide", body:null, contact:null },
  91086. World_step_oldContacts = [], // Pools for unused objects
  91087. World_step_frictionEquationPool = [],
  91088. World_step_p1 = [], // Reusable arrays for collision pairs
  91089. World_step_p2 = [],
  91090. World_step_gvec = new Vec3(), // Temporary vectors and quats
  91091. World_step_vi = new Vec3(),
  91092. World_step_vj = new Vec3(),
  91093. World_step_wi = new Vec3(),
  91094. World_step_wj = new Vec3(),
  91095. World_step_t1 = new Vec3(),
  91096. World_step_t2 = new Vec3(),
  91097. World_step_rixn = new Vec3(),
  91098. World_step_rjxn = new Vec3(),
  91099. World_step_step_q = new Quaternion(),
  91100. World_step_step_w = new Quaternion(),
  91101. World_step_step_wq = new Quaternion(),
  91102. invI_tau_dt = new Vec3();
  91103. World.prototype.internalStep = function(dt){
  91104. this.dt = dt;
  91105. var world = this,
  91106. that = this,
  91107. contacts = this.contacts,
  91108. p1 = World_step_p1,
  91109. p2 = World_step_p2,
  91110. N = this.numObjects(),
  91111. bodies = this.bodies,
  91112. solver = this.solver,
  91113. gravity = this.gravity,
  91114. doProfiling = this.doProfiling,
  91115. profile = this.profile,
  91116. DYNAMIC = Body.DYNAMIC,
  91117. profilingStart,
  91118. constraints = this.constraints,
  91119. frictionEquationPool = World_step_frictionEquationPool,
  91120. gnorm = gravity.norm(),
  91121. gx = gravity.x,
  91122. gy = gravity.y,
  91123. gz = gravity.z,
  91124. i=0;
  91125. if(doProfiling){
  91126. profilingStart = performance.now();
  91127. }
  91128. // Add gravity to all objects
  91129. for(i=0; i!==N; i++){
  91130. var bi = bodies[i];
  91131. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  91132. var f = bi.force, m = bi.mass;
  91133. f.x += m*gx;
  91134. f.y += m*gy;
  91135. f.z += m*gz;
  91136. }
  91137. }
  91138. // Update subsystems
  91139. for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){
  91140. this.subsystems[i].update();
  91141. }
  91142. // Collision detection
  91143. if(doProfiling){ profilingStart = performance.now(); }
  91144. p1.length = 0; // Clean up pair arrays from last step
  91145. p2.length = 0;
  91146. this.broadphase.collisionPairs(this,p1,p2);
  91147. if(doProfiling){ profile.broadphase = performance.now() - profilingStart; }
  91148. // Remove constrained pairs with collideConnected == false
  91149. var Nconstraints = constraints.length;
  91150. for(i=0; i!==Nconstraints; i++){
  91151. var c = constraints[i];
  91152. if(!c.collideConnected){
  91153. for(var j = p1.length-1; j>=0; j-=1){
  91154. if( (c.bodyA === p1[j] && c.bodyB === p2[j]) ||
  91155. (c.bodyB === p1[j] && c.bodyA === p2[j])){
  91156. p1.splice(j, 1);
  91157. p2.splice(j, 1);
  91158. }
  91159. }
  91160. }
  91161. }
  91162. this.collisionMatrixTick();
  91163. // Generate contacts
  91164. if(doProfiling){ profilingStart = performance.now(); }
  91165. var oldcontacts = World_step_oldContacts;
  91166. var NoldContacts = contacts.length;
  91167. for(i=0; i!==NoldContacts; i++){
  91168. oldcontacts.push(contacts[i]);
  91169. }
  91170. contacts.length = 0;
  91171. // Transfer FrictionEquation from current list to the pool for reuse
  91172. var NoldFrictionEquations = this.frictionEquations.length;
  91173. for(i=0; i!==NoldFrictionEquations; i++){
  91174. frictionEquationPool.push(this.frictionEquations[i]);
  91175. }
  91176. this.frictionEquations.length = 0;
  91177. this.narrowphase.getContacts(
  91178. p1,
  91179. p2,
  91180. this,
  91181. contacts,
  91182. oldcontacts, // To be reused
  91183. this.frictionEquations,
  91184. frictionEquationPool
  91185. );
  91186. if(doProfiling){
  91187. profile.narrowphase = performance.now() - profilingStart;
  91188. }
  91189. // Loop over all collisions
  91190. if(doProfiling){
  91191. profilingStart = performance.now();
  91192. }
  91193. // Add all friction eqs
  91194. for (var i = 0; i < this.frictionEquations.length; i++) {
  91195. solver.addEquation(this.frictionEquations[i]);
  91196. }
  91197. var ncontacts = contacts.length;
  91198. for(var k=0; k!==ncontacts; k++){
  91199. // Current contact
  91200. var c = contacts[k];
  91201. // Get current collision indeces
  91202. var bi = c.bi,
  91203. bj = c.bj,
  91204. si = c.si,
  91205. sj = c.sj;
  91206. // Get collision properties
  91207. var cm;
  91208. if(bi.material && bj.material){
  91209. cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial;
  91210. } else {
  91211. cm = this.defaultContactMaterial;
  91212. }
  91213. // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  91214. var mu = cm.friction;
  91215. // c.restitution = cm.restitution;
  91216. // If friction or restitution were specified in the material, use them
  91217. if(bi.material && bj.material){
  91218. if(bi.material.friction >= 0 && bj.material.friction >= 0){
  91219. mu = bi.material.friction * bj.material.friction;
  91220. }
  91221. if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
  91222. c.restitution = bi.material.restitution * bj.material.restitution;
  91223. }
  91224. }
  91225. // c.setSpookParams(
  91226. // cm.contactEquationStiffness,
  91227. // cm.contactEquationRelaxation,
  91228. // dt
  91229. // );
  91230. solver.addEquation(c);
  91231. // // Add friction constraint equation
  91232. // if(mu > 0){
  91233. // // Create 2 tangent equations
  91234. // var mug = mu * gnorm;
  91235. // var reducedMass = (bi.invMass + bj.invMass);
  91236. // if(reducedMass > 0){
  91237. // reducedMass = 1/reducedMass;
  91238. // }
  91239. // var pool = frictionEquationPool;
  91240. // var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  91241. // var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  91242. // this.frictionEquations.push(c1, c2);
  91243. // c1.bi = c2.bi = bi;
  91244. // c1.bj = c2.bj = bj;
  91245. // c1.minForce = c2.minForce = -mug*reducedMass;
  91246. // c1.maxForce = c2.maxForce = mug*reducedMass;
  91247. // // Copy over the relative vectors
  91248. // c1.ri.copy(c.ri);
  91249. // c1.rj.copy(c.rj);
  91250. // c2.ri.copy(c.ri);
  91251. // c2.rj.copy(c.rj);
  91252. // // Construct tangents
  91253. // c.ni.tangents(c1.t, c2.t);
  91254. // // Set spook params
  91255. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  91256. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  91257. // c1.enabled = c2.enabled = c.enabled;
  91258. // // Add equations to solver
  91259. // solver.addEquation(c1);
  91260. // solver.addEquation(c2);
  91261. // }
  91262. if( bi.allowSleep &&
  91263. bi.type === Body.DYNAMIC &&
  91264. bi.sleepState === Body.SLEEPING &&
  91265. bj.sleepState === Body.AWAKE &&
  91266. bj.type !== Body.STATIC
  91267. ){
  91268. var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2();
  91269. var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
  91270. if(speedSquaredB >= speedLimitSquaredB*2){
  91271. bi._wakeUpAfterNarrowphase = true;
  91272. }
  91273. }
  91274. if( bj.allowSleep &&
  91275. bj.type === Body.DYNAMIC &&
  91276. bj.sleepState === Body.SLEEPING &&
  91277. bi.sleepState === Body.AWAKE &&
  91278. bi.type !== Body.STATIC
  91279. ){
  91280. var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2();
  91281. var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
  91282. if(speedSquaredA >= speedLimitSquaredA*2){
  91283. bj._wakeUpAfterNarrowphase = true;
  91284. }
  91285. }
  91286. // Now we know that i and j are in contact. Set collision matrix state
  91287. this.collisionMatrix.set(bi, bj, true);
  91288. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  91289. // First contact!
  91290. // 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.
  91291. World_step_collideEvent.body = bj;
  91292. World_step_collideEvent.contact = c;
  91293. bi.dispatchEvent(World_step_collideEvent);
  91294. World_step_collideEvent.body = bi;
  91295. bj.dispatchEvent(World_step_collideEvent);
  91296. }
  91297. }
  91298. if(doProfiling){
  91299. profile.makeContactConstraints = performance.now() - profilingStart;
  91300. profilingStart = performance.now();
  91301. }
  91302. // Wake up bodies
  91303. for(i=0; i!==N; i++){
  91304. var bi = bodies[i];
  91305. if(bi._wakeUpAfterNarrowphase){
  91306. bi.wakeUp();
  91307. bi._wakeUpAfterNarrowphase = false;
  91308. }
  91309. }
  91310. // Add user-added constraints
  91311. var Nconstraints = constraints.length;
  91312. for(i=0; i!==Nconstraints; i++){
  91313. var c = constraints[i];
  91314. c.update();
  91315. for(var j=0, Neq=c.equations.length; j!==Neq; j++){
  91316. var eq = c.equations[j];
  91317. solver.addEquation(eq);
  91318. }
  91319. }
  91320. // Solve the constrained system
  91321. solver.solve(dt,this);
  91322. if(doProfiling){
  91323. profile.solve = performance.now() - profilingStart;
  91324. }
  91325. // Remove all contacts from solver
  91326. solver.removeAllEquations();
  91327. // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  91328. var pow = Math.pow;
  91329. for(i=0; i!==N; i++){
  91330. var bi = bodies[i];
  91331. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  91332. var ld = pow(1.0 - bi.linearDamping,dt);
  91333. var v = bi.velocity;
  91334. v.mult(ld,v);
  91335. var av = bi.angularVelocity;
  91336. if(av){
  91337. var ad = pow(1.0 - bi.angularDamping,dt);
  91338. av.mult(ad,av);
  91339. }
  91340. }
  91341. }
  91342. this.dispatchEvent(World_step_preStepEvent);
  91343. // Invoke pre-step callbacks
  91344. for(i=0; i!==N; i++){
  91345. var bi = bodies[i];
  91346. if(bi.preStep){
  91347. bi.preStep.call(bi);
  91348. }
  91349. }
  91350. // Leap frog
  91351. // vnew = v + h*f/m
  91352. // xnew = x + h*vnew
  91353. if(doProfiling){
  91354. profilingStart = performance.now();
  91355. }
  91356. var q = World_step_step_q;
  91357. var w = World_step_step_w;
  91358. var wq = World_step_step_wq;
  91359. var stepnumber = this.stepnumber;
  91360. var DYNAMIC_OR_KINEMATIC = Body.DYNAMIC | Body.KINEMATIC;
  91361. var quatNormalize = stepnumber % (this.quatNormalizeSkip+1) === 0;
  91362. var quatNormalizeFast = this.quatNormalizeFast;
  91363. var half_dt = dt * 0.5;
  91364. var PLANE = Shape.types.PLANE,
  91365. CONVEX = Shape.types.CONVEXPOLYHEDRON;
  91366. for(i=0; i!==N; i++){
  91367. var b = bodies[i],
  91368. force = b.force,
  91369. tau = b.torque;
  91370. if((b.type & DYNAMIC_OR_KINEMATIC) && b.sleepState !== Body.SLEEPING){ // Only for dynamic
  91371. var velo = b.velocity,
  91372. angularVelo = b.angularVelocity,
  91373. pos = b.position,
  91374. quat = b.quaternion,
  91375. invMass = b.invMass,
  91376. invInertia = b.invInertiaWorld;
  91377. velo.x += force.x * invMass * dt;
  91378. velo.y += force.y * invMass * dt;
  91379. velo.z += force.z * invMass * dt;
  91380. if(b.angularVelocity){
  91381. invInertia.vmult(tau,invI_tau_dt);
  91382. invI_tau_dt.mult(dt,invI_tau_dt);
  91383. invI_tau_dt.vadd(angularVelo,angularVelo);
  91384. }
  91385. // Use new velocity - leap frog
  91386. pos.x += velo.x * dt;
  91387. pos.y += velo.y * dt;
  91388. pos.z += velo.z * dt;
  91389. if(b.angularVelocity){
  91390. w.set(angularVelo.x, angularVelo.y, angularVelo.z, 0);
  91391. w.mult(quat,wq);
  91392. quat.x += half_dt * wq.x;
  91393. quat.y += half_dt * wq.y;
  91394. quat.z += half_dt * wq.z;
  91395. quat.w += half_dt * wq.w;
  91396. if(quatNormalize){
  91397. if(quatNormalizeFast){
  91398. quat.normalizeFast();
  91399. } else {
  91400. quat.normalize();
  91401. }
  91402. }
  91403. }
  91404. if(b.aabb){
  91405. b.aabbNeedsUpdate = true;
  91406. }
  91407. // Update world inertia
  91408. if(b.updateInertiaWorld){
  91409. b.updateInertiaWorld();
  91410. }
  91411. }
  91412. }
  91413. this.clearForces();
  91414. this.broadphase.dirty = true;
  91415. if(doProfiling){
  91416. profile.integrate = performance.now() - profilingStart;
  91417. }
  91418. // Update world time
  91419. this.time += dt;
  91420. this.stepnumber += 1;
  91421. this.dispatchEvent(World_step_postStepEvent);
  91422. // Invoke post-step callbacks
  91423. for(i=0; i!==N; i++){
  91424. var bi = bodies[i];
  91425. var postStep = bi.postStep;
  91426. if(postStep){
  91427. postStep.call(bi);
  91428. }
  91429. }
  91430. // Sleeping update
  91431. if(this.allowSleep){
  91432. for(i=0; i!==N; i++){
  91433. bodies[i].sleepTick(this.time);
  91434. }
  91435. }
  91436. };
  91437. /**
  91438. * Sets all body forces in the world to zero.
  91439. * @method clearForces
  91440. */
  91441. World.prototype.clearForces = function(){
  91442. var bodies = this.bodies;
  91443. var N = bodies.length;
  91444. for(var i=0; i !== N; i++){
  91445. var b = bodies[i],
  91446. force = b.force,
  91447. tau = b.torque;
  91448. b.force.set(0,0,0);
  91449. b.torque.set(0,0,0);
  91450. }
  91451. };
  91452. },{"../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])
  91453. (2)
  91454. });
  91455. /***/ }),
  91456. /* 16 */
  91457. /***/ (function(module, exports, __webpack_require__) {
  91458. /**
  91459. * from OimoPhysics DEV 1.1.0a AS3
  91460. * @author Saharan / http://el-ement.com/
  91461. *
  91462. * to Oimo.js 2015 JAVASCRIPT
  91463. * @author LoTh / http://lo-th.github.io/labs/
  91464. */
  91465. var OIMO = {
  91466. REVISION: "1.2",
  91467. // Global identification of next shape.
  91468. // This will be incremented every time a shape is created.
  91469. nextID: 0,
  91470. proxyID: 0,
  91471. // BroadPhase
  91472. BR_NULL: 0,
  91473. BR_BRUTE_FORCE: 1,
  91474. BR_SWEEP_AND_PRUNE: 2,
  91475. BR_BOUNDING_VOLUME_TREE: 3,
  91476. // body type
  91477. BODY_NULL: 0,
  91478. BODY_DYNAMIC: 1,
  91479. BODY_STATIC: 2,
  91480. // shape type
  91481. SHAPE_NULL: 0,
  91482. SHAPE_SPHERE: 1,
  91483. SHAPE_BOX: 2,
  91484. SHAPE_CYLINDER: 3,
  91485. SHAPE_TETRA: 4,
  91486. // joint type
  91487. JOINT_NULL: 0,
  91488. JOINT_DISTANCE: 1,
  91489. JOINT_BALL_AND_SOCKET: 2,
  91490. JOINT_HINGE: 3,
  91491. JOINT_WHEEL: 4,
  91492. JOINT_SLIDER: 5,
  91493. JOINT_PRISMATIC: 6,
  91494. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  91495. // scale all by 100 so object is between 10 to 10000 three unit.
  91496. WORLD_SCALE: 100,
  91497. INV_SCALE: 0.01,
  91498. // AABB aproximation
  91499. AABB_PROX: 0.005,
  91500. // Math function
  91501. sqrt: Math.sqrt,
  91502. abs: Math.abs,
  91503. floor: Math.floor,
  91504. cos: Math.cos,
  91505. sin: Math.sin,
  91506. acos: Math.acos,
  91507. asin: Math.asin,
  91508. atan2: Math.atan2,
  91509. round: Math.round,
  91510. pow: Math.pow,
  91511. max: Math.max,
  91512. min: Math.min,
  91513. random: Math.random,
  91514. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  91515. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  91516. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  91517. int: function (x) { return ~~x; },
  91518. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  91519. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  91520. degtorad: 0.0174532925199432957,
  91521. radtodeg: 57.295779513082320876,
  91522. PI: 3.141592653589793,
  91523. TwoPI: 6.283185307179586,
  91524. PI90: 1.570796326794896,
  91525. PI270: 4.712388980384689,
  91526. CustomError: null,
  91527. Error: function (Class, Msg) {
  91528. if (OIMO.CustomError == null) console.error(Class, Msg);
  91529. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  91530. }
  91531. };
  91532. var OIMO_ARRAY_TYPE;
  91533. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  91534. try {
  91535. (function (w) {
  91536. var perfNow;
  91537. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  91538. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  91539. var n = perfNowNames[i];
  91540. if (!!w['performance'][n]) {
  91541. perfNow = function () { return w['performance'][n]() };
  91542. break;
  91543. }
  91544. }
  91545. if (!perfNow) perfNow = Date.now;
  91546. //w.perfNow = perfNow;
  91547. OIMO.now = perfNow;
  91548. })(window);
  91549. } catch (e) { OIMO.now = function () { return 0; }; }
  91550. /**
  91551. * The class of physical computing world.
  91552. * You must be added to the world physical all computing objects
  91553. * @author saharan
  91554. * @author lo-th
  91555. */
  91556. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  91557. // The time between each step
  91558. this.timeStep = TimeStep || 0.01666; // 1/60;
  91559. // The number of iterations for constraint solvers.
  91560. this.numIterations = Iterations || 8;
  91561. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  91562. switch (BroadPhaseType || 2) {
  91563. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  91564. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  91565. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  91566. }
  91567. // This is the detailed information of the performance.
  91568. this.performance = null;
  91569. this.isNoStat = NoStat || false;
  91570. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  91571. // Whether the constraints randomizer is enabled or not.
  91572. this.enableRandomizer = true;
  91573. // The rigid body list
  91574. this.rigidBodies = null;
  91575. // number of rigid body
  91576. this.numRigidBodies = 0;
  91577. // The contact list
  91578. this.contacts = null;
  91579. this.unusedContacts = null;
  91580. // The number of contact
  91581. this.numContacts = 0;
  91582. // The number of contact points
  91583. this.numContactPoints = 0;
  91584. // The joint list
  91585. this.joints = null;
  91586. // The number of joints.
  91587. this.numJoints = 0;
  91588. // The number of simulation islands.
  91589. this.numIslands = 0;
  91590. // The gravity in the world.
  91591. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  91592. var numShapeTypes = 5;//4;//3;
  91593. this.detectors = [];
  91594. this.detectors.length = numShapeTypes;
  91595. var i = numShapeTypes;
  91596. while (i--) {
  91597. this.detectors[i] = [];
  91598. this.detectors[i].length = numShapeTypes;
  91599. }
  91600. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  91601. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  91602. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  91603. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  91604. // CYLINDER add
  91605. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  91606. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  91607. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  91608. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  91609. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  91610. // TETRA add
  91611. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  91612. this.randX = 65535;
  91613. this.randA = 98765;
  91614. this.randB = 123456789;
  91615. //this.maxIslandRigidBodies = 64;
  91616. this.islandRigidBodies = [];
  91617. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  91618. this.islandStack = [];
  91619. //this.islandStack.length = this.maxIslandRigidBodies;
  91620. //this.maxIslandConstraints = 128;
  91621. this.islandConstraints = [];
  91622. //this.islandConstraints.length = this.maxIslandConstraints;
  91623. };
  91624. OIMO.World.prototype = {
  91625. constructor: OIMO.World,
  91626. /**
  91627. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  91628. */
  91629. clear: function () {
  91630. this.randX = 65535;
  91631. while (this.joints !== null) {
  91632. this.removeJoint(this.joints);
  91633. }
  91634. while (this.contacts !== null) {
  91635. this.removeContact(this.contacts);
  91636. }
  91637. while (this.rigidBodies !== null) {
  91638. this.removeRigidBody(this.rigidBodies);
  91639. }
  91640. OIMO.nextID = 0;
  91641. OIMO.proxyID = 0;
  91642. },
  91643. /**
  91644. * I'll add a rigid body to the world.
  91645. * Rigid body that has been added will be the operands of each step.
  91646. * @param rigidBody Rigid body that you want to add
  91647. */
  91648. addRigidBody: function (rigidBody) {
  91649. if (rigidBody.parent) {
  91650. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  91651. }
  91652. rigidBody.parent = this;
  91653. rigidBody.awake();
  91654. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  91655. this.addShape(shape);
  91656. }
  91657. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  91658. this.rigidBodies = rigidBody;
  91659. this.numRigidBodies++;
  91660. },
  91661. /**
  91662. * I will remove the rigid body from the world.
  91663. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  91664. * @param rigidBody Rigid body to be removed
  91665. */
  91666. removeRigidBody: function (rigidBody) {
  91667. var remove = rigidBody;
  91668. if (remove.parent !== this) return;
  91669. remove.awake();
  91670. var js = remove.jointLink;
  91671. while (js != null) {
  91672. var joint = js.joint;
  91673. js = js.next;
  91674. this.removeJoint(joint);
  91675. }
  91676. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  91677. this.removeShape(shape);
  91678. }
  91679. var prev = remove.prev;
  91680. var next = remove.next;
  91681. if (prev !== null) prev.next = next;
  91682. if (next !== null) next.prev = prev;
  91683. if (this.rigidBodies == remove) this.rigidBodies = next;
  91684. remove.prev = null;
  91685. remove.next = null;
  91686. remove.parent = null;
  91687. this.numRigidBodies--;
  91688. },
  91689. getByName: function (name) {
  91690. var result = null;
  91691. var body = this.rigidBodies;
  91692. while (body !== null) {
  91693. if (body.name !== " " && body.name === name) result = body;
  91694. body = body.next;
  91695. }
  91696. var joint = this.joints;
  91697. while (joint !== null) {
  91698. if (joint.name !== "" && joint.name === name) result = joint;
  91699. joint = joint.next;
  91700. }
  91701. return result;
  91702. },
  91703. /**
  91704. * I'll add a shape to the world..
  91705. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  91706. * Shape will be added to the world automatically, please do not call from outside this method.
  91707. * @param shape Shape you want to add
  91708. */
  91709. addShape: function (shape) {
  91710. if (!shape.parent || !shape.parent.parent) {
  91711. OIMO.Error("World", "It is not possible to be added alone to shape world");
  91712. }
  91713. shape.proxy = this.broadPhase.createProxy(shape);
  91714. shape.updateProxy();
  91715. this.broadPhase.addProxy(shape.proxy);
  91716. },
  91717. /**
  91718. * I will remove the shape from the world.
  91719. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  91720. * Shape will be added to the world automatically, please do not call from outside this method.
  91721. * @param shape Shape you want to delete
  91722. */
  91723. removeShape: function (shape) {
  91724. this.broadPhase.removeProxy(shape.proxy);
  91725. shape.proxy = null;
  91726. },
  91727. /**
  91728. * I'll add a joint to the world.
  91729. * Joint that has been added will be the operands of each step.
  91730. * @param shape Joint to be added
  91731. */
  91732. addJoint: function (joint) {
  91733. if (joint.parent) {
  91734. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  91735. }
  91736. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  91737. this.joints = joint;
  91738. joint.parent = this;
  91739. this.numJoints++;
  91740. joint.awake();
  91741. joint.attach();
  91742. },
  91743. /**
  91744. * I will remove the joint from the world.
  91745. * Joint that has been added will be the operands of each step.
  91746. * @param shape Joint to be deleted
  91747. */
  91748. removeJoint: function (joint) {
  91749. var remove = joint;
  91750. var prev = remove.prev;
  91751. var next = remove.next;
  91752. if (prev !== null) prev.next = next;
  91753. if (next !== null) next.prev = prev;
  91754. if (this.joints == remove) this.joints = next;
  91755. remove.prev = null;
  91756. remove.next = null;
  91757. this.numJoints--;
  91758. remove.awake();
  91759. remove.detach();
  91760. remove.parent = null;
  91761. },
  91762. worldscale: function (scale) {
  91763. OIMO.WORLD_SCALE = scale || 100;
  91764. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  91765. },
  91766. addContact: function (s1, s2) {
  91767. var newContact;
  91768. if (this.unusedContacts !== null) {
  91769. newContact = this.unusedContacts;
  91770. this.unusedContacts = this.unusedContacts.next;
  91771. } else {
  91772. newContact = new OIMO.Contact();
  91773. }
  91774. newContact.attach(s1, s2);
  91775. newContact.detector = this.detectors[s1.type][s2.type];
  91776. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  91777. this.contacts = newContact;
  91778. this.numContacts++;
  91779. },
  91780. removeContact: function (contact) {
  91781. var prev = contact.prev;
  91782. var next = contact.next;
  91783. if (next) next.prev = prev;
  91784. if (prev) prev.next = next;
  91785. if (this.contacts == contact) this.contacts = next;
  91786. contact.prev = null;
  91787. contact.next = null;
  91788. contact.detach();
  91789. contact.next = this.unusedContacts;
  91790. this.unusedContacts = contact;
  91791. this.numContacts--;
  91792. },
  91793. checkContact: function (name1, name2) {
  91794. var n1, n2;
  91795. var contact = this.contacts;
  91796. while (contact !== null) {
  91797. n1 = contact.body1.name || ' ';
  91798. n2 = contact.body2.name || ' ';
  91799. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  91800. else contact = contact.next;
  91801. }
  91802. return false;
  91803. },
  91804. callSleep: function (body) {
  91805. if (!body.allowSleep) return false;
  91806. if (body.linearVelocity.lengthSq() > 0.04) return false;
  91807. if (body.angularVelocity.lengthSq() > 0.25) return false;
  91808. return true;
  91809. },
  91810. /**
  91811. * I will proceed only time step seconds time of World.
  91812. */
  91813. step: function () {
  91814. var time0, time1, time2, time3;
  91815. var stat = !this.isNoStat ? true : false;
  91816. if (stat) time0 = OIMO.now();
  91817. var body = this.rigidBodies;
  91818. while (body !== null) {
  91819. body.addedToIsland = false;
  91820. if (body.sleeping) {
  91821. if (
  91822. body.linearVelocity.testZero() ||
  91823. body.angularVelocity.testZero() ||
  91824. body.position.testDiff(body.sleepPosition) ||
  91825. body.orientation.testDiff(body.sleepOrientation)
  91826. ) body.awake(); // awake the body
  91827. }
  91828. body = body.next;
  91829. }
  91830. //------------------------------------------------------
  91831. // UPDATE CONTACT
  91832. //------------------------------------------------------
  91833. // broad phase
  91834. if (stat) time1 = OIMO.now();
  91835. this.broadPhase.detectPairs();
  91836. var pairs = this.broadPhase.pairs;
  91837. var i = this.broadPhase.numPairs;
  91838. //do{
  91839. while (i--) {
  91840. //for(var i=0, l=numPairs; i<l; i++){
  91841. var pair = pairs[i];
  91842. var s1;
  91843. var s2;
  91844. if (pair.shape1.id < pair.shape2.id) {
  91845. s1 = pair.shape1;
  91846. s2 = pair.shape2;
  91847. } else {
  91848. s1 = pair.shape2;
  91849. s2 = pair.shape1;
  91850. }
  91851. var link;
  91852. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  91853. else link = s2.contactLink;
  91854. var exists = false;
  91855. while (link) {
  91856. var contact = link.contact;
  91857. if (contact.shape1 == s1 && contact.shape2 == s2) {
  91858. contact.persisting = true;
  91859. exists = true;// contact already exists
  91860. break;
  91861. }
  91862. link = link.next;
  91863. }
  91864. if (!exists) {
  91865. this.addContact(s1, s2);
  91866. }
  91867. }// while(i-- >0);
  91868. if (stat) {
  91869. time2 = OIMO.now();
  91870. this.performance.broadPhaseTime = time2 - time1;
  91871. }
  91872. // update & narrow phase
  91873. this.numContactPoints = 0;
  91874. contact = this.contacts;
  91875. while (contact !== null) {
  91876. if (!contact.persisting) {
  91877. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  91878. /*var aabb1=contact.shape1.aabb;
  91879. var aabb2=contact.shape2.aabb;
  91880. if(
  91881. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  91882. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  91883. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  91884. ){*/
  91885. var next = contact.next;
  91886. this.removeContact(contact);
  91887. contact = next;
  91888. continue;
  91889. }
  91890. }
  91891. var b1 = contact.body1;
  91892. var b2 = contact.body2;
  91893. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  91894. contact.updateManifold();
  91895. }
  91896. this.numContactPoints += contact.manifold.numPoints;
  91897. contact.persisting = false;
  91898. contact.constraint.addedToIsland = false;
  91899. contact = contact.next;
  91900. }
  91901. if (stat) {
  91902. time3 = OIMO.now();
  91903. this.performance.narrowPhaseTime = time3 - time2;
  91904. }
  91905. //------------------------------------------------------
  91906. // SOLVE ISLANDS
  91907. //------------------------------------------------------
  91908. var invTimeStep = 1 / this.timeStep;
  91909. //var body;
  91910. var joint;
  91911. var constraint;
  91912. //var num;
  91913. for (joint = this.joints; joint !== null; joint = joint.next) {
  91914. joint.addedToIsland = false;
  91915. }
  91916. // clear old island array
  91917. this.islandRigidBodies = [];
  91918. this.islandConstraints = [];
  91919. this.islandStack = [];
  91920. // expand island buffers
  91921. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  91922. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  91923. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  91924. this.islandRigidBodies=[];
  91925. this.islandStack=[];
  91926. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  91927. this.islandStack.length = this.maxIslandRigidBodies;
  91928. }
  91929. var numConstraints=this.numJoints+this.numContacts;
  91930. if(this.maxIslandConstraints<numConstraints){
  91931. this.maxIslandConstraints=numConstraints<<1;
  91932. //this.maxIslandConstraints=numConstraints*2;
  91933. this.islandConstraints=[];
  91934. this.islandConstraints.length = this.maxIslandConstraints;
  91935. }*/
  91936. time1 = OIMO.now();
  91937. this.numIslands = 0;
  91938. // build and solve simulation islands
  91939. for (var base = this.rigidBodies; base !== null; base = base.next) {
  91940. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  91941. if (base.isLonely()) {// update single body
  91942. if (base.isDynamic) {
  91943. base.linearVelocity.addTime(this.gravity, this.timeStep);
  91944. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  91945. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  91946. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  91947. }
  91948. if (this.callSleep(base)) {
  91949. base.sleepTime += this.timeStep;
  91950. if (base.sleepTime > 0.5) base.sleep();
  91951. else base.updatePosition(this.timeStep);
  91952. } else {
  91953. base.sleepTime = 0;
  91954. base.updatePosition(this.timeStep);
  91955. }
  91956. this.numIslands++;
  91957. continue;
  91958. }
  91959. var islandNumRigidBodies = 0;
  91960. var islandNumConstraints = 0;
  91961. var stackCount = 1;
  91962. // add rigid body to stack
  91963. this.islandStack[0] = base;
  91964. base.addedToIsland = true;
  91965. // build an island
  91966. do {
  91967. // get rigid body from stack
  91968. body = this.islandStack[--stackCount];
  91969. this.islandStack[stackCount] = null;
  91970. body.sleeping = false;
  91971. // add rigid body to the island
  91972. this.islandRigidBodies[islandNumRigidBodies++] = body;
  91973. if (body.isStatic) continue;
  91974. // search connections
  91975. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  91976. var contact = cs.contact;
  91977. constraint = contact.constraint;
  91978. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  91979. // add constraint to the island
  91980. this.islandConstraints[islandNumConstraints++] = constraint;
  91981. constraint.addedToIsland = true;
  91982. var next = cs.body;
  91983. if (next.addedToIsland) continue;
  91984. // add rigid body to stack
  91985. this.islandStack[stackCount++] = next;
  91986. next.addedToIsland = true;
  91987. }
  91988. for (var js = body.jointLink; js !== null; js = js.next) {
  91989. constraint = js.joint;
  91990. if (constraint.addedToIsland) continue;// ignore
  91991. // add constraint to the island
  91992. this.islandConstraints[islandNumConstraints++] = constraint;
  91993. constraint.addedToIsland = true;
  91994. next = js.body;
  91995. if (next.addedToIsland || !next.isDynamic) continue;
  91996. // add rigid body to stack
  91997. this.islandStack[stackCount++] = next;
  91998. next.addedToIsland = true;
  91999. }
  92000. } while (stackCount != 0);
  92001. // update velocities
  92002. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  92003. /*var gx=this.gravity.x*this.timeStep;
  92004. var gy=this.gravity.y*this.timeStep;
  92005. var gz=this.gravity.z*this.timeStep;*/
  92006. var j = islandNumRigidBodies;
  92007. while (j--) {
  92008. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  92009. body = this.islandRigidBodies[j];
  92010. if (body.isDynamic) {
  92011. body.linearVelocity.addEqual(gVel);
  92012. /*body.linearVelocity.x+=gx;
  92013. body.linearVelocity.y+=gy;
  92014. body.linearVelocity.z+=gz;*/
  92015. }
  92016. }
  92017. // randomizing order
  92018. if (this.enableRandomizer) {
  92019. //for(var j=1, l=islandNumConstraints; j<l; j++){
  92020. j = islandNumConstraints;
  92021. while (j--) {
  92022. if (j !== 0) {
  92023. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  92024. constraint = this.islandConstraints[j];
  92025. this.islandConstraints[j] = this.islandConstraints[swap];
  92026. this.islandConstraints[swap] = constraint;
  92027. }
  92028. }
  92029. }
  92030. // solve contraints
  92031. j = islandNumConstraints;
  92032. while (j--) {
  92033. //for(j=0, l=islandNumConstraints; j<l; j++){
  92034. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  92035. }
  92036. var k = this.numIterations;
  92037. while (k--) {
  92038. //for(var k=0, l=this.numIterations; k<l; k++){
  92039. j = islandNumConstraints;
  92040. while (j--) {
  92041. //for(j=0, m=islandNumConstraints; j<m; j++){
  92042. this.islandConstraints[j].solve();// main-solve
  92043. }
  92044. }
  92045. j = islandNumConstraints;
  92046. while (j--) {
  92047. //for(j=0, l=islandNumConstraints; j<l; j++){
  92048. this.islandConstraints[j].postSolve();// post-solve
  92049. this.islandConstraints[j] = null;// gc
  92050. }
  92051. // sleeping check
  92052. var sleepTime = 10;
  92053. j = islandNumRigidBodies;
  92054. while (j--) {
  92055. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92056. body = this.islandRigidBodies[j];
  92057. if (this.callSleep(body)) {
  92058. body.sleepTime += this.timeStep;
  92059. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  92060. } else {
  92061. body.sleepTime = 0;
  92062. sleepTime = 0;
  92063. continue;
  92064. }
  92065. }
  92066. if (sleepTime > 0.5) {
  92067. // sleep the island
  92068. j = islandNumRigidBodies;
  92069. while (j--) {
  92070. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92071. this.islandRigidBodies[j].sleep();
  92072. this.islandRigidBodies[j] = null;// gc
  92073. }
  92074. } else {
  92075. // update positions
  92076. j = islandNumRigidBodies;
  92077. while (j--) {
  92078. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92079. this.islandRigidBodies[j].updatePosition(this.timeStep);
  92080. this.islandRigidBodies[j] = null;// gc
  92081. }
  92082. }
  92083. this.numIslands++;
  92084. }
  92085. if (stat) {
  92086. time2 = OIMO.now();
  92087. this.performance.solvingTime = time2 - time1;
  92088. //------------------------------------------------------
  92089. // END SIMULATION
  92090. //------------------------------------------------------
  92091. time2 = OIMO.now();
  92092. // fps update
  92093. this.performance.upfps();
  92094. this.performance.totalTime = time2 - time0;
  92095. }
  92096. }
  92097. }
  92098. /**
  92099. * The class of rigid body.
  92100. * Rigid body has the shape of a single or multiple collision processing,
  92101. * I can set the parameters individually.
  92102. * @author saharan
  92103. */
  92104. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  92105. this.name = " ";
  92106. // The maximum number of shapes that can be added to a one rigid.
  92107. this.MAX_SHAPES = 64;//64;
  92108. this.prev = null;
  92109. this.next = null;
  92110. // I represent the kind of rigid body.
  92111. // Please do not change from the outside this variable.
  92112. // If you want to change the type of rigid body, always
  92113. // Please specify the type you want to set the arguments of setupMass method.
  92114. this.type = OIMO.BODY_NULL;
  92115. this.massInfo = new OIMO.MassInfo();
  92116. // It is the world coordinate of the center of gravity.
  92117. this.position = new OIMO.Vec3(x, y, z);
  92118. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  92119. this.newPosition = new OIMO.Vec3();
  92120. this.controlPos = false;
  92121. this.newOrientation = new OIMO.Quat();
  92122. this.newRotation = new OIMO.Vec3();
  92123. this.currentRotation = new OIMO.Vec3();
  92124. this.controlRot = false;
  92125. this.controlRotInTime = false;
  92126. // Is the translational velocity.
  92127. this.linearVelocity = new OIMO.Vec3();
  92128. // Is the angular velocity.
  92129. this.angularVelocity = new OIMO.Vec3();
  92130. // return matrix for three.js
  92131. this.matrix = new OIMO.Mat44();
  92132. //--------------------------------------------
  92133. // Please do not change from the outside this variables.
  92134. //--------------------------------------------
  92135. // It is a world that rigid body has been added.
  92136. this.parent = null;
  92137. this.contactLink = null;
  92138. this.numContacts = 0;
  92139. // An array of shapes that are included in the rigid body.
  92140. this.shapes = null;
  92141. // The number of shapes that are included in the rigid body.
  92142. this.numShapes = 0;
  92143. // It is the link array of joint that is connected to the rigid body.
  92144. this.jointLink = null;
  92145. // The number of joints that are connected to the rigid body.
  92146. this.numJoints = 0;
  92147. // It is the world coordinate of the center of gravity in the sleep just before.
  92148. this.sleepPosition = new OIMO.Vec3();
  92149. // It is a quaternion that represents the attitude of sleep just before.
  92150. this.sleepOrientation = new OIMO.Quat();
  92151. // I will show this rigid body to determine whether it is a rigid body static.
  92152. this.isStatic = false;
  92153. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  92154. this.isDynamic = false;
  92155. // It is a rotation matrix representing the orientation.
  92156. this.rotation = new OIMO.Mat33();
  92157. //--------------------------------------------
  92158. // It will be recalculated automatically from the shape, which is included.
  92159. //--------------------------------------------
  92160. // This is the weight.
  92161. this.mass = NaN;
  92162. // It is the reciprocal of the mass.
  92163. this.inverseMass = NaN;
  92164. // It is the inverse of the inertia tensor in the world system.
  92165. this.inverseInertia = new OIMO.Mat33();
  92166. // It is the inertia tensor in the initial state.
  92167. this.localInertia = new OIMO.Mat33();
  92168. // It is the inverse of the inertia tensor in the initial state.
  92169. this.inverseLocalInertia = new OIMO.Mat33();
  92170. // I indicates rigid body whether it has been added to the simulation Island.
  92171. this.addedToIsland = false;
  92172. // It shows how to sleep rigid body.
  92173. this.allowSleep = true;
  92174. // This is the time from when the rigid body at rest.
  92175. this.sleepTime = 0;
  92176. // I shows rigid body to determine whether it is a sleep state.
  92177. this.sleeping = false;
  92178. };
  92179. OIMO.RigidBody.prototype = {
  92180. constructor: OIMO.RigidBody,
  92181. /**
  92182. * I'll add a shape to rigid body.
  92183. * If you add a shape, please call the setupMass method to step up to the start of the next.
  92184. * @param shape shape to Add
  92185. */
  92186. addShape: function (shape) {
  92187. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  92188. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  92189. this.shapes = shape;
  92190. shape.parent = this;
  92191. if (this.parent) this.parent.addShape(shape);
  92192. this.numShapes++;
  92193. },
  92194. /**
  92195. * I will delete the shape from the rigid body.
  92196. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  92197. * @param shape shape to Delete
  92198. */
  92199. removeShape: function (shape) {
  92200. var remove = shape;
  92201. if (remove.parent != this) return;
  92202. var prev = remove.prev;
  92203. var next = remove.next;
  92204. if (prev != null) prev.next = next;
  92205. if (next != null) next.prev = prev;
  92206. if (this.shapes == remove) this.shapes = next;
  92207. remove.prev = null;
  92208. remove.next = null;
  92209. remove.parent = null;
  92210. if (this.parent) this.parent.removeShape(remove);
  92211. this.numShapes--;
  92212. },
  92213. remove: function () {
  92214. this.dispose();
  92215. },
  92216. dispose: function () {
  92217. this.parent.removeRigidBody(this);
  92218. },
  92219. checkContact: function (name) {
  92220. this.parent.checkContact(this.name, name);
  92221. },
  92222. /**
  92223. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  92224. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  92225. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  92226. * the rigid body's position will be adjusted to the center of gravity.
  92227. * @param type
  92228. * @param adjustPosition
  92229. */
  92230. setupMass: function (type, AdjustPosition) {
  92231. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  92232. this.type = type || OIMO.BODY_DYNAMIC;
  92233. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  92234. this.isStatic = this.type == OIMO.BODY_STATIC;
  92235. this.mass = 0;
  92236. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92237. var te = this.localInertia.elements;
  92238. //
  92239. var tmpM = new OIMO.Mat33();
  92240. var tmpV = new OIMO.Vec3();
  92241. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92242. shape.calculateMassInfo(this.massInfo);
  92243. var shapeMass = this.massInfo.mass;
  92244. var relX = shape.relativePosition.x;
  92245. var relY = shape.relativePosition.y;
  92246. var relZ = shape.relativePosition.z;
  92247. /*tmpV.x+=relX*shapeMass;
  92248. tmpV.y+=relY*shapeMass;
  92249. tmpV.z+=relZ*shapeMass;*/
  92250. tmpV.addScale(shape.relativePosition, shapeMass);
  92251. this.mass += shapeMass;
  92252. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  92253. this.localInertia.addEqual(tmpM);
  92254. // add offset inertia
  92255. te[0] += shapeMass * (relY * relY + relZ * relZ);
  92256. te[4] += shapeMass * (relX * relX + relZ * relZ);
  92257. te[8] += shapeMass * (relX * relX + relY * relY);
  92258. var xy = shapeMass * relX * relY;
  92259. var yz = shapeMass * relY * relZ;
  92260. var zx = shapeMass * relZ * relX;
  92261. te[1] -= xy;
  92262. te[3] -= xy;
  92263. te[2] -= yz;
  92264. te[6] -= yz;
  92265. te[5] -= zx;
  92266. te[7] -= zx;
  92267. }
  92268. this.inverseMass = 1 / this.mass;
  92269. tmpV.scaleEqual(this.inverseMass);
  92270. if (adjustPosition) {
  92271. this.position.addEqual(tmpV);
  92272. for (shape = this.shapes; shape != null; shape = shape.next) {
  92273. shape.relativePosition.subEqual(tmpV);
  92274. }
  92275. // subtract offset inertia
  92276. relX = tmpV.x;
  92277. relY = tmpV.y;
  92278. relZ = tmpV.z;
  92279. //var te = this.localInertia.elements;
  92280. te[0] -= this.mass * (relY * relY + relZ * relZ);
  92281. te[4] -= this.mass * (relX * relX + relZ * relZ);
  92282. te[8] -= this.mass * (relX * relX + relY * relY);
  92283. xy = this.mass * relX * relY;
  92284. yz = this.mass * relY * relZ;
  92285. zx = this.mass * relZ * relX;
  92286. te[1] += xy;
  92287. te[3] += xy;
  92288. te[2] += yz;
  92289. te[6] += yz;
  92290. te[5] += zx;
  92291. te[7] += zx;
  92292. }
  92293. this.inverseLocalInertia.invert(this.localInertia);
  92294. if (this.type == OIMO.BODY_STATIC) {
  92295. this.inverseMass = 0;
  92296. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92297. }
  92298. this.syncShapes();
  92299. this.awake();
  92300. },
  92301. /**
  92302. * Awake the rigid body.
  92303. */
  92304. awake: function () {
  92305. if (!this.allowSleep || !this.sleeping) return;
  92306. this.sleeping = false;
  92307. this.sleepTime = 0;
  92308. // awake connected constraints
  92309. var cs = this.contactLink;
  92310. while (cs != null) {
  92311. cs.body.sleepTime = 0;
  92312. cs.body.sleeping = false;
  92313. cs = cs.next;
  92314. }
  92315. var js = this.jointLink;
  92316. while (js != null) {
  92317. js.body.sleepTime = 0;
  92318. js.body.sleeping = false;
  92319. js = js.next;
  92320. }
  92321. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92322. shape.updateProxy();
  92323. }
  92324. },
  92325. /**
  92326. * Sleep the rigid body.
  92327. */
  92328. sleep: function () {
  92329. if (!this.allowSleep || this.sleeping) return;
  92330. this.linearVelocity.set(0, 0, 0);
  92331. this.angularVelocity.set(0, 0, 0);
  92332. this.sleepPosition.copy(this.position);
  92333. this.sleepOrientation.copy(this.orientation);
  92334. /*this.linearVelocity.x=0;
  92335. this.linearVelocity.y=0;
  92336. this.linearVelocity.z=0;
  92337. this.angularVelocity.x=0;
  92338. this.angularVelocity.y=0;
  92339. this.angularVelocity.z=0;
  92340. this.sleepPosition.x=this.position.x;
  92341. this.sleepPosition.y=this.position.y;
  92342. this.sleepPosition.z=this.position.z;*/
  92343. /*this.sleepOrientation.s=this.orientation.s;
  92344. this.sleepOrientation.x=this.orientation.x;
  92345. this.sleepOrientation.y=this.orientation.y;
  92346. this.sleepOrientation.z=this.orientation.z;*/
  92347. this.sleepTime = 0;
  92348. this.sleeping = true;
  92349. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92350. shape.updateProxy();
  92351. }
  92352. },
  92353. /**
  92354. * Get whether the rigid body has not any connection with others.
  92355. * @return
  92356. */
  92357. isLonely: function () {
  92358. return this.numJoints == 0 && this.numContacts == 0;
  92359. },
  92360. /**
  92361. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  92362. * This method is invoked automatically when calling the step of the World,
  92363. * There is no need to call from outside usually.
  92364. * @param timeStep time
  92365. */
  92366. updatePosition: function (timeStep) {
  92367. switch (this.type) {
  92368. case OIMO.BODY_STATIC:
  92369. this.linearVelocity.set(0, 0, 0);
  92370. this.angularVelocity.set(0, 0, 0);
  92371. // ONLY FOR TEST
  92372. if (this.controlPos) {
  92373. this.position.copy(this.newPosition);
  92374. this.controlPos = false;
  92375. }
  92376. if (this.controlRot) {
  92377. this.orientation.copy(this.newOrientation);
  92378. this.controlRot = false;
  92379. }
  92380. /*this.linearVelocity.x=0;
  92381. this.linearVelocity.y=0;
  92382. this.linearVelocity.z=0;
  92383. this.angularVelocity.x=0;
  92384. this.angularVelocity.y=0;
  92385. this.angularVelocity.z=0;*/
  92386. break;
  92387. case OIMO.BODY_DYNAMIC:
  92388. if (this.controlPos) {
  92389. this.angularVelocity.set(0, 0, 0);
  92390. this.linearVelocity.set(0, 0, 0);
  92391. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  92392. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  92393. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  92394. this.controlPos = false;
  92395. }
  92396. if (this.controlRot) {
  92397. this.angularVelocity.set(0, 0, 0);
  92398. this.orientation.copy(this.newOrientation);
  92399. //var t=timeStep//*0.5;
  92400. //var q = new OIMO.Quat();
  92401. //q.sub(this.newOrientation, this.orientation);
  92402. //q.normalize(q);
  92403. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  92404. q.x = (this.newOrientation.x - this.orientation.x)/t;
  92405. q.y = (this.newOrientation.y - this.orientation.y)/t;
  92406. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  92407. //this.angularVelocity.applyQuaternion(q);
  92408. //this.angularVelocity.x = this.angularVelocity.x/t;
  92409. //this.angularVelocity.y = this.angularVelocity.y/t;
  92410. //this.angularVelocity.z = this.angularVelocity.z/t;
  92411. this.controlRot = false;
  92412. }
  92413. this.position.addTime(this.linearVelocity, timeStep);
  92414. this.orientation.addTime(this.angularVelocity, timeStep);
  92415. break;
  92416. default: OIMO.Error("RigidBody", "Invalid type.");
  92417. }
  92418. this.syncShapes();
  92419. },
  92420. rotateInertia: function (rot, inertia, out) {
  92421. var tm1 = rot.elements;
  92422. var tm2 = inertia.elements;
  92423. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  92424. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  92425. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  92426. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  92427. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  92428. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  92429. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  92430. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  92431. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  92432. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  92433. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  92434. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  92435. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  92436. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  92437. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  92438. var oe = out.elements;
  92439. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  92440. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  92441. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  92442. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  92443. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  92444. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  92445. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  92446. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  92447. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  92448. },
  92449. syncShapes: function () {
  92450. var s = this.orientation.s;
  92451. var x = this.orientation.x;
  92452. var y = this.orientation.y;
  92453. var z = this.orientation.z;
  92454. var x2 = 2 * x;
  92455. var y2 = 2 * y;
  92456. var z2 = 2 * z;
  92457. var xx = x * x2;
  92458. var yy = y * y2;
  92459. var zz = z * z2;
  92460. var xy = x * y2;
  92461. var yz = y * z2;
  92462. var xz = x * z2;
  92463. var sx = s * x2;
  92464. var sy = s * y2;
  92465. var sz = s * z2;
  92466. var tr = this.rotation.elements;
  92467. tr[0] = 1 - yy - zz;
  92468. tr[1] = xy - sz;
  92469. tr[2] = xz + sy;
  92470. tr[3] = xy + sz;
  92471. tr[4] = 1 - xx - zz;
  92472. tr[5] = yz - sx;
  92473. tr[6] = xz - sy;
  92474. tr[7] = yz + sx;
  92475. tr[8] = 1 - xx - yy;
  92476. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  92477. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92478. //var relPos=shape.relativePosition;
  92479. //var relRot=shape.relativeRotation;
  92480. //var rot=shape.rotation;
  92481. /*var lx=relPos.x;
  92482. var ly=relPos.y;
  92483. var lz=relPos.z;
  92484. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  92485. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  92486. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  92487. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  92488. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  92489. // add by QuaziKb
  92490. shape.rotation.mul(this.rotation, shape.relativeRotation);
  92491. shape.updateProxy();
  92492. }
  92493. },
  92494. applyImpulse: function (position, force) {
  92495. this.linearVelocity.addScale(force, this.inverseMass);
  92496. /*this.linearVelocity.x+=force.x*this.inverseMass;
  92497. this.linearVelocity.y+=force.y*this.inverseMass;
  92498. this.linearVelocity.z+=force.z*this.inverseMass;*/
  92499. var rel = new OIMO.Vec3();
  92500. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  92501. this.angularVelocity.addEqual(rel);
  92502. /*this.angularVelocity.x+=rel.x;
  92503. this.angularVelocity.y+=rel.y;
  92504. this.angularVelocity.z+=rel.z;*/
  92505. },
  92506. //---------------------------------------------
  92507. //
  92508. // FOR THREE JS
  92509. //
  92510. //---------------------------------------------
  92511. rotationVectToQuad: function (rot) {
  92512. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  92513. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  92514. },
  92515. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  92516. var len = ax * ax + ay * ay + az * az;
  92517. if (len > 0) {
  92518. len = 1 / OIMO.sqrt(len);
  92519. ax *= len;
  92520. ay *= len;
  92521. az *= len;
  92522. }
  92523. var sin = OIMO.sin(rad * 0.5);
  92524. var cos = OIMO.cos(rad * 0.5);
  92525. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  92526. },
  92527. //---------------------------------------------
  92528. // SET DYNAMIQUE POSITION AND ROTATION
  92529. //---------------------------------------------
  92530. setPosition: function (pos) {
  92531. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  92532. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  92533. this.controlPos = true;
  92534. },
  92535. setQuaternion: function (q) {
  92536. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  92537. this.newOrientation.set(q.x, q.y, q.z, q.w);
  92538. this.controlRot = true;
  92539. },
  92540. setRotation: function (rot) {
  92541. this.newOrientation = this.rotationVectToQuad(rot);
  92542. this.controlRot = true;
  92543. },
  92544. //---------------------------------------------
  92545. // RESET DYNAMIQUE POSITION AND ROTATION
  92546. //---------------------------------------------
  92547. resetPosition: function (x, y, z) {
  92548. this.linearVelocity.set(0, 0, 0);
  92549. this.angularVelocity.set(0, 0, 0);
  92550. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  92551. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  92552. this.awake();
  92553. },
  92554. resetQuaternion: function (q) {
  92555. this.angularVelocity.set(0, 0, 0);
  92556. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  92557. this.awake();
  92558. },
  92559. resetRotation: function (x, y, z) {
  92560. this.angularVelocity.set(0, 0, 0);
  92561. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  92562. this.awake();
  92563. },
  92564. //---------------------------------------------
  92565. // GET POSITION AND ROTATION
  92566. //---------------------------------------------
  92567. getPosition: function () {
  92568. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  92569. },
  92570. getRotation: function () {
  92571. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  92572. },
  92573. getQuaternion: function () {
  92574. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  92575. },
  92576. getMatrix: function () {
  92577. var m = this.matrix.elements;
  92578. var r, p;
  92579. if (!this.sleeping) {
  92580. // rotation matrix
  92581. r = this.rotation.elements;
  92582. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  92583. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  92584. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  92585. // position matrix
  92586. p = this.position;
  92587. m[12] = p.x * OIMO.WORLD_SCALE;
  92588. m[13] = p.y * OIMO.WORLD_SCALE;
  92589. m[14] = p.z * OIMO.WORLD_SCALE;
  92590. // sleep or not ?
  92591. m[15] = 0;
  92592. } else {
  92593. m[15] = 1;
  92594. }
  92595. return m;
  92596. }
  92597. };
  92598. /**
  92599. * The main class of body.
  92600. * is for simplify creation process and data access of rigidRody
  92601. * Rigid body has the shape of a single or multiple collision processing,
  92602. * all setting in object
  92603. *
  92604. * @author loth
  92605. */
  92606. OIMO.Body = function (Obj) {
  92607. var obj = Obj || {};
  92608. if (!obj.world) return;
  92609. if (obj.type === undefined) obj.type = "box";
  92610. this.name = obj.name || '';
  92611. // obsolete use world.add(obj)
  92612. this.body = obj.world.add(obj);
  92613. /*
  92614. // the world where i am
  92615. this.parent = obj.world;
  92616. // Yep my name
  92617. this.name = obj.name || '';
  92618. // I'm dynamique or not
  92619. var move = obj.move || false;
  92620. // I can sleep or not
  92621. var noSleep = obj.noSleep || false;
  92622. // My start position
  92623. var p = obj.pos || [0,0,0];
  92624. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  92625. // My size
  92626. var s = obj.size || [1,1,1];
  92627. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  92628. // My rotation in degre
  92629. var rot = obj.rot || [0,0,0];
  92630. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  92631. var r = [];
  92632. for (var i=0; i<rot.length/3; i++){
  92633. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  92634. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  92635. }
  92636. // My physics setting
  92637. var sc = obj.sc || new OIMO.ShapeConfig();
  92638. if(obj.config){
  92639. // The density of the shape.
  92640. sc.density = obj.config[0] || 1;
  92641. // The coefficient of friction of the shape.
  92642. sc.friction = obj.config[1] || 0.4;
  92643. // The coefficient of restitution of the shape.
  92644. sc.restitution = obj.config[2] || 0.2;
  92645. // The bits of the collision groups to which the shape belongs.
  92646. sc.belongsTo = obj.config[3] || 1;
  92647. // The bits of the collision groups with which the shape collides.
  92648. sc.collidesWith = obj.config[4] || 0xffffffff;
  92649. }
  92650. if(obj.massPos){
  92651. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  92652. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  92653. }
  92654. if(obj.massRot){
  92655. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  92656. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  92657. }
  92658. // My rigidbody
  92659. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  92660. // My shapes
  92661. var shapes = [];
  92662. var type = obj.type || "box";
  92663. if( typeof type === 'string' ) type = [type];// single shape
  92664. var n, n2;
  92665. for(var i=0; i<type.length; i++){
  92666. n = i*3;
  92667. n2 = i*4;
  92668. switch(type[i]){
  92669. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  92670. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  92671. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  92672. }
  92673. this.body.addShape(shapes[i]);
  92674. if(i>0){
  92675. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  92676. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  92677. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  92678. }
  92679. }
  92680. // I'm static or i move
  92681. if(move){
  92682. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  92683. else this.body.setupMass(0x1, true);
  92684. if(noSleep) this.body.allowSleep = false;
  92685. else this.body.allowSleep = true;
  92686. } else {
  92687. this.body.setupMass(0x2);
  92688. }
  92689. this.body.name = this.name;
  92690. this.sleeping = this.body.sleeping;
  92691. // finaly add to physics world
  92692. this.parent.addRigidBody(this.body);*/
  92693. }
  92694. OIMO.Body.prototype = {
  92695. constructor: OIMO.Body,
  92696. // SET
  92697. setPosition: function (pos) {
  92698. this.body.setPosition(pos);
  92699. },
  92700. setQuaternion: function (q) {
  92701. this.body.setQuaternion(q);
  92702. },
  92703. setRotation: function (rot) {
  92704. this.body.setRotation(rot);
  92705. },
  92706. // GET
  92707. getPosition: function () {
  92708. return this.body.getPosition();
  92709. },
  92710. getRotation: function () {
  92711. return this.body.getRotation();
  92712. },
  92713. getQuaternion: function () {
  92714. return this.body.getQuaternion();
  92715. },
  92716. getMatrix: function () {
  92717. return this.body.getMatrix();
  92718. },
  92719. getSleep: function () {
  92720. return this.body.sleeping;
  92721. },
  92722. // RESET
  92723. resetPosition: function (x, y, z) {
  92724. this.body.resetPosition(x, y, z);
  92725. },
  92726. resetRotation: function (x, y, z) {
  92727. this.body.resetRotation(x, y, z);
  92728. },
  92729. // force wakeup
  92730. awake: function () {
  92731. this.body.awake();
  92732. },
  92733. // remove rigidbody
  92734. remove: function () {
  92735. this.body.dispose();
  92736. //this.parent.removeRigidBody(this.body);
  92737. },
  92738. // test if this object hit another
  92739. checkContact: function (name) {
  92740. this.body.checkContact(name);
  92741. //this.parent.checkContact(this.name, name);
  92742. }
  92743. }
  92744. /**
  92745. * The main class of link.
  92746. * is for simplify creation process and data access of Joint
  92747. * all setting in object
  92748. *
  92749. * @author loth
  92750. */
  92751. OIMO.Link = function (Obj) {
  92752. var obj = Obj || {};
  92753. if (!obj.world) return;
  92754. if (obj.type === undefined) obj.type = "jointHinge";
  92755. this.name = obj.name || '';
  92756. // obsolete use world.add(obj)
  92757. this.joint = obj.world.add(obj);
  92758. // the world where i am
  92759. /*this.parent = obj.world;
  92760. this.name = obj.name || '';
  92761. var type = obj.type || "jointHinge";
  92762. var axe1 = obj.axe1 || [1,0,0];
  92763. var axe2 = obj.axe2 || [1,0,0];
  92764. var pos1 = obj.pos1 || [0,0,0];
  92765. var pos2 = obj.pos2 || [0,0,0];
  92766. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  92767. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  92768. var min, max;
  92769. if(type==="jointDistance"){
  92770. min = obj.min || 0;
  92771. max = obj.max || 10;
  92772. min = min*OIMO.INV_SCALE;
  92773. max = max*OIMO.INV_SCALE;
  92774. }else{
  92775. min = obj.min || 57.29578;
  92776. max = obj.max || 0;
  92777. min = min*OIMO.TO_RAD;
  92778. max = max*OIMO.TO_RAD;
  92779. }
  92780. var limit = obj.limit || null;
  92781. var spring = obj.spring || null;
  92782. var motor = obj.motor || null;
  92783. // joint setting
  92784. var jc = new OIMO.JointConfig();
  92785. jc.allowCollision = obj.collision || false;;
  92786. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  92787. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  92788. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  92789. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  92790. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  92791. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  92792. jc.body1 = obj.body1;
  92793. jc.body2 = obj.body2;
  92794. switch(type){
  92795. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  92796. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  92797. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  92798. break;
  92799. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  92800. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  92801. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  92802. break;
  92803. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  92804. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  92805. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  92806. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  92807. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  92808. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  92809. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  92810. break;
  92811. }
  92812. this.joint.name = this.name;
  92813. // finaly add to physics world
  92814. this.parent.addJoint(this.joint);*/
  92815. }
  92816. OIMO.Link.prototype = {
  92817. constructor: OIMO.Link,
  92818. getPosition: function () {
  92819. // array of two vect3 [point1, point2]
  92820. return this.joint.getPosition();
  92821. },
  92822. getMatrix: function () {
  92823. return this.joint.getMatrix();
  92824. },
  92825. // remove joint
  92826. remove: function () {
  92827. this.joint.dispose();
  92828. //this.parent.removeJoint(this.joint);
  92829. },
  92830. // force wakeup linked body
  92831. awake: function () {
  92832. this.joint.awake();
  92833. }
  92834. }
  92835. /**
  92836. * The Dictionary class for testing
  92837. * @author lo-th
  92838. */
  92839. OIMO.Dictionary = function () {
  92840. this.data = {};
  92841. this.keys = [];
  92842. };
  92843. OIMO.Dictionary.prototype = {
  92844. constructor: OIMO.Dictionary,
  92845. set: function (value) {
  92846. var key = value.id;
  92847. if (!this.get[key]) this.keys.push(key);
  92848. this.data[key] = value;
  92849. },
  92850. get: function (id) {
  92851. return this.data[id];
  92852. },
  92853. del: function (value) {
  92854. var k = this.keys;
  92855. var n = k.indexOf(value.id);
  92856. if (n > -1) {
  92857. delete this.data[k[n]];
  92858. k.splice(n, 1);
  92859. }
  92860. },
  92861. reset: function () {
  92862. var data = this.data, keys = this.keys, key;
  92863. while (keys.length > 0) {
  92864. key = keys.pop();
  92865. delete data[key];
  92866. }
  92867. }
  92868. };
  92869. OIMO.Performance = function (world) {
  92870. this.parent = world;
  92871. this.infos = new OIMO_ARRAY_TYPE(13);
  92872. this.f = [0, 0, 0];
  92873. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  92874. this.broadPhase = this.types[this.parent.broadPhase.types];
  92875. this.version = OIMO.REVISION;
  92876. this.fps = 0;
  92877. this.broadPhaseTime = 0;
  92878. this.narrowPhaseTime = 0;
  92879. this.solvingTime = 0;
  92880. //this.updatingTime = 0;
  92881. this.totalTime = 0;
  92882. };
  92883. OIMO.Performance.prototype = {
  92884. upfps: function () {
  92885. this.f[1] = Date.now();
  92886. 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]++;
  92887. },
  92888. updatingTime: function () {
  92889. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  92890. },
  92891. show: function () {
  92892. var info = [
  92893. "Oimo.js " + this.version + "<br>",
  92894. this.broadPhase + "<br><br>",
  92895. "FPS: " + this.fps + " fps<br><br>",
  92896. "rigidbody " + this.parent.numRigidBodies + "<br>",
  92897. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  92898. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  92899. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  92900. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  92901. "Time in milliseconde<br><br>",
  92902. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  92903. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  92904. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  92905. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  92906. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  92907. ].join("\n");
  92908. return info;
  92909. },
  92910. toArray: function () {
  92911. this.infos[0] = this.parent.broadPhase.types;
  92912. this.infos[1] = this.parent.numRigidBodies;
  92913. this.infos[2] = this.parent.numContacts;
  92914. this.infos[3] = this.parent.broadPhase.numPairChecks;
  92915. this.infos[4] = this.parent.numContactPoints;
  92916. this.infos[5] = this.parent.numIslands;
  92917. this.infos[6] = this.broadPhaseTime;
  92918. this.infos[7] = this.narrowPhaseTime;
  92919. this.infos[8] = this.solvingTime;
  92920. this.infos[9] = this.updatingTime();
  92921. this.infos[10] = this.totalTime;
  92922. this.infos[11] = this.fps;
  92923. return this.infos;
  92924. }
  92925. };
  92926. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  92927. this.elements = new OIMO_ARRAY_TYPE(16);
  92928. var te = this.elements;
  92929. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  92930. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  92931. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  92932. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  92933. };
  92934. OIMO.Mat44.prototype = {
  92935. constructor: OIMO.Mat44,
  92936. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  92937. var te = this.elements;
  92938. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  92939. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  92940. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  92941. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  92942. return this;
  92943. }/*,
  92944. extractRotation: function () {
  92945. var v1 = new THREE.Vector3();
  92946. return function ( m ) {
  92947. var te = this.elements;
  92948. var me = m.elements;
  92949. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  92950. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  92951. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  92952. te[ 0 ] = me[ 0 ] * scaleX;
  92953. te[ 1 ] = me[ 1 ] * scaleX;
  92954. te[ 2 ] = me[ 2 ] * scaleX;
  92955. te[ 4 ] = me[ 4 ] * scaleY;
  92956. te[ 5 ] = me[ 5 ] * scaleY;
  92957. te[ 6 ] = me[ 6 ] * scaleY;
  92958. te[ 8 ] = me[ 8 ] * scaleZ;
  92959. te[ 9 ] = me[ 9 ] * scaleZ;
  92960. te[ 10 ] = me[ 10 ] * scaleZ;
  92961. return this;
  92962. };
  92963. }() */
  92964. }
  92965. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  92966. this.elements = new OIMO_ARRAY_TYPE(9);
  92967. var te = this.elements;
  92968. this.init(
  92969. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  92970. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  92971. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  92972. );
  92973. };
  92974. OIMO.Mat33.prototype = {
  92975. constructor: OIMO.Mat33,
  92976. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  92977. var te = this.elements;
  92978. te[0] = e00; te[1] = e01; te[2] = e02;
  92979. te[3] = e10; te[4] = e11; te[5] = e12;
  92980. te[6] = e20; te[7] = e21; te[8] = e22;
  92981. return this;
  92982. },
  92983. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  92984. var te = this.elements;
  92985. te[0] = e00; te[1] = e01; te[2] = e02;
  92986. te[3] = e10; te[4] = e11; te[5] = e12;
  92987. te[6] = e20; te[7] = e21; te[8] = e22;
  92988. return this;
  92989. },
  92990. multiply: function (s) {
  92991. var te = this.elements;
  92992. te[0] *= s; te[1] *= s; te[2] *= s;
  92993. te[3] *= s; te[4] *= s; te[5] *= s;
  92994. te[6] *= s; te[7] *= s; te[8] *= s;
  92995. return this;
  92996. },
  92997. add: function (m1, m2) {
  92998. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  92999. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  93000. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  93001. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  93002. return this;
  93003. },
  93004. addEqual: function (m) {
  93005. var te = this.elements, tem = m.elements;
  93006. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  93007. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  93008. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  93009. return this;
  93010. },
  93011. sub: function (m1, m2) {
  93012. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93013. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  93014. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  93015. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  93016. return this;
  93017. },
  93018. subEqual: function (m) {
  93019. var te = this.elements, tem = m.elements;
  93020. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  93021. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  93022. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  93023. return this;
  93024. },
  93025. scale: function (m, s) {
  93026. var te = this.elements, tm = m.elements;
  93027. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  93028. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  93029. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  93030. return this;
  93031. },
  93032. scaleEqual: function (s) {
  93033. var te = this.elements;
  93034. te[0] *= s; te[1] *= s; te[2] *= s;
  93035. te[3] *= s; te[4] *= s; te[5] *= s;
  93036. te[6] *= s; te[7] *= s; te[8] *= s;
  93037. return this;
  93038. },
  93039. mul: function (m1, m2) {
  93040. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  93041. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  93042. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  93043. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  93044. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  93045. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  93046. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93047. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  93048. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  93049. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  93050. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  93051. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  93052. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  93053. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  93054. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  93055. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  93056. return this;
  93057. },
  93058. mulScale: function (m, sx, sy, sz, Prepend) {
  93059. var prepend = Prepend || false;
  93060. var te = this.elements, tm = m.elements;
  93061. if (prepend) {
  93062. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  93063. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  93064. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  93065. } else {
  93066. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  93067. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  93068. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  93069. }
  93070. return this;
  93071. },
  93072. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  93073. var prepend = Prepend || false;
  93074. var s = OIMO.sin(rad);
  93075. var c = OIMO.cos(rad);
  93076. var c1 = 1 - c;
  93077. var r00 = ax * ax * c1 + c;
  93078. var r01 = ax * ay * c1 - az * s;
  93079. var r02 = ax * az * c1 + ay * s;
  93080. var r10 = ay * ax * c1 + az * s;
  93081. var r11 = ay * ay * c1 + c;
  93082. var r12 = ay * az * c1 - ax * s;
  93083. var r20 = az * ax * c1 - ay * s;
  93084. var r21 = az * ay * c1 + ax * s;
  93085. var r22 = az * az * c1 + c;
  93086. var tm = m.elements;
  93087. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  93088. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  93089. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  93090. var te = this.elements;
  93091. if (prepend) {
  93092. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  93093. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  93094. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  93095. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  93096. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  93097. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  93098. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  93099. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  93100. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  93101. } else {
  93102. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  93103. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  93104. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  93105. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  93106. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  93107. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  93108. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  93109. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  93110. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  93111. }
  93112. return this;
  93113. },
  93114. transpose: function (m) {
  93115. var te = this.elements, tm = m.elements;
  93116. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  93117. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  93118. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  93119. return this;
  93120. },
  93121. setQuat: function (q) {
  93122. var te = this.elements,
  93123. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  93124. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  93125. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  93126. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  93127. te[0] = 1 - yy - zz;
  93128. te[1] = xy - sz;
  93129. te[2] = xz + sy;
  93130. te[3] = xy + sz;
  93131. te[4] = 1 - xx - zz;
  93132. te[5] = yz - sx;
  93133. te[6] = xz - sy;
  93134. te[7] = yz + sx;
  93135. te[8] = 1 - xx - yy;
  93136. return this;
  93137. },
  93138. invert: function (m) {
  93139. var te = this.elements, tm = m.elements,
  93140. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  93141. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  93142. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  93143. b01 = a4 * a8 - a7 * a5,
  93144. b11 = a7 * a2 - a1 * a8,
  93145. b21 = a1 * a5 - a4 * a2,
  93146. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  93147. if (dt != 0) { dt = 1.0 / dt; }
  93148. te[0] = dt * b01;//(a4*a8 - a5*a7);
  93149. te[1] = dt * b11;//(a2*a7 - a1*a8);
  93150. te[2] = dt * b21;//(a1*a5 - a2*a4);
  93151. te[3] = dt * (a5 * a6 - a3 * a8);
  93152. te[4] = dt * (a0 * a8 - a2 * a6);
  93153. te[5] = dt * (a2 * a3 - a0 * a5);
  93154. te[6] = dt * (a3 * a7 - a4 * a6);
  93155. te[7] = dt * (a1 * a6 - a0 * a7);
  93156. te[8] = dt * (a0 * a4 - a1 * a3);
  93157. return this;
  93158. },
  93159. /*copy: function(m){
  93160. var te = this.elements, tem = m.elements;
  93161. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  93162. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  93163. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  93164. return this;
  93165. },*/
  93166. toEuler: function () { // not work !!
  93167. function clamp(x) {
  93168. return OIMO.min(OIMO.max(x, -1), 1);
  93169. }
  93170. var te = this.elements;
  93171. var m11 = te[0], m12 = te[3], m13 = te[6];
  93172. var m21 = te[1], m22 = te[4], m23 = te[7];
  93173. var m31 = te[2], m32 = te[5], m33 = te[8];
  93174. var p = new OIMO.Vec3();
  93175. var d = new OIMO.Quat();
  93176. var s;
  93177. p.y = OIMO.asin(clamp(m13));
  93178. if (OIMO.abs(m13) < 0.99999) {
  93179. p.x = OIMO.atan2(-m23, m33);
  93180. p.z = OIMO.atan2(-m12, m11);
  93181. } else {
  93182. p.x = OIMO.atan2(m32, m22);
  93183. p.z = 0;
  93184. }
  93185. return p;
  93186. },
  93187. /*clone: function(){
  93188. var te = this.elements;
  93189. return new OIMO.Mat33(
  93190. te[0], te[1], te[2],
  93191. te[3], te[4], te[5],
  93192. te[6], te[7], te[8]
  93193. );
  93194. },*/
  93195. toString: function () {
  93196. var te = this.elements;
  93197. var text =
  93198. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  93199. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  93200. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  93201. return text;
  93202. },
  93203. // OK
  93204. multiplyScalar: function (s) {
  93205. var te = this.elements;
  93206. te[0] *= s; te[3] *= s; te[6] *= s;
  93207. te[1] *= s; te[4] *= s; te[7] *= s;
  93208. te[2] *= s; te[5] *= s; te[8] *= s;
  93209. return this;
  93210. },
  93211. identity: function () {
  93212. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  93213. return this;
  93214. },
  93215. clone: function () {
  93216. return new this.constructor().fromArray(this.elements);
  93217. },
  93218. copy: function (m) {
  93219. var me = m.elements;
  93220. this.set(
  93221. me[0], me[3], me[6],
  93222. me[1], me[4], me[7],
  93223. me[2], me[5], me[8]
  93224. );
  93225. return this;
  93226. },
  93227. fromArray: function (array) {
  93228. this.elements.set(array);
  93229. return this;
  93230. },
  93231. toArray: function () {
  93232. var te = this.elements;
  93233. return [
  93234. te[0], te[1], te[2],
  93235. te[3], te[4], te[5],
  93236. te[6], te[7], te[8]
  93237. ];
  93238. }
  93239. };
  93240. OIMO.Quat = function (s, x, y, z) {
  93241. this.s = (s !== undefined) ? s : 1;
  93242. this.x = x || 0;
  93243. this.y = y || 0;
  93244. this.z = z || 0;
  93245. };
  93246. OIMO.Quat.prototype = {
  93247. constructor: OIMO.Quat,
  93248. set: function (x, y, z, w) {
  93249. this.x = x;
  93250. this.y = y;
  93251. this.z = z;
  93252. this.s = w;
  93253. return this;
  93254. },
  93255. init: function (s, x, y, z) {
  93256. this.s = (s !== undefined) ? s : 1;
  93257. this.x = x || 0;
  93258. this.y = y || 0;
  93259. this.z = z || 0;
  93260. return this;
  93261. },
  93262. add: function (q1, q2) {
  93263. this.s = q1.s + q2.s;
  93264. this.x = q1.x + q2.x;
  93265. this.y = q1.y + q2.y;
  93266. this.z = q1.z + q2.z;
  93267. return this;
  93268. },
  93269. addTime: function (v, t) {
  93270. var x = v.x;
  93271. var y = v.y;
  93272. var z = v.z;
  93273. var qs = this.s;
  93274. var qx = this.x;
  93275. var qy = this.y;
  93276. var qz = this.z;
  93277. t *= 0.5;
  93278. var ns = (-x * qx - y * qy - z * qz) * t;
  93279. var nx = (x * qs + y * qz - z * qy) * t;
  93280. var ny = (-x * qz + y * qs + z * qx) * t;
  93281. var nz = (x * qy - y * qx + z * qs) * t;
  93282. qs += ns;
  93283. qx += nx;
  93284. qy += ny;
  93285. qz += nz;
  93286. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  93287. this.s = qs * s;
  93288. this.x = qx * s;
  93289. this.y = qy * s;
  93290. this.z = qz * s;
  93291. return this;
  93292. },
  93293. sub: function (q1, q2) {
  93294. this.s = q1.s - q2.s;
  93295. this.x = q1.x - q2.x;
  93296. this.y = q1.y - q2.y;
  93297. this.z = q1.z - q2.z;
  93298. return this;
  93299. },
  93300. scale: function (q, s) {
  93301. this.s = q.s * s;
  93302. this.x = q.x * s;
  93303. this.y = q.y * s;
  93304. this.z = q.z * s;
  93305. return this;
  93306. },
  93307. mul: function (q1, q2) {
  93308. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  93309. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  93310. this.x = ax * bs + as * bx + ay * bz - az * by;
  93311. this.y = ay * bs + as * by + az * bx - ax * bz;
  93312. this.z = az * bs + as * bz + ax * by - ay * bx;
  93313. this.s = as * bs - ax * bx - ay * by - az * bz;
  93314. return this;
  93315. },
  93316. arc: function (v1, v2) {
  93317. var x1 = v1.x;
  93318. var y1 = v1.y;
  93319. var z1 = v1.z;
  93320. var x2 = v2.x;
  93321. var y2 = v2.y;
  93322. var z2 = v2.z;
  93323. var d = x1 * x2 + y1 * y2 + z1 * z2;
  93324. if (d == -1) {
  93325. x2 = y1 * x1 - z1 * z1;
  93326. y2 = -z1 * y1 - x1 * x1;
  93327. z2 = x1 * z1 + y1 * y1;
  93328. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  93329. this.s = 0;
  93330. this.x = x2 * d;
  93331. this.y = y2 * d;
  93332. this.z = z2 * d;
  93333. return this;
  93334. }
  93335. var cx = y1 * z2 - z1 * y2;
  93336. var cy = z1 * x2 - x1 * z2;
  93337. var cz = x1 * y2 - y1 * x2;
  93338. this.s = OIMO.sqrt((1 + d) * 0.5);
  93339. d = 0.5 / this.s;
  93340. this.x = cx * d;
  93341. this.y = cy * d;
  93342. this.z = cz * d;
  93343. return this;
  93344. },
  93345. normalize: function (q) {
  93346. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  93347. if (len > 0) { len = 1 / len; }
  93348. this.s = q.s * len;
  93349. this.x = q.x * len;
  93350. this.y = q.y * len;
  93351. this.z = q.z * len;
  93352. return this;
  93353. },
  93354. invert: function (q) {
  93355. this.s = q.s;
  93356. this.x = -q.x;
  93357. this.y = -q.y;
  93358. this.z = -q.z;
  93359. return this;
  93360. },
  93361. length: function () {
  93362. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  93363. },
  93364. copy: function (q) {
  93365. this.s = q.s;
  93366. this.x = q.x;
  93367. this.y = q.y;
  93368. this.z = q.z;
  93369. return this;
  93370. },
  93371. testDiff: function (q) {
  93372. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  93373. else return false;
  93374. },
  93375. clone: function (q) {
  93376. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  93377. },
  93378. toString: function () {
  93379. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  93380. }
  93381. }
  93382. // for three easy export
  93383. OIMO.Quaternion = function (x, y, z, w) {
  93384. this.x = x || 0;
  93385. this.y = y || 0;
  93386. this.z = z || 0;
  93387. this.w = (w !== undefined) ? w : 1;
  93388. };
  93389. OIMO.Quaternion.prototype = {
  93390. constructor: OIMO.Quaternion,
  93391. setFromRotationMatrix: function (m) {
  93392. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  93393. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  93394. var te = m.elements,
  93395. m11 = te[0], m12 = te[1], m13 = te[2],
  93396. m21 = te[3], m22 = te[4], m23 = te[5],
  93397. m31 = te[6], m32 = te[7], m33 = te[8],
  93398. trace = m11 + m22 + m33,
  93399. s;
  93400. if (trace > 0) {
  93401. s = 0.5 / OIMO.sqrt(trace + 1.0);
  93402. this.w = 0.25 / s;
  93403. this.x = (m32 - m23) * s;
  93404. this.y = (m13 - m31) * s;
  93405. this.z = (m21 - m12) * s;
  93406. } else if (m11 > m22 && m11 > m33) {
  93407. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  93408. this.w = (m32 - m23) / s;
  93409. this.x = 0.25 * s;
  93410. this.y = (m12 + m21) / s;
  93411. this.z = (m13 + m31) / s;
  93412. } else if (m22 > m33) {
  93413. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  93414. this.w = (m13 - m31) / s;
  93415. this.x = (m12 + m21) / s;
  93416. this.y = 0.25 * s;
  93417. this.z = (m23 + m32) / s;
  93418. } else {
  93419. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  93420. this.w = (m21 - m12) / s;
  93421. this.x = (m13 + m31) / s;
  93422. this.y = (m23 + m32) / s;
  93423. this.z = 0.25 * s;
  93424. }
  93425. //this.onChangeCallback();
  93426. return this;
  93427. }
  93428. }
  93429. OIMO.Vec3 = function (x, y, z) {
  93430. this.x = x || 0;
  93431. this.y = y || 0;
  93432. this.z = z || 0;
  93433. };
  93434. OIMO.Vec3.prototype = {
  93435. constructor: OIMO.Vec3,
  93436. init: function (x, y, z) {
  93437. this.x = x || 0;
  93438. this.y = y || 0;
  93439. this.z = z || 0;
  93440. return this;
  93441. },
  93442. set: function (x, y, z) {
  93443. this.x = x;
  93444. this.y = y;
  93445. this.z = z;
  93446. return this;
  93447. },
  93448. add: function (v1, v2) {
  93449. this.x = v1.x + v2.x;
  93450. this.y = v1.y + v2.y;
  93451. this.z = v1.z + v2.z;
  93452. return this;
  93453. },
  93454. addEqual: function (v) {
  93455. this.x += v.x;
  93456. this.y += v.y;
  93457. this.z += v.z;
  93458. return this;
  93459. },
  93460. addTime: function (v, t) {
  93461. this.x += v.x * t;
  93462. this.y += v.y * t;
  93463. this.z += v.z * t;
  93464. return this;
  93465. },
  93466. sub: function (v1, v2) {
  93467. this.x = v1.x - v2.x;
  93468. this.y = v1.y - v2.y;
  93469. this.z = v1.z - v2.z;
  93470. return this;
  93471. },
  93472. subEqual: function (v) {
  93473. this.x -= v.x;
  93474. this.y -= v.y;
  93475. this.z -= v.z;
  93476. return this;
  93477. },
  93478. addScale: function (v, s) {
  93479. this.x += v.x * s;
  93480. this.y += v.y * s;
  93481. this.z += v.z * s;
  93482. return this;
  93483. },
  93484. scale: function (v, s) {
  93485. this.x = v.x * s;
  93486. this.y = v.y * s;
  93487. this.z = v.z * s;
  93488. return this;
  93489. },
  93490. scaleEqual: function (s) {
  93491. this.x *= s;
  93492. this.y *= s;
  93493. this.z *= s;
  93494. return this;
  93495. },
  93496. /*dot: function(v){
  93497. return this.x*v.x+this.y*v.y+this.z*v.z;
  93498. },*/
  93499. cross: function (v1, v2) {
  93500. var ax = v1.x, ay = v1.y, az = v1.z,
  93501. bx = v2.x, by = v2.y, bz = v2.z;
  93502. this.x = ay * bz - az * by;
  93503. this.y = az * bx - ax * bz;
  93504. this.z = ax * by - ay * bx;
  93505. return this;
  93506. },
  93507. mul: function (o, v, m) {
  93508. var te = m.elements;
  93509. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  93510. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  93511. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  93512. return this;
  93513. },
  93514. mulMat: function (m, v) {
  93515. var te = m.elements;
  93516. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  93517. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  93518. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  93519. return this;
  93520. },
  93521. normalize: function (v) {
  93522. var x = v.x, y = v.y, z = v.z;
  93523. var l = x * x + y * y + z * z;
  93524. if (l > 0) {
  93525. l = 1 / OIMO.sqrt(l);
  93526. this.x = x * l;
  93527. this.y = y * l;
  93528. this.z = z * l;
  93529. }
  93530. return this;
  93531. },
  93532. /*norm: function(){
  93533. var x = this.x, y = this.y, z = this.z;
  93534. var l = x*x + y*y + z*z;
  93535. if (l > 0) {
  93536. l = 1 / OIMO.sqrt(l);
  93537. this.x = x*l;
  93538. this.y = y*l;
  93539. this.z = z*l;
  93540. }
  93541. return this;
  93542. },*/
  93543. invert: function (v) {
  93544. this.x = -v.x;
  93545. this.y = -v.y;
  93546. this.z = -v.z;
  93547. return this;
  93548. },
  93549. /*length: function(){
  93550. var x = this.x, y = this.y, z = this.z;
  93551. return OIMO.sqrt(x*x + y*y + z*z);
  93552. },*/
  93553. negate: function () {
  93554. this.x = -this.x;
  93555. this.y = -this.y;
  93556. this.z = -this.z;
  93557. return this;
  93558. },
  93559. dot: function (v) {
  93560. return this.x * v.x + this.y * v.y + this.z * v.z;
  93561. },
  93562. lengthSq: function () {
  93563. return this.x * this.x + this.y * this.y + this.z * this.z;
  93564. },
  93565. length: function () {
  93566. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  93567. },
  93568. /*len: function(){
  93569. var x = this.x, y = this.y, z = this.z;
  93570. return x*x + y*y + z*z;
  93571. },*/
  93572. copy: function (v) {
  93573. this.x = v.x;
  93574. this.y = v.y;
  93575. this.z = v.z;
  93576. return this;
  93577. },
  93578. applyQuaternion: function (q) {
  93579. var x = this.x;
  93580. var y = this.y;
  93581. var z = this.z;
  93582. var qx = q.x;
  93583. var qy = q.y;
  93584. var qz = q.z;
  93585. var qs = q.s;
  93586. // calculate quat * vector
  93587. var ix = qs * x + qy * z - qz * y;
  93588. var iy = qs * y + qz * x - qx * z;
  93589. var iz = qs * z + qx * y - qy * x;
  93590. var iw = -qx * x - qy * y - qz * z;
  93591. // calculate result * inverse quat
  93592. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  93593. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  93594. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  93595. return this;
  93596. },
  93597. testZero: function () {
  93598. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  93599. else return false;
  93600. },
  93601. testDiff: function (v) {
  93602. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  93603. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  93604. //else return false;
  93605. },
  93606. equals: function (v) {
  93607. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  93608. },
  93609. clone: function () {
  93610. return new this.constructor(this.x, this.y, this.z);
  93611. },
  93612. toString: function () {
  93613. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  93614. },
  93615. multiplyScalar: function (scalar) {
  93616. if (isFinite(scalar)) {
  93617. this.x *= scalar;
  93618. this.y *= scalar;
  93619. this.z *= scalar;
  93620. } else {
  93621. this.x = 0;
  93622. this.y = 0;
  93623. this.z = 0;
  93624. }
  93625. return this;
  93626. },
  93627. divideScalar: function (scalar) {
  93628. return this.multiplyScalar(1 / scalar);
  93629. },
  93630. // TODO rename to normalize
  93631. norm: function () {
  93632. return this.divideScalar(this.length());
  93633. },
  93634. }
  93635. OIMO.Euler = function (x, y, z, order) {
  93636. this._x = x || 0;
  93637. this._y = y || 0;
  93638. this._z = z || 0;
  93639. this._order = order || OIMO.Euler.DefaultOrder;
  93640. };
  93641. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  93642. OIMO.Euler.DefaultOrder = 'XYZ';
  93643. OIMO.clamp = function (x, a, b) {
  93644. return (x < a) ? a : ((x > b) ? b : x);
  93645. }
  93646. OIMO.Euler.prototype = {
  93647. constructor: OIMO.Euler,
  93648. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  93649. get x() {
  93650. return this._x;
  93651. },
  93652. set x(value) {
  93653. this._x = value;
  93654. this.onChangeCallback();
  93655. },
  93656. get y() {
  93657. return this._y;
  93658. },
  93659. set y(value) {
  93660. this._y = value;
  93661. this.onChangeCallback();
  93662. },
  93663. get z() {
  93664. return this._z;
  93665. },
  93666. set z(value) {
  93667. this._z = value;
  93668. this.onChangeCallback();
  93669. },
  93670. get order() {
  93671. return this._order;
  93672. },
  93673. set order(value) {
  93674. this._order = value;
  93675. this.onChangeCallback();
  93676. },
  93677. set: function (x, y, z, order) {
  93678. this._x = x;
  93679. this._y = y;
  93680. this._z = z;
  93681. this._order = order || this._order;
  93682. this.onChangeCallback();
  93683. return this;
  93684. },
  93685. copy: function (euler) {
  93686. this._x = euler._x;
  93687. this._y = euler._y;
  93688. this._z = euler._z;
  93689. this._order = euler._order;
  93690. this.onChangeCallback();
  93691. return this;
  93692. },
  93693. setFromRotationMatrix: function (m, order) {
  93694. var clamp = OIMO.clamp;
  93695. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  93696. var te = m.elements;
  93697. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  93698. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  93699. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  93700. var m11 = te[0], m12 = te[1], m13 = te[2],
  93701. m21 = te[3], m22 = te[4], m23 = te[5],
  93702. m31 = te[6], m32 = te[7], m33 = te[8];
  93703. order = order || this._order;
  93704. if (order === 'XYZ') {
  93705. this._y = OIMO.asin(clamp(m13, -1, 1));
  93706. if (OIMO.abs(m13) < 0.99999) {
  93707. this._x = OIMO.atan2(-m23, m33);
  93708. this._z = OIMO.atan2(-m12, m11);
  93709. } else {
  93710. this._x = OIMO.atan2(m32, m22);
  93711. this._z = 0;
  93712. }
  93713. } else if (order === 'YXZ') {
  93714. this._x = OIMO.asin(-clamp(m23, -1, 1));
  93715. if (OIMO.abs(m23) < 0.99999) {
  93716. this._y = OIMO.atan2(m13, m33);
  93717. this._z = OIMO.atan2(m21, m22);
  93718. } else {
  93719. this._y = OIMO.atan2(-m31, m11);
  93720. this._z = 0;
  93721. }
  93722. } else if (order === 'ZXY') {
  93723. this._x = OIMO.asin(clamp(m32, -1, 1));
  93724. if (OIMO.abs(m32) < 0.99999) {
  93725. this._y = OIMO.atan2(-m31, m33);
  93726. this._z = OIMO.atan2(-m12, m22);
  93727. } else {
  93728. this._y = 0;
  93729. this._z = OIMO.atan2(m21, m11);
  93730. }
  93731. } else if (order === 'ZYX') {
  93732. this._y = OIMO.asin(-clamp(m31, -1, 1));
  93733. if (OIMO.abs(m31) < 0.99999) {
  93734. this._x = OIMO.atan2(m32, m33);
  93735. this._z = OIMO.atan2(m21, m11);
  93736. } else {
  93737. this._x = 0;
  93738. this._z = OIMO.atan2(-m12, m22);
  93739. }
  93740. } else if (order === 'YZX') {
  93741. this._z = OIMO.asin(clamp(m21, -1, 1));
  93742. if (OIMO.abs(m21) < 0.99999) {
  93743. this._x = OIMO.atan2(-m23, m22);
  93744. this._y = OIMO.atan2(-m31, m11);
  93745. } else {
  93746. this._x = 0;
  93747. this._y = OIMO.atan2(m13, m33);
  93748. }
  93749. } else if (order === 'XZY') {
  93750. this._z = OIMO.asin(-clamp(m12, -1, 1));
  93751. if (OIMO.abs(m12) < 0.99999) {
  93752. this._x = OIMO.atan2(m32, m22);
  93753. this._y = OIMO.atan2(m13, m11);
  93754. } else {
  93755. this._x = OIMO.atan2(-m23, m33);
  93756. this._y = 0;
  93757. }
  93758. } else {
  93759. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  93760. }
  93761. this._order = order;
  93762. this.onChangeCallback();
  93763. return this;
  93764. },
  93765. setFromQuaternion: function (q, order, update) {
  93766. var clamp = OIMO.clamp;
  93767. // q is assumed to be normalized
  93768. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  93769. var sqx = q.x * q.x;
  93770. var sqy = q.y * q.y;
  93771. var sqz = q.z * q.z;
  93772. var sqw = q.s * q.s;
  93773. order = order || this._order;
  93774. if (order === 'XYZ') {
  93775. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  93776. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  93777. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  93778. } else if (order === 'YXZ') {
  93779. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  93780. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  93781. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  93782. } else if (order === 'ZXY') {
  93783. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  93784. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  93785. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  93786. } else if (order === 'ZYX') {
  93787. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  93788. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  93789. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  93790. } else if (order === 'YZX') {
  93791. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  93792. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  93793. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  93794. } else if (order === 'XZY') {
  93795. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  93796. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  93797. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  93798. } else {
  93799. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  93800. }
  93801. this._order = order;
  93802. if (update !== false) this.onChangeCallback();
  93803. return this;
  93804. },
  93805. reorder: function () {
  93806. // WARNING: this discards revolution information -bhouston
  93807. var q = new OIMO.Quat();
  93808. return function (newOrder) {
  93809. q.setFromEuler(this);
  93810. this.setFromQuaternion(q, newOrder);
  93811. };
  93812. }(),
  93813. equals: function (euler) {
  93814. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  93815. },
  93816. fromArray: function (array) {
  93817. this._x = array[0];
  93818. this._y = array[1];
  93819. this._z = array[2];
  93820. if (array[3] !== undefined) this._order = array[3];
  93821. this.onChangeCallback();
  93822. return this;
  93823. },
  93824. toArray: function () {
  93825. return [this._x, this._y, this._z, this._order];
  93826. },
  93827. onChange: function (callback) {
  93828. this.onChangeCallback = callback;
  93829. return this;
  93830. },
  93831. onChangeCallback: function () { },
  93832. clone: function () {
  93833. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  93834. }
  93835. };
  93836. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  93837. var c1 = OIMO.cos(oy * 0.5);//heading
  93838. var s1 = OIMO.sin(oy * 0.5);
  93839. var c2 = OIMO.cos(oz * 0.5);//altitude
  93840. var s2 = OIMO.sin(oz * 0.5);
  93841. var c3 = OIMO.cos(ox * 0.5);//bank
  93842. var s3 = OIMO.sin(ox * 0.5);
  93843. var c1c2 = c1 * c2;
  93844. var s1s2 = s1 * s2;
  93845. var w = c1c2 * c3 - s1s2 * s3;
  93846. var x = c1c2 * s3 + s1s2 * c3;
  93847. var y = s1 * c2 * c3 + c1 * s2 * s3;
  93848. var z = c1 * s2 * c3 - s1 * c2 * s3;
  93849. var angle = 2 * OIMO.acos(w);
  93850. var norm = x * x + y * y + z * z;
  93851. if (norm < 0.001) {
  93852. x = 1;
  93853. y = z = 0;
  93854. } else {
  93855. norm = OIMO.sqrt(norm);
  93856. x /= norm;
  93857. y /= norm;
  93858. z /= norm;
  93859. }
  93860. return [angle, x, y, z];
  93861. }
  93862. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  93863. var ch = OIMO.cos(oy);//heading
  93864. var sh = OIMO.sin(oy);
  93865. var ca = OIMO.cos(oz);//altitude
  93866. var sa = OIMO.sin(oz);
  93867. var cb = OIMO.cos(ox);//bank
  93868. var sb = OIMO.sin(ox);
  93869. var mtx = new OIMO.Mat33();
  93870. var te = mtx.elements;
  93871. te[0] = ch * ca;
  93872. te[1] = sh * sb - ch * sa * cb;
  93873. te[2] = ch * sa * sb + sh * cb;
  93874. te[3] = sa;
  93875. te[4] = ca * cb;
  93876. te[5] = -ca * sb;
  93877. te[6] = -sh * ca;
  93878. te[7] = sh * sa * cb + ch * sb;
  93879. te[8] = -sh * sa * sb + ch * cb;
  93880. return mtx;
  93881. }
  93882. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  93883. var te = mtx.elements;
  93884. var x, y, z;
  93885. if (te[3] > 0.998) { // singularity at north pole
  93886. y = OIMO.atan2(te[2], te[8]);
  93887. z = OIMO.PI / 2;
  93888. x = 0;
  93889. } else if (te[3] < -0.998) { // singularity at south pole
  93890. y = OIMO.atan2(te[2], te[8]);
  93891. z = -OIMO.PI / 2;
  93892. x = 0;
  93893. } else {
  93894. y = OIMO.atan2(-te[6], te[0]);
  93895. x = OIMO.atan2(-te[5], te[4]);
  93896. z = OIMO.asin(te[3]);
  93897. }
  93898. return [x, y, z];
  93899. }
  93900. OIMO.unwrapDegrees = function (r) {
  93901. r = r % 360;
  93902. if (r > 180) r -= 360;
  93903. if (r < -180) r += 360;
  93904. return r;
  93905. }
  93906. OIMO.unwrapRadian = function (r) {
  93907. r = r % OIMO.TwoPI;
  93908. if (r > OIMO.PI) r -= OIMO.TwoPI;
  93909. if (r < -OIMO.PI) r += OIMO.TwoPI;
  93910. return r;
  93911. }
  93912. OIMO.Distance3d = function (p1, p2) {
  93913. var xd = p2[0] - p1[0];
  93914. var yd = p2[1] - p1[1];
  93915. var zd = p2[2] - p1[2];
  93916. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  93917. }
  93918. /**
  93919. * The base class of all type of the constraints.
  93920. * @author saharan
  93921. */
  93922. OIMO.Constraint = function () {
  93923. // The parent world of the constraint.
  93924. this.parent = null;
  93925. // The first body of the constraint.
  93926. this.body1 = null;
  93927. // The second body of the constraint.
  93928. this.body2 = null;
  93929. // Internal
  93930. this.addedToIsland = false;
  93931. }
  93932. OIMO.Constraint.prototype = {
  93933. constructor: OIMO.Constraint,
  93934. /**
  93935. * Prepare for solving the constraint.
  93936. * @param timeStep
  93937. * @param invTimeStep
  93938. */
  93939. preSolve: function (timeStep, invTimeStep) {
  93940. OIMO.Error("Constraint", "Inheritance error.");
  93941. },
  93942. /**
  93943. * Solve the constraint.
  93944. * This is usually called iteratively.
  93945. */
  93946. solve: function () {
  93947. OIMO.Error("Constraint", "Inheritance error.");
  93948. },
  93949. /**
  93950. * Do the post-processing.
  93951. */
  93952. postSolve: function () {
  93953. OIMO.Error("Constraint", "Inheritance error.");
  93954. }
  93955. }
  93956. /**
  93957. * Joints are used to constrain the motion between two rigid bodies.
  93958. * @author saharan
  93959. * @author lo-th
  93960. */
  93961. OIMO.Joint = function (config) {
  93962. OIMO.Constraint.call(this);
  93963. // joint name
  93964. this.name = "";
  93965. // The type of the joint.
  93966. this.type = OIMO.JOINT_NULL;
  93967. // The previous joint in the world.
  93968. this.prev = null;
  93969. // The next joint in the world.
  93970. this.next = null;
  93971. this.body1 = config.body1;
  93972. this.body2 = config.body2;
  93973. // The anchor point on the first rigid body in local coordinate system.
  93974. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  93975. // The anchor point on the second rigid body in local coordinate system.
  93976. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  93977. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  93978. this.relativeAnchorPoint1 = new OIMO.Vec3();
  93979. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  93980. this.relativeAnchorPoint2 = new OIMO.Vec3();
  93981. // The anchor point on the first rigid body in world coordinate system.
  93982. this.anchorPoint1 = new OIMO.Vec3();
  93983. // The anchor point on the second rigid body in world coordinate system.
  93984. this.anchorPoint2 = new OIMO.Vec3();
  93985. // Whether allow collision between connected rigid bodies or not.
  93986. this.allowCollision = config.allowCollision;
  93987. this.b1Link = new OIMO.JointLink(this);
  93988. this.b2Link = new OIMO.JointLink(this);
  93989. this.matrix = new OIMO.Mat44();
  93990. };
  93991. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  93992. OIMO.Joint.prototype.constructor = OIMO.Joint;
  93993. // Update all the anchor points.
  93994. OIMO.Joint.prototype.updateAnchorPoints = function () {
  93995. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  93996. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  93997. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  93998. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  93999. };
  94000. // Attach the joint from the bodies.
  94001. OIMO.Joint.prototype.attach = function () {
  94002. this.b1Link.body = this.body2;
  94003. this.b2Link.body = this.body1;
  94004. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  94005. else this.b1Link.next = null;
  94006. this.body1.jointLink = this.b1Link;
  94007. this.body1.numJoints++;
  94008. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  94009. else this.b2Link.next = null;
  94010. this.body2.jointLink = this.b2Link;
  94011. this.body2.numJoints++;
  94012. };
  94013. // Detach the joint from the bodies.
  94014. OIMO.Joint.prototype.detach = function () {
  94015. var prev = this.b1Link.prev;
  94016. var next = this.b1Link.next;
  94017. if (prev != null) prev.next = next;
  94018. if (next != null) next.prev = prev;
  94019. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  94020. this.b1Link.prev = null;
  94021. this.b1Link.next = null;
  94022. this.b1Link.body = null;
  94023. this.body1.numJoints--;
  94024. prev = this.b2Link.prev;
  94025. next = this.b2Link.next;
  94026. if (prev != null) prev.next = next;
  94027. if (next != null) next.prev = prev;
  94028. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  94029. this.b2Link.prev = null;
  94030. this.b2Link.next = null;
  94031. this.b2Link.body = null;
  94032. this.body2.numJoints--;
  94033. this.b1Link.body = null;
  94034. this.b2Link.body = null;
  94035. };
  94036. // Awake the bodies.
  94037. OIMO.Joint.prototype.awake = function () {
  94038. this.body1.awake();
  94039. this.body2.awake();
  94040. };
  94041. // calculation function
  94042. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  94043. };
  94044. OIMO.Joint.prototype.solve = function () {
  94045. };
  94046. OIMO.Joint.prototype.postSolve = function () {
  94047. };
  94048. // Delete process
  94049. OIMO.Joint.prototype.remove = function () {
  94050. this.dispose();
  94051. };
  94052. OIMO.Joint.prototype.dispose = function () {
  94053. this.parent.removeJoint(this);
  94054. };
  94055. // Three js add
  94056. OIMO.Joint.prototype.getPosition = function () {
  94057. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  94058. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  94059. return [p1, p2];
  94060. };
  94061. OIMO.Joint.prototype.getMatrix = function () {
  94062. var m = this.matrix.elements;
  94063. var p1 = this.anchorPoint1;
  94064. var p2 = this.anchorPoint2;
  94065. m[0] = p1.x * OIMO.WORLD_SCALE;
  94066. m[1] = p1.y * OIMO.WORLD_SCALE;
  94067. m[2] = p1.z * OIMO.WORLD_SCALE;
  94068. m[3] = 0;
  94069. m[4] = p2.x * OIMO.WORLD_SCALE;
  94070. m[5] = p2.y * OIMO.WORLD_SCALE;
  94071. m[6] = p2.z * OIMO.WORLD_SCALE;
  94072. m[7] = 0;
  94073. return m;
  94074. };
  94075. /**
  94076. * A joint configuration holds all configuration data for constructing a joint.
  94077. * Joint configurations can be reused safely.
  94078. * @author saharan
  94079. */
  94080. OIMO.JointConfig = function () {
  94081. // The first rigid body of the joint.
  94082. this.body1 = null;
  94083. // The second rigid body of the joint.
  94084. this.body2 = null;
  94085. // The anchor point on the first rigid body in local coordinate system.
  94086. this.localAnchorPoint1 = new OIMO.Vec3();
  94087. // The anchor point on the second rigid body in local coordinate system.
  94088. this.localAnchorPoint2 = new OIMO.Vec3();
  94089. // The axis in the first body's coordinate system.
  94090. // his property is available in some joints.
  94091. this.localAxis1 = new OIMO.Vec3();
  94092. // The axis in the second body's coordinate system.
  94093. // This property is available in some joints.
  94094. this.localAxis2 = new OIMO.Vec3();
  94095. // Whether allow collision between connected rigid bodies or not.
  94096. this.allowCollision = false;
  94097. };
  94098. /**
  94099. * A link list of joints.
  94100. * @author saharan
  94101. */
  94102. OIMO.JointLink = function (joint) {
  94103. // The previous joint link.
  94104. this.prev = null;
  94105. // The next joint link.
  94106. this.next = null;
  94107. // The other rigid body connected to the joint.
  94108. this.body = null;
  94109. // The joint of the link.
  94110. this.joint = joint;
  94111. };
  94112. /**
  94113. * An information of limit and motor.
  94114. * @author saharan
  94115. */
  94116. OIMO.LimitMotor = function (axis, fixed) {
  94117. fixed = fixed || false;
  94118. // The axis of the constraint.
  94119. this.axis = axis;
  94120. // The current angle for rotational constraints.
  94121. this.angle = 0;
  94122. // The lower limit. Set lower > upper to disable
  94123. this.lowerLimit = fixed ? 0 : 1;
  94124. //if(fixed)this.lowerLimit = 0;
  94125. //else this.lowerLimit = 1;
  94126. // The upper limit. Set lower > upper to disable.
  94127. this.upperLimit = 0;
  94128. // The target motor speed.
  94129. this.motorSpeed = 0;
  94130. // The maximum motor force or torque. Set 0 to disable.
  94131. this.maxMotorForce = 0;
  94132. // The frequency of the spring. Set 0 to disable.
  94133. this.frequency = 0;
  94134. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  94135. this.dampingRatio = 0;
  94136. };
  94137. OIMO.LimitMotor.prototype = {
  94138. constructor: OIMO.LimitMotor,
  94139. /**
  94140. * Set limit data into this constraint.
  94141. * @param lowerLimit
  94142. * @param upperLimit
  94143. */
  94144. setLimit: function (lowerLimit, upperLimit) {
  94145. this.lowerLimit = lowerLimit;
  94146. this.upperLimit = upperLimit;
  94147. },
  94148. /**
  94149. * Set motor data into this constraint.
  94150. * @param motorSpeed
  94151. * @param maxMotorForce
  94152. */
  94153. setMotor: function (motorSpeed, maxMotorForce) {
  94154. this.motorSpeed = motorSpeed;
  94155. this.maxMotorForce = maxMotorForce;
  94156. },
  94157. /**
  94158. * Set spring data into this constraint.
  94159. * @param frequency
  94160. * @param dampingRatio
  94161. */
  94162. setSpring: function (frequency, dampingRatio) {
  94163. this.frequency = frequency;
  94164. this.dampingRatio = dampingRatio;
  94165. }
  94166. };
  94167. /**
  94168. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  94169. * @author saharan
  94170. * @author lo-th
  94171. */
  94172. OIMO.BallAndSocketJoint = function (config) {
  94173. OIMO.Joint.call(this, config);
  94174. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  94175. this.lc = new OIMO.LinearConstraint(this);
  94176. };
  94177. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  94178. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  94179. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94180. this.updateAnchorPoints();
  94181. this.lc.preSolve(timeStep, invTimeStep);
  94182. };
  94183. OIMO.BallAndSocketJoint.prototype.solve = function () {
  94184. this.lc.solve();
  94185. };
  94186. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  94187. };
  94188. /**
  94189. * A distance joint limits the distance between two anchor points on rigid bodies.
  94190. * @author saharan
  94191. * @author lo-th
  94192. */
  94193. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  94194. OIMO.Joint.call(this, config);
  94195. this.type = OIMO.JOINT_DISTANCE;
  94196. this.normal = new OIMO.Vec3();
  94197. this.nr = new OIMO.Vec3();
  94198. // The limit and motor information of the joint.
  94199. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  94200. this.limitMotor.lowerLimit = minDistance;
  94201. this.limitMotor.upperLimit = maxDistance;
  94202. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  94203. };
  94204. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  94205. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  94206. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94207. this.updateAnchorPoints();
  94208. //var nr = this.nr;
  94209. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  94210. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  94211. //if(len>0) len = 1/len;
  94212. //this.normal.scale( nr, len );
  94213. this.normal.normalize(this.nr);
  94214. this.t.preSolve(timeStep, invTimeStep);
  94215. };
  94216. OIMO.DistanceJoint.prototype.solve = function () {
  94217. this.t.solve();
  94218. };
  94219. OIMO.DistanceJoint.prototype.postSolve = function () {
  94220. };
  94221. /**
  94222. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  94223. * @author saharan
  94224. * @author lo-th
  94225. */
  94226. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  94227. OIMO.Joint.call(this, config);
  94228. this.type = OIMO.JOINT_HINGE;
  94229. // The axis in the first body's coordinate system.
  94230. this.localAxis1 = config.localAxis1.clone().norm();
  94231. // The axis in the second body's coordinate system.
  94232. this.localAxis2 = config.localAxis2.clone().norm();
  94233. // make angle axis 1
  94234. this.localAngle1 = new OIMO.Vec3(
  94235. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  94236. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  94237. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  94238. ).norm();
  94239. // make angle axis 2
  94240. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94241. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  94242. this.nor = new OIMO.Vec3();
  94243. this.tan = new OIMO.Vec3();
  94244. this.bin = new OIMO.Vec3();
  94245. this.ax1 = new OIMO.Vec3();
  94246. this.ax2 = new OIMO.Vec3();
  94247. this.an1 = new OIMO.Vec3();
  94248. this.an2 = new OIMO.Vec3();
  94249. // The rotational limit and motor information of the joint.
  94250. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  94251. this.limitMotor.lowerLimit = lowerAngleLimit;
  94252. this.limitMotor.upperLimit = upperAngleLimit;
  94253. this.lc = new OIMO.LinearConstraint(this);
  94254. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94255. };
  94256. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  94257. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  94258. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94259. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  94260. this.updateAnchorPoints();
  94261. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  94262. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  94263. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  94264. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  94265. this.nor.set(
  94266. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  94267. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  94268. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  94269. ).norm();
  94270. this.tan.set(
  94271. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  94272. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  94273. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  94274. ).norm();
  94275. this.bin.set(
  94276. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  94277. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  94278. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  94279. );
  94280. // calculate hinge angle
  94281. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  94282. if (
  94283. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  94284. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  94285. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  94286. ) {
  94287. this.limitMotor.angle = -limite;
  94288. } else {
  94289. this.limitMotor.angle = limite;
  94290. }
  94291. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  94292. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  94293. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  94294. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  94295. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  94296. this.r3.preSolve(timeStep, invTimeStep);
  94297. this.lc.preSolve(timeStep, invTimeStep);
  94298. };
  94299. OIMO.HingeJoint.prototype.solve = function () {
  94300. this.r3.solve();
  94301. this.lc.solve();
  94302. };
  94303. OIMO.HingeJoint.prototype.postSolve = function () {
  94304. };
  94305. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  94306. if (cos > 1) return 0;
  94307. else if (cos < -1) return OIMO.PI;
  94308. else return OIMO.acos(cos);
  94309. };
  94310. /**
  94311. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  94312. * @author saharan
  94313. * @author lo-th
  94314. */
  94315. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  94316. OIMO.Joint.call(this, config);
  94317. this.type = OIMO.JOINT_PRISMATIC;
  94318. // The axis in the first body's coordinate system.
  94319. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94320. // The axis in the second body's coordinate system.
  94321. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94322. this.localAxis1X = this.localAxis1.x;
  94323. this.localAxis1Y = this.localAxis1.y;
  94324. this.localAxis1Z = this.localAxis1.z;
  94325. this.localAxis2X = this.localAxis2.x;
  94326. this.localAxis2Y = this.localAxis2.y;
  94327. this.localAxis2Z = this.localAxis2.z;
  94328. this.nor = new OIMO.Vec3();
  94329. this.tan = new OIMO.Vec3();
  94330. this.bin = new OIMO.Vec3();
  94331. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94332. // The translational limit and motor information of the joint.
  94333. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  94334. this.limitMotor.lowerLimit = lowerTranslation;
  94335. this.limitMotor.upperLimit = upperTranslation;
  94336. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94337. };
  94338. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  94339. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  94340. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94341. var tmpM;
  94342. var tmp1X;
  94343. var tmp1Y;
  94344. var tmp1Z;
  94345. this.updateAnchorPoints();
  94346. tmpM = this.body1.rotation.elements;
  94347. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94348. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94349. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94350. tmpM = this.body2.rotation.elements;
  94351. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94352. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94353. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94354. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  94355. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  94356. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  94357. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94358. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94359. nx *= tmp1X;
  94360. ny *= tmp1X;
  94361. nz *= tmp1X;
  94362. var tx = ny * nx - nz * nz;
  94363. var ty = -nz * ny - nx * nx;
  94364. var tz = nx * nz + ny * ny;
  94365. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94366. tx *= tmp1X;
  94367. ty *= tmp1X;
  94368. tz *= tmp1X;
  94369. var bx = ny * tz - nz * ty;
  94370. var by = nz * tx - nx * tz;
  94371. var bz = nx * ty - ny * tx;
  94372. this.nor.init(nx, ny, nz);
  94373. this.tan.init(tx, ty, tz);
  94374. this.bin.init(bx, by, bz);
  94375. this.ac.preSolve(timeStep, invTimeStep);
  94376. this.t3.preSolve(timeStep, invTimeStep);
  94377. };
  94378. OIMO.PrismaticJoint.prototype.solve = function () {
  94379. this.ac.solve();
  94380. this.t3.solve();
  94381. };
  94382. OIMO.PrismaticJoint.prototype.postSolve = function () {
  94383. };
  94384. /**
  94385. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  94386. * @author saharan
  94387. * @author lo-th
  94388. */
  94389. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  94390. OIMO.Joint.call(this, config);
  94391. this.type = OIMO.JOINT_SLIDER;
  94392. // The first axis in local coordinate system.
  94393. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94394. // The second axis in local coordinate system.
  94395. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94396. var len;
  94397. this.localAxis1X = this.localAxis1.x;
  94398. this.localAxis1Y = this.localAxis1.y;
  94399. this.localAxis1Z = this.localAxis1.z;
  94400. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  94401. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  94402. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  94403. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94404. this.localAngAxis1X *= len;
  94405. this.localAngAxis1Y *= len;
  94406. this.localAngAxis1Z *= len;
  94407. this.localAxis2X = this.localAxis2.x;
  94408. this.localAxis2Y = this.localAxis2.y;
  94409. this.localAxis2Z = this.localAxis2.z;
  94410. // make angle axis 2
  94411. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94412. var tarc = arc.elements;
  94413. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  94414. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  94415. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  94416. this.nor = new OIMO.Vec3();
  94417. this.tan = new OIMO.Vec3();
  94418. this.bin = new OIMO.Vec3();
  94419. // The limit and motor for the rotation
  94420. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  94421. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94422. // The limit and motor for the translation.
  94423. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  94424. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  94425. this.translationalLimitMotor.upperLimit = upperTranslation;
  94426. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94427. };
  94428. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  94429. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  94430. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94431. var tmpM;
  94432. var tmp1X;
  94433. var tmp1Y;
  94434. var tmp1Z;
  94435. this.updateAnchorPoints();
  94436. tmpM = this.body1.rotation.elements;
  94437. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94438. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94439. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94440. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  94441. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  94442. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  94443. tmpM = this.body2.rotation.elements;
  94444. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94445. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94446. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94447. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  94448. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  94449. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  94450. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  94451. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  94452. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  94453. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94454. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94455. nx *= tmp1X;
  94456. ny *= tmp1X;
  94457. nz *= tmp1X;
  94458. var tx = ny * nx - nz * nz;
  94459. var ty = -nz * ny - nx * nx;
  94460. var tz = nx * nz + ny * ny;
  94461. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94462. tx *= tmp1X;
  94463. ty *= tmp1X;
  94464. tz *= tmp1X;
  94465. var bx = ny * tz - nz * ty;
  94466. var by = nz * tx - nx * tz;
  94467. var bz = nx * ty - ny * tx;
  94468. this.nor.init(nx, ny, nz);
  94469. this.tan.init(tx, ty, tz);
  94470. this.bin.init(bx, by, bz);
  94471. // ----------------------------------------------
  94472. // calculate hinge angle
  94473. // ----------------------------------------------
  94474. if (
  94475. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  94476. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  94477. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  94478. ) {
  94479. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  94480. } else {
  94481. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  94482. }
  94483. // angular error
  94484. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  94485. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  94486. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  94487. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  94488. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  94489. this.r3.preSolve(timeStep, invTimeStep);
  94490. this.t3.preSolve(timeStep, invTimeStep);
  94491. };
  94492. OIMO.SliderJoint.prototype.solve = function () {
  94493. this.r3.solve();
  94494. this.t3.solve();
  94495. };
  94496. OIMO.SliderJoint.prototype.postSolve = function () {
  94497. };
  94498. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  94499. if (cos > 1) return 0;
  94500. else if (cos < -1) return OIMO.PI;
  94501. else return OIMO.acos(cos);
  94502. };
  94503. /**
  94504. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  94505. * The wheel joint also allows for relative translation for the suspension.
  94506. * @author saharan
  94507. * @author lo-th
  94508. */
  94509. OIMO.WheelJoint = function (config) {
  94510. OIMO.Joint.call(this, config);
  94511. this.type = OIMO.JOINT_WHEEL;
  94512. // The first axis in local coordinate system.
  94513. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94514. // The second axis in local coordinate system.
  94515. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94516. var len;
  94517. this.localAxis1X = this.localAxis1.x;
  94518. this.localAxis1Y = this.localAxis1.y;
  94519. this.localAxis1Z = this.localAxis1.z;
  94520. this.localAxis2X = this.localAxis2.x;
  94521. this.localAxis2Y = this.localAxis2.y;
  94522. this.localAxis2Z = this.localAxis2.z;
  94523. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  94524. if (dot > -1 && dot < 1) {
  94525. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  94526. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  94527. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  94528. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  94529. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  94530. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  94531. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94532. this.localAngAxis1X *= len;
  94533. this.localAngAxis1Y *= len;
  94534. this.localAngAxis1Z *= len;
  94535. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  94536. this.localAngAxis2X *= len;
  94537. this.localAngAxis2Y *= len;
  94538. this.localAngAxis2Z *= len;
  94539. } else {
  94540. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  94541. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  94542. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  94543. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94544. this.localAngAxis1X *= len;
  94545. this.localAngAxis1Y *= len;
  94546. this.localAngAxis1Z *= len;
  94547. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94548. var tarc = arc.elements;
  94549. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  94550. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  94551. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  94552. }
  94553. this.nor = new OIMO.Vec3();
  94554. this.tan = new OIMO.Vec3();
  94555. this.bin = new OIMO.Vec3();
  94556. // The translational limit and motor information of the joint.
  94557. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  94558. this.translationalLimitMotor.frequency = 8;
  94559. this.translationalLimitMotor.dampingRatio = 1;
  94560. // The first rotational limit and motor information of the joint.
  94561. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  94562. // The second rotational limit and motor information of the joint.
  94563. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  94564. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  94565. this.t3.weight = 1;
  94566. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  94567. };
  94568. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  94569. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  94570. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94571. var tmpM;
  94572. var tmp1X;
  94573. var tmp1Y;
  94574. var tmp1Z;
  94575. this.updateAnchorPoints();
  94576. tmpM = this.body1.rotation.elements;
  94577. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94578. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94579. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94580. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  94581. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  94582. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  94583. tmpM = this.body2.rotation.elements;
  94584. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94585. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94586. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94587. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  94588. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  94589. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  94590. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  94591. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  94592. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  94593. } else {
  94594. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  94595. }
  94596. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  94597. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  94598. } else {
  94599. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  94600. }
  94601. var nx = y2 * z1 - z2 * y1;
  94602. var ny = z2 * x1 - x2 * z1;
  94603. var nz = x2 * y1 - y2 * x1;
  94604. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94605. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94606. nx *= tmp1X;
  94607. ny *= tmp1X;
  94608. nz *= tmp1X;
  94609. var tx = ny * z2 - nz * y2;
  94610. var ty = nz * x2 - nx * z2;
  94611. var tz = nx * y2 - ny * x2;
  94612. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94613. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94614. tx *= tmp1X;
  94615. ty *= tmp1X;
  94616. tz *= tmp1X;
  94617. var bx = y1 * nz - z1 * ny;
  94618. var by = z1 * nx - x1 * nz;
  94619. var bz = x1 * ny - y1 * nx;
  94620. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  94621. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94622. bx *= tmp1X;
  94623. by *= tmp1X;
  94624. bz *= tmp1X;
  94625. this.nor.init(nx, ny, nz);
  94626. this.tan.init(tx, ty, tz);
  94627. this.bin.init(bx, by, bz);
  94628. this.r3.preSolve(timeStep, invTimeStep);
  94629. this.t3.preSolve(timeStep, invTimeStep);
  94630. };
  94631. OIMO.WheelJoint.prototype.solve = function () {
  94632. this.r3.solve();
  94633. this.t3.solve();
  94634. };
  94635. OIMO.WheelJoint.prototype.postSolve = function () {
  94636. };
  94637. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  94638. if (cos > 1) return 0;
  94639. else if (cos < -1) return OIMO.PI;
  94640. else return OIMO.acos(cos);
  94641. };
  94642. /**
  94643. * An angular constraint for all axes for various joints.
  94644. * @author saharan
  94645. */
  94646. OIMO.AngularConstraint = function (joint, targetOrientation) {
  94647. this.joint = joint;
  94648. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  94649. this.relativeOrientation = new OIMO.Quat();
  94650. this.ii1 = null;
  94651. this.ii2 = null;
  94652. this.dd = null;
  94653. this.vel = new OIMO.Vec3();
  94654. this.imp = new OIMO.Vec3();
  94655. this.rn0 = new OIMO.Vec3();
  94656. this.rn1 = new OIMO.Vec3();
  94657. this.rn2 = new OIMO.Vec3();
  94658. this.b1 = joint.body1;
  94659. this.b2 = joint.body2;
  94660. this.a1 = this.b1.angularVelocity;
  94661. this.a2 = this.b2.angularVelocity;
  94662. this.i1 = this.b1.inverseInertia;
  94663. this.i2 = this.b2.inverseInertia;
  94664. };
  94665. OIMO.AngularConstraint.prototype = {
  94666. constructor: OIMO.AngularConstraint,
  94667. preSolve: function (timeStep, invTimeStep) {
  94668. var inv, len, v, vv;
  94669. this.ii1 = this.i1.clone();
  94670. this.ii2 = this.i2.clone();
  94671. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  94672. 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]));
  94673. this.dd = new OIMO.Mat33(
  94674. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  94675. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  94676. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  94677. ).multiply(inv);
  94678. this.relativeOrientation.invert(this.b1.orientation);
  94679. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  94680. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  94681. inv = this.relativeOrientation.s * 2;
  94682. this.vel.scale(this.relativeOrientation, inv);
  94683. len = this.vel.length();
  94684. if (len > 0.02) {
  94685. len = (0.02 - len) / len * invTimeStep * 0.05;
  94686. this.vel.scaleEqual(len);
  94687. } else {
  94688. this.vel.init();
  94689. }
  94690. this.rn1.mulMat(this.ii1, this.imp);
  94691. this.rn2.mulMat(this.ii2, this.imp);
  94692. this.a1.addEqual(this.rn1);
  94693. this.a2.subEqual(this.rn2);
  94694. },
  94695. solve: function () {
  94696. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  94697. this.rn0.mulMat(this.dd, r);
  94698. this.rn1.mulMat(this.ii1, this.rn0);
  94699. this.rn2.mulMat(this.ii2, this.rn0);
  94700. this.imp.addEqual(this.rn0);
  94701. this.a1.addEqual(this.rn1);
  94702. this.a2.subEqual(this.rn2);
  94703. }
  94704. };
  94705. /**
  94706. * A linear constraint for all axes for various joints.
  94707. * @author saharan
  94708. */
  94709. OIMO.LinearConstraint = function (joint) {
  94710. this.m1 = NaN;
  94711. this.m2 = NaN;
  94712. this.ii1 = null;
  94713. this.ii2 = null;
  94714. this.dd = null;
  94715. this.r1x = NaN;
  94716. this.r1y = NaN;
  94717. this.r1z = NaN;
  94718. this.r2x = NaN;
  94719. this.r2y = NaN;
  94720. this.r2z = NaN;
  94721. this.ax1x = NaN;
  94722. this.ax1y = NaN;
  94723. this.ax1z = NaN;
  94724. this.ay1x = NaN;
  94725. this.ay1y = NaN;
  94726. this.ay1z = NaN;
  94727. this.az1x = NaN;
  94728. this.az1y = NaN;
  94729. this.az1z = NaN;
  94730. this.ax2x = NaN;
  94731. this.ax2y = NaN;
  94732. this.ax2z = NaN;
  94733. this.ay2x = NaN;
  94734. this.ay2y = NaN;
  94735. this.ay2z = NaN;
  94736. this.az2x = NaN;
  94737. this.az2y = NaN;
  94738. this.az2z = NaN;
  94739. this.vel = NaN;
  94740. this.velx = NaN;
  94741. this.vely = NaN;
  94742. this.velz = NaN;
  94743. this.joint = joint;
  94744. this.r1 = joint.relativeAnchorPoint1;
  94745. this.r2 = joint.relativeAnchorPoint2;
  94746. this.p1 = joint.anchorPoint1;
  94747. this.p2 = joint.anchorPoint2;
  94748. this.b1 = joint.body1;
  94749. this.b2 = joint.body2;
  94750. this.l1 = this.b1.linearVelocity;
  94751. this.l2 = this.b2.linearVelocity;
  94752. this.a1 = this.b1.angularVelocity;
  94753. this.a2 = this.b2.angularVelocity;
  94754. this.i1 = this.b1.inverseInertia;
  94755. this.i2 = this.b2.inverseInertia;
  94756. this.impx = 0;
  94757. this.impy = 0;
  94758. this.impz = 0;
  94759. }
  94760. OIMO.LinearConstraint.prototype = {
  94761. constructor: OIMO.LinearConstraint,
  94762. preSolve: function (timeStep, invTimeStep) {
  94763. this.r1x = this.r1.x;
  94764. this.r1y = this.r1.y;
  94765. this.r1z = this.r1.z;
  94766. this.r2x = this.r2.x;
  94767. this.r2y = this.r2.y;
  94768. this.r2z = this.r2.z;
  94769. this.m1 = this.b1.inverseMass;
  94770. this.m2 = this.b2.inverseMass;
  94771. this.ii1 = this.i1.clone();
  94772. this.ii2 = this.i2.clone();
  94773. var ii1 = this.ii1.elements;
  94774. var ii2 = this.ii2.elements;
  94775. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  94776. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  94777. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  94778. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  94779. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  94780. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  94781. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  94782. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  94783. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  94784. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  94785. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  94786. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  94787. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  94788. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  94789. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  94790. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  94791. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  94792. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  94793. // calculate point-to-point mass matrix
  94794. // from impulse equation
  94795. //
  94796. // M = ([/m] - [r^][/I][r^]) ^ -1
  94797. //
  94798. // where
  94799. //
  94800. // [/m] = |1/m, 0, 0|
  94801. // |0, 1/m, 0|
  94802. // |0, 0, 1/m|
  94803. //
  94804. // [r^] = |0, -rz, ry|
  94805. // |rz, 0, -rx|
  94806. // |-ry, rx, 0|
  94807. //
  94808. // [/I] = Inverted moment inertia
  94809. var rxx = this.m1 + this.m2;
  94810. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  94811. var k = kk.elements;
  94812. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  94813. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  94814. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  94815. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  94816. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  94817. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  94818. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  94819. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  94820. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  94821. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  94822. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  94823. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  94824. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  94825. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  94826. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  94827. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  94828. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  94829. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  94830. 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]));
  94831. this.dd = new OIMO.Mat33(
  94832. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  94833. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  94834. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  94835. ).multiply(inv);
  94836. this.velx = this.p2.x - this.p1.x;
  94837. this.vely = this.p2.y - this.p1.y;
  94838. this.velz = this.p2.z - this.p1.z;
  94839. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  94840. if (len > 0.005) {
  94841. len = (0.005 - len) / len * invTimeStep * 0.05;
  94842. this.velx *= len;
  94843. this.vely *= len;
  94844. this.velz *= len;
  94845. } else {
  94846. this.velx = 0;
  94847. this.vely = 0;
  94848. this.velz = 0;
  94849. }
  94850. this.impx *= 0.95;
  94851. this.impy *= 0.95;
  94852. this.impz *= 0.95;
  94853. this.l1.x += this.impx * this.m1;
  94854. this.l1.y += this.impy * this.m1;
  94855. this.l1.z += this.impz * this.m1;
  94856. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  94857. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  94858. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  94859. this.l2.x -= this.impx * this.m2;
  94860. this.l2.y -= this.impy * this.m2;
  94861. this.l2.z -= this.impz * this.m2;
  94862. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  94863. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  94864. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  94865. },
  94866. solve: function () {
  94867. var d = this.dd.elements;
  94868. 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;
  94869. 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;
  94870. 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;
  94871. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  94872. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  94873. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  94874. this.impx += nimpx;
  94875. this.impy += nimpy;
  94876. this.impz += nimpz;
  94877. this.l1.x += nimpx * this.m1;
  94878. this.l1.y += nimpy * this.m1;
  94879. this.l1.z += nimpz * this.m1;
  94880. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  94881. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  94882. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  94883. this.l2.x -= nimpx * this.m2;
  94884. this.l2.y -= nimpy * this.m2;
  94885. this.l2.z -= nimpz * this.m2;
  94886. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  94887. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  94888. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  94889. }
  94890. }
  94891. /**
  94892. * A three-axis rotational constraint for various joints.
  94893. * @author saharan
  94894. */
  94895. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  94896. this.cfm1 = NaN;
  94897. this.cfm2 = NaN;
  94898. this.cfm3 = NaN;
  94899. this.i1e00 = NaN;
  94900. this.i1e01 = NaN;
  94901. this.i1e02 = NaN;
  94902. this.i1e10 = NaN;
  94903. this.i1e11 = NaN;
  94904. this.i1e12 = NaN;
  94905. this.i1e20 = NaN;
  94906. this.i1e21 = NaN;
  94907. this.i1e22 = NaN;
  94908. this.i2e00 = NaN;
  94909. this.i2e01 = NaN;
  94910. this.i2e02 = NaN;
  94911. this.i2e10 = NaN;
  94912. this.i2e11 = NaN;
  94913. this.i2e12 = NaN;
  94914. this.i2e20 = NaN;
  94915. this.i2e21 = NaN;
  94916. this.i2e22 = NaN;
  94917. this.ax1 = NaN;
  94918. this.ay1 = NaN;
  94919. this.az1 = NaN;
  94920. this.ax2 = NaN;
  94921. this.ay2 = NaN;
  94922. this.az2 = NaN;
  94923. this.ax3 = NaN;
  94924. this.ay3 = NaN;
  94925. this.az3 = NaN;
  94926. this.a1x1 = NaN; // jacoians
  94927. this.a1y1 = NaN;
  94928. this.a1z1 = NaN;
  94929. this.a2x1 = NaN;
  94930. this.a2y1 = NaN;
  94931. this.a2z1 = NaN;
  94932. this.a1x2 = NaN;
  94933. this.a1y2 = NaN;
  94934. this.a1z2 = NaN;
  94935. this.a2x2 = NaN;
  94936. this.a2y2 = NaN;
  94937. this.a2z2 = NaN;
  94938. this.a1x3 = NaN;
  94939. this.a1y3 = NaN;
  94940. this.a1z3 = NaN;
  94941. this.a2x3 = NaN;
  94942. this.a2y3 = NaN;
  94943. this.a2z3 = NaN;
  94944. this.lowerLimit1 = NaN;
  94945. this.upperLimit1 = NaN;
  94946. this.limitVelocity1 = NaN;
  94947. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94948. this.enableMotor1 = false;
  94949. this.motorSpeed1 = NaN;
  94950. this.maxMotorForce1 = NaN;
  94951. this.maxMotorImpulse1 = NaN;
  94952. this.lowerLimit2 = NaN;
  94953. this.upperLimit2 = NaN;
  94954. this.limitVelocity2 = NaN;
  94955. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94956. this.enableMotor2 = false;
  94957. this.motorSpeed2 = NaN;
  94958. this.maxMotorForce2 = NaN;
  94959. this.maxMotorImpulse2 = NaN;
  94960. this.lowerLimit3 = NaN;
  94961. this.upperLimit3 = NaN;
  94962. this.limitVelocity3 = NaN;
  94963. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94964. this.enableMotor3 = false;
  94965. this.motorSpeed3 = NaN;
  94966. this.maxMotorForce3 = NaN;
  94967. this.maxMotorImpulse3 = NaN;
  94968. this.k00 = NaN; // K = J*M*JT
  94969. this.k01 = NaN;
  94970. this.k02 = NaN;
  94971. this.k10 = NaN;
  94972. this.k11 = NaN;
  94973. this.k12 = NaN;
  94974. this.k20 = NaN;
  94975. this.k21 = NaN;
  94976. this.k22 = NaN;
  94977. this.kv00 = NaN; // diagonals without CFMs
  94978. this.kv11 = NaN;
  94979. this.kv22 = NaN;
  94980. this.dv00 = NaN; // ...inverted
  94981. this.dv11 = NaN;
  94982. this.dv22 = NaN;
  94983. this.d00 = NaN; // K^-1
  94984. this.d01 = NaN;
  94985. this.d02 = NaN;
  94986. this.d10 = NaN;
  94987. this.d11 = NaN;
  94988. this.d12 = NaN;
  94989. this.d20 = NaN;
  94990. this.d21 = NaN;
  94991. this.d22 = NaN;
  94992. this.limitMotor1 = limitMotor1;
  94993. this.limitMotor2 = limitMotor2;
  94994. this.limitMotor3 = limitMotor3;
  94995. this.b1 = joint.body1;
  94996. this.b2 = joint.body2;
  94997. this.a1 = this.b1.angularVelocity;
  94998. this.a2 = this.b2.angularVelocity;
  94999. this.i1 = this.b1.inverseInertia;
  95000. this.i2 = this.b2.inverseInertia;
  95001. this.limitImpulse1 = 0;
  95002. this.motorImpulse1 = 0;
  95003. this.limitImpulse2 = 0;
  95004. this.motorImpulse2 = 0;
  95005. this.limitImpulse3 = 0;
  95006. this.motorImpulse3 = 0;
  95007. }
  95008. OIMO.Rotational3Constraint.prototype = {
  95009. constructor: OIMO.Rotational3Constraint,
  95010. preSolve: function (timeStep, invTimeStep) {
  95011. this.ax1 = this.limitMotor1.axis.x;
  95012. this.ay1 = this.limitMotor1.axis.y;
  95013. this.az1 = this.limitMotor1.axis.z;
  95014. this.ax2 = this.limitMotor2.axis.x;
  95015. this.ay2 = this.limitMotor2.axis.y;
  95016. this.az2 = this.limitMotor2.axis.z;
  95017. this.ax3 = this.limitMotor3.axis.x;
  95018. this.ay3 = this.limitMotor3.axis.y;
  95019. this.az3 = this.limitMotor3.axis.z;
  95020. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  95021. this.upperLimit1 = this.limitMotor1.upperLimit;
  95022. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  95023. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  95024. this.enableMotor1 = this.maxMotorForce1 > 0;
  95025. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  95026. this.upperLimit2 = this.limitMotor2.upperLimit;
  95027. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  95028. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  95029. this.enableMotor2 = this.maxMotorForce2 > 0;
  95030. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  95031. this.upperLimit3 = this.limitMotor3.upperLimit;
  95032. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  95033. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  95034. this.enableMotor3 = this.maxMotorForce3 > 0;
  95035. var ti1 = this.i1.elements;
  95036. var ti2 = this.i2.elements;
  95037. this.i1e00 = ti1[0];
  95038. this.i1e01 = ti1[1];
  95039. this.i1e02 = ti1[2];
  95040. this.i1e10 = ti1[3];
  95041. this.i1e11 = ti1[4];
  95042. this.i1e12 = ti1[5];
  95043. this.i1e20 = ti1[6];
  95044. this.i1e21 = ti1[7];
  95045. this.i1e22 = ti1[8];
  95046. this.i2e00 = ti2[0];
  95047. this.i2e01 = ti2[1];
  95048. this.i2e02 = ti2[2];
  95049. this.i2e10 = ti2[3];
  95050. this.i2e11 = ti2[4];
  95051. this.i2e12 = ti2[5];
  95052. this.i2e20 = ti2[6];
  95053. this.i2e21 = ti2[7];
  95054. this.i2e22 = ti2[8];
  95055. var frequency1 = this.limitMotor1.frequency;
  95056. var frequency2 = this.limitMotor2.frequency;
  95057. var frequency3 = this.limitMotor3.frequency;
  95058. var enableSpring1 = frequency1 > 0;
  95059. var enableSpring2 = frequency2 > 0;
  95060. var enableSpring3 = frequency3 > 0;
  95061. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  95062. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  95063. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  95064. var angle1 = this.limitMotor1.angle;
  95065. if (enableLimit1) {
  95066. if (this.lowerLimit1 == this.upperLimit1) {
  95067. if (this.limitState1 != 0) {
  95068. this.limitState1 = 0;
  95069. this.limitImpulse1 = 0;
  95070. }
  95071. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95072. } else if (angle1 < this.lowerLimit1) {
  95073. if (this.limitState1 != -1) {
  95074. this.limitState1 = -1;
  95075. this.limitImpulse1 = 0;
  95076. }
  95077. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95078. } else if (angle1 > this.upperLimit1) {
  95079. if (this.limitState1 != 1) {
  95080. this.limitState1 = 1;
  95081. this.limitImpulse1 = 0;
  95082. }
  95083. this.limitVelocity1 = this.upperLimit1 - angle1;
  95084. } else {
  95085. this.limitState1 = 2;
  95086. this.limitImpulse1 = 0;
  95087. this.limitVelocity1 = 0;
  95088. }
  95089. if (!enableSpring1) {
  95090. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  95091. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  95092. else this.limitVelocity1 = 0;
  95093. }
  95094. } else {
  95095. this.limitState1 = 2;
  95096. this.limitImpulse1 = 0;
  95097. }
  95098. var angle2 = this.limitMotor2.angle;
  95099. if (enableLimit2) {
  95100. if (this.lowerLimit2 == this.upperLimit2) {
  95101. if (this.limitState2 != 0) {
  95102. this.limitState2 = 0;
  95103. this.limitImpulse2 = 0;
  95104. }
  95105. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95106. } else if (angle2 < this.lowerLimit2) {
  95107. if (this.limitState2 != -1) {
  95108. this.limitState2 = -1;
  95109. this.limitImpulse2 = 0;
  95110. }
  95111. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95112. } else if (angle2 > this.upperLimit2) {
  95113. if (this.limitState2 != 1) {
  95114. this.limitState2 = 1;
  95115. this.limitImpulse2 = 0;
  95116. }
  95117. this.limitVelocity2 = this.upperLimit2 - angle2;
  95118. } else {
  95119. this.limitState2 = 2;
  95120. this.limitImpulse2 = 0;
  95121. this.limitVelocity2 = 0;
  95122. }
  95123. if (!enableSpring2) {
  95124. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  95125. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  95126. else this.limitVelocity2 = 0;
  95127. }
  95128. } else {
  95129. this.limitState2 = 2;
  95130. this.limitImpulse2 = 0;
  95131. }
  95132. var angle3 = this.limitMotor3.angle;
  95133. if (enableLimit3) {
  95134. if (this.lowerLimit3 == this.upperLimit3) {
  95135. if (this.limitState3 != 0) {
  95136. this.limitState3 = 0;
  95137. this.limitImpulse3 = 0;
  95138. }
  95139. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95140. } else if (angle3 < this.lowerLimit3) {
  95141. if (this.limitState3 != -1) {
  95142. this.limitState3 = -1;
  95143. this.limitImpulse3 = 0;
  95144. }
  95145. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95146. } else if (angle3 > this.upperLimit3) {
  95147. if (this.limitState3 != 1) {
  95148. this.limitState3 = 1;
  95149. this.limitImpulse3 = 0;
  95150. }
  95151. this.limitVelocity3 = this.upperLimit3 - angle3;
  95152. } else {
  95153. this.limitState3 = 2;
  95154. this.limitImpulse3 = 0;
  95155. this.limitVelocity3 = 0;
  95156. }
  95157. if (!enableSpring3) {
  95158. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  95159. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  95160. else this.limitVelocity3 = 0;
  95161. }
  95162. } else {
  95163. this.limitState3 = 2;
  95164. this.limitImpulse3 = 0;
  95165. }
  95166. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  95167. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  95168. } else {
  95169. this.motorImpulse1 = 0;
  95170. this.maxMotorImpulse1 = 0;
  95171. }
  95172. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  95173. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  95174. } else {
  95175. this.motorImpulse2 = 0;
  95176. this.maxMotorImpulse2 = 0;
  95177. }
  95178. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  95179. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  95180. } else {
  95181. this.motorImpulse3 = 0;
  95182. this.maxMotorImpulse3 = 0;
  95183. }
  95184. // build jacobians
  95185. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  95186. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  95187. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  95188. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  95189. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  95190. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  95191. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  95192. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  95193. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  95194. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  95195. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  95196. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  95197. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  95198. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  95199. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  95200. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  95201. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  95202. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  95203. // build an impulse matrix
  95204. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  95205. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  95206. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  95207. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  95208. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  95209. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  95210. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  95211. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  95212. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  95213. this.kv00 = this.k00;
  95214. this.kv11 = this.k11;
  95215. this.kv22 = this.k22;
  95216. this.dv00 = 1 / this.kv00;
  95217. this.dv11 = 1 / this.kv11;
  95218. this.dv22 = 1 / this.kv22;
  95219. if (enableSpring1 && this.limitState1 != 2) {
  95220. var omega = 6.2831853 * frequency1;
  95221. var k = omega * omega * timeStep;
  95222. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  95223. this.cfm1 = this.kv00 * dmp;
  95224. this.limitVelocity1 *= k * dmp;
  95225. } else {
  95226. this.cfm1 = 0;
  95227. this.limitVelocity1 *= invTimeStep * 0.05;
  95228. }
  95229. if (enableSpring2 && this.limitState2 != 2) {
  95230. omega = 6.2831853 * frequency2;
  95231. k = omega * omega * timeStep;
  95232. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  95233. this.cfm2 = this.kv11 * dmp;
  95234. this.limitVelocity2 *= k * dmp;
  95235. } else {
  95236. this.cfm2 = 0;
  95237. this.limitVelocity2 *= invTimeStep * 0.05;
  95238. }
  95239. if (enableSpring3 && this.limitState3 != 2) {
  95240. omega = 6.2831853 * frequency3;
  95241. k = omega * omega * timeStep;
  95242. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  95243. this.cfm3 = this.kv22 * dmp;
  95244. this.limitVelocity3 *= k * dmp;
  95245. } else {
  95246. this.cfm3 = 0;
  95247. this.limitVelocity3 *= invTimeStep * 0.05;
  95248. }
  95249. this.k00 += this.cfm1;
  95250. this.k11 += this.cfm2;
  95251. this.k22 += this.cfm3;
  95252. var inv = 1 / (
  95253. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  95254. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  95255. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  95256. );
  95257. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  95258. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  95259. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  95260. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  95261. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  95262. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  95263. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  95264. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  95265. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  95266. this.limitImpulse1 *= 0.95;
  95267. this.motorImpulse1 *= 0.95;
  95268. this.limitImpulse2 *= 0.95;
  95269. this.motorImpulse2 *= 0.95;
  95270. this.limitImpulse3 *= 0.95;
  95271. this.motorImpulse3 *= 0.95;
  95272. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  95273. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  95274. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  95275. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  95276. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  95277. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  95278. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  95279. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  95280. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  95281. },
  95282. solve_: function () {
  95283. var rvx = this.a2.x - this.a1.x;
  95284. var rvy = this.a2.y - this.a1.y;
  95285. var rvz = this.a2.z - this.a1.z;
  95286. this.limitVelocity3 = 30;
  95287. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  95288. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  95289. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  95290. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95291. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95292. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95293. this.limitImpulse1 += dLimitImpulse1;
  95294. this.limitImpulse2 += dLimitImpulse2;
  95295. this.limitImpulse3 += dLimitImpulse3;
  95296. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  95297. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  95298. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  95299. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  95300. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  95301. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  95302. },
  95303. solve: function () {
  95304. var rvx = this.a2.x - this.a1.x;
  95305. var rvy = this.a2.y - this.a1.y;
  95306. var rvz = this.a2.z - this.a1.z;
  95307. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  95308. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95309. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  95310. var oldMotorImpulse1 = this.motorImpulse1;
  95311. var oldMotorImpulse2 = this.motorImpulse2;
  95312. var oldMotorImpulse3 = this.motorImpulse3;
  95313. var dMotorImpulse1 = 0;
  95314. var dMotorImpulse2 = 0;
  95315. var dMotorImpulse3 = 0;
  95316. if (this.enableMotor1) {
  95317. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  95318. this.motorImpulse1 += dMotorImpulse1;
  95319. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  95320. this.motorImpulse1 = this.maxMotorImpulse1;
  95321. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  95322. this.motorImpulse1 = -this.maxMotorImpulse1;
  95323. }
  95324. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  95325. }
  95326. if (this.enableMotor2) {
  95327. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  95328. this.motorImpulse2 += dMotorImpulse2;
  95329. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  95330. this.motorImpulse2 = this.maxMotorImpulse2;
  95331. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  95332. this.motorImpulse2 = -this.maxMotorImpulse2;
  95333. }
  95334. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  95335. }
  95336. if (this.enableMotor3) {
  95337. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  95338. this.motorImpulse3 += dMotorImpulse3;
  95339. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  95340. this.motorImpulse3 = this.maxMotorImpulse3;
  95341. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  95342. this.motorImpulse3 = -this.maxMotorImpulse3;
  95343. }
  95344. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  95345. }
  95346. // apply motor impulse to relative velocity
  95347. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  95348. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  95349. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  95350. // subtract target velocity and applied impulse
  95351. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  95352. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  95353. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  95354. var oldLimitImpulse1 = this.limitImpulse1;
  95355. var oldLimitImpulse2 = this.limitImpulse2;
  95356. var oldLimitImpulse3 = this.limitImpulse3;
  95357. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95358. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95359. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95360. this.limitImpulse1 += dLimitImpulse1;
  95361. this.limitImpulse2 += dLimitImpulse2;
  95362. this.limitImpulse3 += dLimitImpulse3;
  95363. // clamp
  95364. var clampState = 0;
  95365. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  95366. dLimitImpulse1 = -oldLimitImpulse1;
  95367. rvn2 += dLimitImpulse1 * this.k10;
  95368. rvn3 += dLimitImpulse1 * this.k20;
  95369. clampState |= 1;
  95370. }
  95371. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  95372. dLimitImpulse2 = -oldLimitImpulse2;
  95373. rvn1 += dLimitImpulse2 * this.k01;
  95374. rvn3 += dLimitImpulse2 * this.k21;
  95375. clampState |= 2;
  95376. }
  95377. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  95378. dLimitImpulse3 = -oldLimitImpulse3;
  95379. rvn1 += dLimitImpulse3 * this.k02;
  95380. rvn2 += dLimitImpulse3 * this.k12;
  95381. clampState |= 4;
  95382. }
  95383. // update un-clamped impulse
  95384. // TODO: isolate division
  95385. var det;
  95386. switch (clampState) {
  95387. case 1: // update 2 3
  95388. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  95389. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  95390. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  95391. break;
  95392. case 2: // update 1 3
  95393. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  95394. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  95395. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  95396. break;
  95397. case 3: // update 3
  95398. dLimitImpulse3 = rvn3 / this.k22;
  95399. break;
  95400. case 4: // update 1 2
  95401. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  95402. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  95403. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  95404. break;
  95405. case 5: // update 2
  95406. dLimitImpulse2 = rvn2 / this.k11;
  95407. break;
  95408. case 6: // update 1
  95409. dLimitImpulse1 = rvn1 / this.k00;
  95410. break;
  95411. }
  95412. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  95413. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  95414. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  95415. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  95416. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  95417. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  95418. // apply impulse
  95419. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  95420. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  95421. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  95422. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  95423. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  95424. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  95425. rvx = this.a2.x - this.a1.x;
  95426. rvy = this.a2.y - this.a1.y;
  95427. rvz = this.a2.z - this.a1.z;
  95428. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95429. }
  95430. }
  95431. /**
  95432. * A rotational constraint for various joints.
  95433. * @author saharan
  95434. */
  95435. OIMO.RotationalConstraint = function (joint, limitMotor) {
  95436. this.cfm = NaN;
  95437. this.i1e00 = NaN;
  95438. this.i1e01 = NaN;
  95439. this.i1e02 = NaN;
  95440. this.i1e10 = NaN;
  95441. this.i1e11 = NaN;
  95442. this.i1e12 = NaN;
  95443. this.i1e20 = NaN;
  95444. this.i1e21 = NaN;
  95445. this.i1e22 = NaN;
  95446. this.i2e00 = NaN;
  95447. this.i2e01 = NaN;
  95448. this.i2e02 = NaN;
  95449. this.i2e10 = NaN;
  95450. this.i2e11 = NaN;
  95451. this.i2e12 = NaN;
  95452. this.i2e20 = NaN;
  95453. this.i2e21 = NaN;
  95454. this.i2e22 = NaN;
  95455. this.motorDenom = NaN;
  95456. this.invMotorDenom = NaN;
  95457. this.invDenom = NaN;
  95458. this.ax = NaN;
  95459. this.ay = NaN;
  95460. this.az = NaN;
  95461. this.a1x = NaN;
  95462. this.a1y = NaN;
  95463. this.a1z = NaN;
  95464. this.a2x = NaN;
  95465. this.a2y = NaN;
  95466. this.a2z = NaN;
  95467. this.enableLimit = false;
  95468. this.lowerLimit = NaN;
  95469. this.upperLimit = NaN;
  95470. this.limitVelocity = NaN;
  95471. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95472. this.enableMotor = false;
  95473. this.motorSpeed = NaN;
  95474. this.maxMotorForce = NaN;
  95475. this.maxMotorImpulse = NaN;
  95476. this.limitMotor = limitMotor;
  95477. this.b1 = joint.body1;
  95478. this.b2 = joint.body2;
  95479. this.a1 = this.b1.angularVelocity;
  95480. this.a2 = this.b2.angularVelocity;
  95481. this.i1 = this.b1.inverseInertia;
  95482. this.i2 = this.b2.inverseInertia;
  95483. this.limitImpulse = 0;
  95484. this.motorImpulse = 0;
  95485. }
  95486. OIMO.RotationalConstraint.prototype = {
  95487. constructor: OIMO.RotationalConstraint,
  95488. preSolve: function (timeStep, invTimeStep) {
  95489. this.ax = this.limitMotor.axis.x;
  95490. this.ay = this.limitMotor.axis.y;
  95491. this.az = this.limitMotor.axis.z;
  95492. this.lowerLimit = this.limitMotor.lowerLimit;
  95493. this.upperLimit = this.limitMotor.upperLimit;
  95494. this.motorSpeed = this.limitMotor.motorSpeed;
  95495. this.maxMotorForce = this.limitMotor.maxMotorForce;
  95496. this.enableMotor = this.maxMotorForce > 0;
  95497. var ti1 = this.i1.elements;
  95498. var ti2 = this.i2.elements;
  95499. this.i1e00 = ti1[0];
  95500. this.i1e01 = ti1[1];
  95501. this.i1e02 = ti1[2];
  95502. this.i1e10 = ti1[3];
  95503. this.i1e11 = ti1[4];
  95504. this.i1e12 = ti1[5];
  95505. this.i1e20 = ti1[6];
  95506. this.i1e21 = ti1[7];
  95507. this.i1e22 = ti1[8];
  95508. this.i2e00 = ti2[0];
  95509. this.i2e01 = ti2[1];
  95510. this.i2e02 = ti2[2];
  95511. this.i2e10 = ti2[3];
  95512. this.i2e11 = ti2[4];
  95513. this.i2e12 = ti2[5];
  95514. this.i2e20 = ti2[6];
  95515. this.i2e21 = ti2[7];
  95516. this.i2e22 = ti2[8];
  95517. var frequency = this.limitMotor.frequency;
  95518. var enableSpring = frequency > 0;
  95519. var enableLimit = this.lowerLimit <= this.upperLimit;
  95520. var angle = this.limitMotor.angle;
  95521. if (enableLimit) {
  95522. if (this.lowerLimit == this.upperLimit) {
  95523. if (this.limitState != 0) {
  95524. this.limitState = 0;
  95525. this.limitImpulse = 0;
  95526. }
  95527. this.limitVelocity = this.lowerLimit - angle;
  95528. } else if (angle < this.lowerLimit) {
  95529. if (this.limitState != -1) {
  95530. this.limitState = -1;
  95531. this.limitImpulse = 0;
  95532. }
  95533. this.limitVelocity = this.lowerLimit - angle;
  95534. } else if (angle > this.upperLimit) {
  95535. if (this.limitState != 1) {
  95536. this.limitState = 1;
  95537. this.limitImpulse = 0;
  95538. }
  95539. this.limitVelocity = this.upperLimit - angle;
  95540. } else {
  95541. this.limitState = 2;
  95542. this.limitImpulse = 0;
  95543. this.limitVelocity = 0;
  95544. }
  95545. if (!enableSpring) {
  95546. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  95547. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  95548. else this.limitVelocity = 0;
  95549. }
  95550. } else {
  95551. this.limitState = 2;
  95552. this.limitImpulse = 0;
  95553. }
  95554. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  95555. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  95556. } else {
  95557. this.motorImpulse = 0;
  95558. this.maxMotorImpulse = 0;
  95559. }
  95560. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  95561. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  95562. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  95563. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  95564. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  95565. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  95566. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  95567. this.invMotorDenom = 1 / this.motorDenom;
  95568. if (enableSpring && this.limitState != 2) {
  95569. var omega = 6.2831853 * frequency;
  95570. var k = omega * omega * timeStep;
  95571. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  95572. this.cfm = this.motorDenom * dmp;
  95573. this.limitVelocity *= k * dmp;
  95574. } else {
  95575. this.cfm = 0;
  95576. this.limitVelocity *= invTimeStep * 0.05;
  95577. }
  95578. this.invDenom = 1 / (this.motorDenom + this.cfm);
  95579. this.limitImpulse *= 0.95;
  95580. this.motorImpulse *= 0.95;
  95581. var totalImpulse = this.limitImpulse + this.motorImpulse;
  95582. this.a1.x += totalImpulse * this.a1x;
  95583. this.a1.y += totalImpulse * this.a1y;
  95584. this.a1.z += totalImpulse * this.a1z;
  95585. this.a2.x -= totalImpulse * this.a2x;
  95586. this.a2.y -= totalImpulse * this.a2y;
  95587. this.a2.z -= totalImpulse * this.a2z;
  95588. },
  95589. solve: function () {
  95590. 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);
  95591. // motor part
  95592. var newMotorImpulse;
  95593. if (this.enableMotor) {
  95594. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  95595. var oldMotorImpulse = this.motorImpulse;
  95596. this.motorImpulse += newMotorImpulse;
  95597. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  95598. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  95599. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  95600. rvn -= newMotorImpulse * this.motorDenom;
  95601. } else newMotorImpulse = 0;
  95602. // limit part
  95603. var newLimitImpulse;
  95604. if (this.limitState != 2) {
  95605. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  95606. var oldLimitImpulse = this.limitImpulse;
  95607. this.limitImpulse += newLimitImpulse;
  95608. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  95609. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  95610. } else newLimitImpulse = 0;
  95611. var totalImpulse = newLimitImpulse + newMotorImpulse;
  95612. this.a1.x += totalImpulse * this.a1x;
  95613. this.a1.y += totalImpulse * this.a1y;
  95614. this.a1.z += totalImpulse * this.a1z;
  95615. this.a2.x -= totalImpulse * this.a2x;
  95616. this.a2.y -= totalImpulse * this.a2y;
  95617. this.a2.z -= totalImpulse * this.a2z;
  95618. }
  95619. }
  95620. /**
  95621. * A three-axis translational constraint for various joints.
  95622. * @author saharan
  95623. */
  95624. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95625. this.m1 = NaN;
  95626. this.m2 = NaN;
  95627. this.i1e00 = NaN;
  95628. this.i1e01 = NaN;
  95629. this.i1e02 = NaN;
  95630. this.i1e10 = NaN;
  95631. this.i1e11 = NaN;
  95632. this.i1e12 = NaN;
  95633. this.i1e20 = NaN;
  95634. this.i1e21 = NaN;
  95635. this.i1e22 = NaN;
  95636. this.i2e00 = NaN;
  95637. this.i2e01 = NaN;
  95638. this.i2e02 = NaN;
  95639. this.i2e10 = NaN;
  95640. this.i2e11 = NaN;
  95641. this.i2e12 = NaN;
  95642. this.i2e20 = NaN;
  95643. this.i2e21 = NaN;
  95644. this.i2e22 = NaN;
  95645. this.ax1 = NaN;
  95646. this.ay1 = NaN;
  95647. this.az1 = NaN;
  95648. this.ax2 = NaN;
  95649. this.ay2 = NaN;
  95650. this.az2 = NaN;
  95651. this.ax3 = NaN;
  95652. this.ay3 = NaN;
  95653. this.az3 = NaN;
  95654. this.r1x = NaN;
  95655. this.r1y = NaN;
  95656. this.r1z = NaN;
  95657. this.r2x = NaN;
  95658. this.r2y = NaN;
  95659. this.r2z = NaN;
  95660. this.t1x1 = NaN;// jacobians
  95661. this.t1y1 = NaN;
  95662. this.t1z1 = NaN;
  95663. this.t2x1 = NaN;
  95664. this.t2y1 = NaN;
  95665. this.t2z1 = NaN;
  95666. this.l1x1 = NaN;
  95667. this.l1y1 = NaN;
  95668. this.l1z1 = NaN;
  95669. this.l2x1 = NaN;
  95670. this.l2y1 = NaN;
  95671. this.l2z1 = NaN;
  95672. this.a1x1 = NaN;
  95673. this.a1y1 = NaN;
  95674. this.a1z1 = NaN;
  95675. this.a2x1 = NaN;
  95676. this.a2y1 = NaN;
  95677. this.a2z1 = NaN;
  95678. this.t1x2 = NaN;
  95679. this.t1y2 = NaN;
  95680. this.t1z2 = NaN;
  95681. this.t2x2 = NaN;
  95682. this.t2y2 = NaN;
  95683. this.t2z2 = NaN;
  95684. this.l1x2 = NaN;
  95685. this.l1y2 = NaN;
  95686. this.l1z2 = NaN;
  95687. this.l2x2 = NaN;
  95688. this.l2y2 = NaN;
  95689. this.l2z2 = NaN;
  95690. this.a1x2 = NaN;
  95691. this.a1y2 = NaN;
  95692. this.a1z2 = NaN;
  95693. this.a2x2 = NaN;
  95694. this.a2y2 = NaN;
  95695. this.a2z2 = NaN;
  95696. this.t1x3 = NaN;
  95697. this.t1y3 = NaN;
  95698. this.t1z3 = NaN;
  95699. this.t2x3 = NaN;
  95700. this.t2y3 = NaN;
  95701. this.t2z3 = NaN;
  95702. this.l1x3 = NaN;
  95703. this.l1y3 = NaN;
  95704. this.l1z3 = NaN;
  95705. this.l2x3 = NaN;
  95706. this.l2y3 = NaN;
  95707. this.l2z3 = NaN;
  95708. this.a1x3 = NaN;
  95709. this.a1y3 = NaN;
  95710. this.a1z3 = NaN;
  95711. this.a2x3 = NaN;
  95712. this.a2y3 = NaN;
  95713. this.a2z3 = NaN;
  95714. this.lowerLimit1 = NaN;
  95715. this.upperLimit1 = NaN;
  95716. this.limitVelocity1 = NaN;
  95717. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95718. this.enableMotor1 = false;
  95719. this.motorSpeed1 = NaN;
  95720. this.maxMotorForce1 = NaN;
  95721. this.maxMotorImpulse1 = NaN;
  95722. this.lowerLimit2 = NaN;
  95723. this.upperLimit2 = NaN;
  95724. this.limitVelocity2 = NaN;
  95725. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95726. this.enableMotor2 = false;
  95727. this.motorSpeed2 = NaN;
  95728. this.maxMotorForce2 = NaN;
  95729. this.maxMotorImpulse2 = NaN;
  95730. this.lowerLimit3 = NaN;
  95731. this.upperLimit3 = NaN;
  95732. this.limitVelocity3 = NaN;
  95733. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95734. this.enableMotor3 = false;
  95735. this.motorSpeed3 = NaN;
  95736. this.maxMotorForce3 = NaN;
  95737. this.maxMotorImpulse3 = NaN;
  95738. this.k00 = NaN; // K = J*M*JT
  95739. this.k01 = NaN;
  95740. this.k02 = NaN;
  95741. this.k10 = NaN;
  95742. this.k11 = NaN;
  95743. this.k12 = NaN;
  95744. this.k20 = NaN;
  95745. this.k21 = NaN;
  95746. this.k22 = NaN;
  95747. this.kv00 = NaN; // diagonals without CFMs
  95748. this.kv11 = NaN;
  95749. this.kv22 = NaN;
  95750. this.dv00 = NaN; // ...inverted
  95751. this.dv11 = NaN;
  95752. this.dv22 = NaN;
  95753. this.d00 = NaN; // K^-1
  95754. this.d01 = NaN;
  95755. this.d02 = NaN;
  95756. this.d10 = NaN;
  95757. this.d11 = NaN;
  95758. this.d12 = NaN;
  95759. this.d20 = NaN;
  95760. this.d21 = NaN;
  95761. this.d22 = NaN;
  95762. this.limitMotor1 = limitMotor1;
  95763. this.limitMotor2 = limitMotor2;
  95764. this.limitMotor3 = limitMotor3;
  95765. this.b1 = joint.body1;
  95766. this.b2 = joint.body2;
  95767. this.p1 = joint.anchorPoint1;
  95768. this.p2 = joint.anchorPoint2;
  95769. this.r1 = joint.relativeAnchorPoint1;
  95770. this.r2 = joint.relativeAnchorPoint2;
  95771. this.l1 = this.b1.linearVelocity;
  95772. this.l2 = this.b2.linearVelocity;
  95773. this.a1 = this.b1.angularVelocity;
  95774. this.a2 = this.b2.angularVelocity;
  95775. this.i1 = this.b1.inverseInertia;
  95776. this.i2 = this.b2.inverseInertia;
  95777. this.limitImpulse1 = 0;
  95778. this.motorImpulse1 = 0;
  95779. this.limitImpulse2 = 0;
  95780. this.motorImpulse2 = 0;
  95781. this.limitImpulse3 = 0;
  95782. this.motorImpulse3 = 0;
  95783. this.cfm1 = 0;// Constraint Force Mixing
  95784. this.cfm2 = 0;
  95785. this.cfm3 = 0;
  95786. this.weight = -1;
  95787. }
  95788. OIMO.Translational3Constraint.prototype = {
  95789. constructor: OIMO.Translational3Constraint,
  95790. preSolve: function (timeStep, invTimeStep) {
  95791. this.ax1 = this.limitMotor1.axis.x;
  95792. this.ay1 = this.limitMotor1.axis.y;
  95793. this.az1 = this.limitMotor1.axis.z;
  95794. this.ax2 = this.limitMotor2.axis.x;
  95795. this.ay2 = this.limitMotor2.axis.y;
  95796. this.az2 = this.limitMotor2.axis.z;
  95797. this.ax3 = this.limitMotor3.axis.x;
  95798. this.ay3 = this.limitMotor3.axis.y;
  95799. this.az3 = this.limitMotor3.axis.z;
  95800. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  95801. this.upperLimit1 = this.limitMotor1.upperLimit;
  95802. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  95803. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  95804. this.enableMotor1 = this.maxMotorForce1 > 0;
  95805. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  95806. this.upperLimit2 = this.limitMotor2.upperLimit;
  95807. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  95808. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  95809. this.enableMotor2 = this.maxMotorForce2 > 0;
  95810. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  95811. this.upperLimit3 = this.limitMotor3.upperLimit;
  95812. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  95813. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  95814. this.enableMotor3 = this.maxMotorForce3 > 0;
  95815. this.m1 = this.b1.inverseMass;
  95816. this.m2 = this.b2.inverseMass;
  95817. var ti1 = this.i1.elements;
  95818. var ti2 = this.i2.elements;
  95819. this.i1e00 = ti1[0];
  95820. this.i1e01 = ti1[1];
  95821. this.i1e02 = ti1[2];
  95822. this.i1e10 = ti1[3];
  95823. this.i1e11 = ti1[4];
  95824. this.i1e12 = ti1[5];
  95825. this.i1e20 = ti1[6];
  95826. this.i1e21 = ti1[7];
  95827. this.i1e22 = ti1[8];
  95828. this.i2e00 = ti2[0];
  95829. this.i2e01 = ti2[1];
  95830. this.i2e02 = ti2[2];
  95831. this.i2e10 = ti2[3];
  95832. this.i2e11 = ti2[4];
  95833. this.i2e12 = ti2[5];
  95834. this.i2e20 = ti2[6];
  95835. this.i2e21 = ti2[7];
  95836. this.i2e22 = ti2[8];
  95837. var dx = this.p2.x - this.p1.x;
  95838. var dy = this.p2.y - this.p1.y;
  95839. var dz = this.p2.z - this.p1.z;
  95840. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  95841. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  95842. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  95843. var frequency1 = this.limitMotor1.frequency;
  95844. var frequency2 = this.limitMotor2.frequency;
  95845. var frequency3 = this.limitMotor3.frequency;
  95846. var enableSpring1 = frequency1 > 0;
  95847. var enableSpring2 = frequency2 > 0;
  95848. var enableSpring3 = frequency3 > 0;
  95849. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  95850. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  95851. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  95852. // for stability
  95853. if (enableSpring1 && d1 > 20 || d1 < -20) {
  95854. enableSpring1 = false;
  95855. }
  95856. if (enableSpring2 && d2 > 20 || d2 < -20) {
  95857. enableSpring2 = false;
  95858. }
  95859. if (enableSpring3 && d3 > 20 || d3 < -20) {
  95860. enableSpring3 = false;
  95861. }
  95862. if (enableLimit1) {
  95863. if (this.lowerLimit1 == this.upperLimit1) {
  95864. if (this.limitState1 != 0) {
  95865. this.limitState1 = 0;
  95866. this.limitImpulse1 = 0;
  95867. }
  95868. this.limitVelocity1 = this.lowerLimit1 - d1;
  95869. if (!enableSpring1) d1 = this.lowerLimit1;
  95870. } else if (d1 < this.lowerLimit1) {
  95871. if (this.limitState1 != -1) {
  95872. this.limitState1 = -1;
  95873. this.limitImpulse1 = 0;
  95874. }
  95875. this.limitVelocity1 = this.lowerLimit1 - d1;
  95876. if (!enableSpring1) d1 = this.lowerLimit1;
  95877. } else if (d1 > this.upperLimit1) {
  95878. if (this.limitState1 != 1) {
  95879. this.limitState1 = 1;
  95880. this.limitImpulse1 = 0;
  95881. }
  95882. this.limitVelocity1 = this.upperLimit1 - d1;
  95883. if (!enableSpring1) d1 = this.upperLimit1;
  95884. } else {
  95885. this.limitState1 = 2;
  95886. this.limitImpulse1 = 0;
  95887. this.limitVelocity1 = 0;
  95888. }
  95889. if (!enableSpring1) {
  95890. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  95891. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  95892. else this.limitVelocity1 = 0;
  95893. }
  95894. } else {
  95895. this.limitState1 = 2;
  95896. this.limitImpulse1 = 0;
  95897. }
  95898. if (enableLimit2) {
  95899. if (this.lowerLimit2 == this.upperLimit2) {
  95900. if (this.limitState2 != 0) {
  95901. this.limitState2 = 0;
  95902. this.limitImpulse2 = 0;
  95903. }
  95904. this.limitVelocity2 = this.lowerLimit2 - d2;
  95905. if (!enableSpring2) d2 = this.lowerLimit2;
  95906. } else if (d2 < this.lowerLimit2) {
  95907. if (this.limitState2 != -1) {
  95908. this.limitState2 = -1;
  95909. this.limitImpulse2 = 0;
  95910. }
  95911. this.limitVelocity2 = this.lowerLimit2 - d2;
  95912. if (!enableSpring2) d2 = this.lowerLimit2;
  95913. } else if (d2 > this.upperLimit2) {
  95914. if (this.limitState2 != 1) {
  95915. this.limitState2 = 1;
  95916. this.limitImpulse2 = 0;
  95917. }
  95918. this.limitVelocity2 = this.upperLimit2 - d2;
  95919. if (!enableSpring2) d2 = this.upperLimit2;
  95920. } else {
  95921. this.limitState2 = 2;
  95922. this.limitImpulse2 = 0;
  95923. this.limitVelocity2 = 0;
  95924. }
  95925. if (!enableSpring2) {
  95926. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  95927. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  95928. else this.limitVelocity2 = 0;
  95929. }
  95930. } else {
  95931. this.limitState2 = 2;
  95932. this.limitImpulse2 = 0;
  95933. }
  95934. if (enableLimit3) {
  95935. if (this.lowerLimit3 == this.upperLimit3) {
  95936. if (this.limitState3 != 0) {
  95937. this.limitState3 = 0;
  95938. this.limitImpulse3 = 0;
  95939. }
  95940. this.limitVelocity3 = this.lowerLimit3 - d3;
  95941. if (!enableSpring3) d3 = this.lowerLimit3;
  95942. } else if (d3 < this.lowerLimit3) {
  95943. if (this.limitState3 != -1) {
  95944. this.limitState3 = -1;
  95945. this.limitImpulse3 = 0;
  95946. }
  95947. this.limitVelocity3 = this.lowerLimit3 - d3;
  95948. if (!enableSpring3) d3 = this.lowerLimit3;
  95949. } else if (d3 > this.upperLimit3) {
  95950. if (this.limitState3 != 1) {
  95951. this.limitState3 = 1;
  95952. this.limitImpulse3 = 0;
  95953. }
  95954. this.limitVelocity3 = this.upperLimit3 - d3;
  95955. if (!enableSpring3) d3 = this.upperLimit3;
  95956. } else {
  95957. this.limitState3 = 2;
  95958. this.limitImpulse3 = 0;
  95959. this.limitVelocity3 = 0;
  95960. }
  95961. if (!enableSpring3) {
  95962. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  95963. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  95964. else this.limitVelocity3 = 0;
  95965. }
  95966. } else {
  95967. this.limitState3 = 2;
  95968. this.limitImpulse3 = 0;
  95969. }
  95970. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  95971. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  95972. } else {
  95973. this.motorImpulse1 = 0;
  95974. this.maxMotorImpulse1 = 0;
  95975. }
  95976. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  95977. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  95978. } else {
  95979. this.motorImpulse2 = 0;
  95980. this.maxMotorImpulse2 = 0;
  95981. }
  95982. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  95983. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  95984. } else {
  95985. this.motorImpulse3 = 0;
  95986. this.maxMotorImpulse3 = 0;
  95987. }
  95988. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  95989. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  95990. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  95991. var w1 = this.m2 / (this.m1 + this.m2);
  95992. if (this.weight >= 0) w1 = this.weight; // use given weight
  95993. var w2 = 1 - w1;
  95994. this.r1x = this.r1.x + rdx * w1;
  95995. this.r1y = this.r1.y + rdy * w1;
  95996. this.r1z = this.r1.z + rdz * w1;
  95997. this.r2x = this.r2.x - rdx * w2;
  95998. this.r2y = this.r2.y - rdy * w2;
  95999. this.r2z = this.r2.z - rdz * w2;
  96000. // build jacobians
  96001. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  96002. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  96003. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  96004. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  96005. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  96006. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  96007. this.l1x1 = this.ax1 * this.m1;
  96008. this.l1y1 = this.ay1 * this.m1;
  96009. this.l1z1 = this.az1 * this.m1;
  96010. this.l2x1 = this.ax1 * this.m2;
  96011. this.l2y1 = this.ay1 * this.m2;
  96012. this.l2z1 = this.az1 * this.m2;
  96013. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  96014. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  96015. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  96016. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  96017. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  96018. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  96019. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  96020. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  96021. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  96022. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  96023. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  96024. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  96025. this.l1x2 = this.ax2 * this.m1;
  96026. this.l1y2 = this.ay2 * this.m1;
  96027. this.l1z2 = this.az2 * this.m1;
  96028. this.l2x2 = this.ax2 * this.m2;
  96029. this.l2y2 = this.ay2 * this.m2;
  96030. this.l2z2 = this.az2 * this.m2;
  96031. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  96032. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  96033. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  96034. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  96035. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  96036. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  96037. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  96038. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  96039. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  96040. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  96041. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  96042. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  96043. this.l1x3 = this.ax3 * this.m1;
  96044. this.l1y3 = this.ay3 * this.m1;
  96045. this.l1z3 = this.az3 * this.m1;
  96046. this.l2x3 = this.ax3 * this.m2;
  96047. this.l2y3 = this.ay3 * this.m2;
  96048. this.l2z3 = this.az3 * this.m2;
  96049. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  96050. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  96051. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  96052. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  96053. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  96054. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  96055. // build an impulse matrix
  96056. var m12 = this.m1 + this.m2;
  96057. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  96058. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  96059. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  96060. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  96061. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  96062. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  96063. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  96064. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  96065. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  96066. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  96067. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  96068. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  96069. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  96070. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  96071. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  96072. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  96073. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  96074. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  96075. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  96076. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  96077. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  96078. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  96079. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  96080. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  96081. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  96082. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  96083. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  96084. this.kv00 = this.k00;
  96085. this.kv11 = this.k11;
  96086. this.kv22 = this.k22;
  96087. this.dv00 = 1 / this.kv00;
  96088. this.dv11 = 1 / this.kv11;
  96089. this.dv22 = 1 / this.kv22;
  96090. if (enableSpring1 && this.limitState1 != 2) {
  96091. var omega = 6.2831853 * frequency1;
  96092. var k = omega * omega * timeStep;
  96093. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96094. this.cfm1 = this.kv00 * dmp;
  96095. this.limitVelocity1 *= k * dmp;
  96096. } else {
  96097. this.cfm1 = 0;
  96098. this.limitVelocity1 *= invTimeStep * 0.05;
  96099. }
  96100. if (enableSpring2 && this.limitState2 != 2) {
  96101. omega = 6.2831853 * frequency2;
  96102. k = omega * omega * timeStep;
  96103. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96104. this.cfm2 = this.kv11 * dmp;
  96105. this.limitVelocity2 *= k * dmp;
  96106. } else {
  96107. this.cfm2 = 0;
  96108. this.limitVelocity2 *= invTimeStep * 0.05;
  96109. }
  96110. if (enableSpring3 && this.limitState3 != 2) {
  96111. omega = 6.2831853 * frequency3;
  96112. k = omega * omega * timeStep;
  96113. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96114. this.cfm3 = this.kv22 * dmp;
  96115. this.limitVelocity3 *= k * dmp;
  96116. } else {
  96117. this.cfm3 = 0;
  96118. this.limitVelocity3 *= invTimeStep * 0.05;
  96119. }
  96120. this.k00 += this.cfm1;
  96121. this.k11 += this.cfm2;
  96122. this.k22 += this.cfm3;
  96123. var inv = 1 / (
  96124. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96125. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96126. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96127. );
  96128. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96129. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96130. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96131. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96132. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96133. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96134. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96135. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96136. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96137. // warm starting
  96138. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96139. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96140. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96141. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  96142. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  96143. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  96144. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96145. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96146. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96147. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  96148. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  96149. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  96150. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96151. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96152. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96153. },
  96154. solve: function () {
  96155. 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;
  96156. 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;
  96157. 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;
  96158. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96159. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96160. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96161. var oldMotorImpulse1 = this.motorImpulse1;
  96162. var oldMotorImpulse2 = this.motorImpulse2;
  96163. var oldMotorImpulse3 = this.motorImpulse3;
  96164. var dMotorImpulse1 = 0;
  96165. var dMotorImpulse2 = 0;
  96166. var dMotorImpulse3 = 0;
  96167. if (this.enableMotor1) {
  96168. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96169. this.motorImpulse1 += dMotorImpulse1;
  96170. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96171. this.motorImpulse1 = this.maxMotorImpulse1;
  96172. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96173. this.motorImpulse1 = -this.maxMotorImpulse1;
  96174. }
  96175. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96176. }
  96177. if (this.enableMotor2) {
  96178. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96179. this.motorImpulse2 += dMotorImpulse2;
  96180. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96181. this.motorImpulse2 = this.maxMotorImpulse2;
  96182. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96183. this.motorImpulse2 = -this.maxMotorImpulse2;
  96184. }
  96185. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96186. }
  96187. if (this.enableMotor3) {
  96188. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96189. this.motorImpulse3 += dMotorImpulse3;
  96190. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96191. this.motorImpulse3 = this.maxMotorImpulse3;
  96192. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96193. this.motorImpulse3 = -this.maxMotorImpulse3;
  96194. }
  96195. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96196. }
  96197. // apply motor impulse to relative velocity
  96198. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96199. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96200. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96201. // subtract target velocity and applied impulse
  96202. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96203. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96204. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96205. var oldLimitImpulse1 = this.limitImpulse1;
  96206. var oldLimitImpulse2 = this.limitImpulse2;
  96207. var oldLimitImpulse3 = this.limitImpulse3;
  96208. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96209. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96210. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96211. this.limitImpulse1 += dLimitImpulse1;
  96212. this.limitImpulse2 += dLimitImpulse2;
  96213. this.limitImpulse3 += dLimitImpulse3;
  96214. // clamp
  96215. var clampState = 0;
  96216. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96217. dLimitImpulse1 = -oldLimitImpulse1;
  96218. rvn2 += dLimitImpulse1 * this.k10;
  96219. rvn3 += dLimitImpulse1 * this.k20;
  96220. clampState |= 1;
  96221. }
  96222. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96223. dLimitImpulse2 = -oldLimitImpulse2;
  96224. rvn1 += dLimitImpulse2 * this.k01;
  96225. rvn3 += dLimitImpulse2 * this.k21;
  96226. clampState |= 2;
  96227. }
  96228. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96229. dLimitImpulse3 = -oldLimitImpulse3;
  96230. rvn1 += dLimitImpulse3 * this.k02;
  96231. rvn2 += dLimitImpulse3 * this.k12;
  96232. clampState |= 4;
  96233. }
  96234. // update un-clamped impulse
  96235. // TODO: isolate division
  96236. var det;
  96237. switch (clampState) {
  96238. case 1:// update 2 3
  96239. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96240. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96241. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96242. break;
  96243. case 2:// update 1 3
  96244. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96245. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96246. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96247. break;
  96248. case 3:// update 3
  96249. dLimitImpulse3 = rvn3 / this.k22;
  96250. break;
  96251. case 4:// update 1 2
  96252. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96253. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96254. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96255. break;
  96256. case 5:// update 2
  96257. dLimitImpulse2 = rvn2 / this.k11;
  96258. break;
  96259. case 6:// update 1
  96260. dLimitImpulse1 = rvn1 / this.k00;
  96261. break;
  96262. }
  96263. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  96264. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  96265. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  96266. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96267. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96268. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96269. // apply impulse
  96270. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  96271. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  96272. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  96273. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96274. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96275. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96276. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  96277. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  96278. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  96279. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96280. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96281. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96282. }
  96283. }
  96284. /**
  96285. * A translational constraint for various joints.
  96286. * @author saharan
  96287. */
  96288. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  96289. this.cfm = NaN;
  96290. this.m1 = NaN;
  96291. this.m2 = NaN;
  96292. this.i1e00 = NaN;
  96293. this.i1e01 = NaN;
  96294. this.i1e02 = NaN;
  96295. this.i1e10 = NaN;
  96296. this.i1e11 = NaN;
  96297. this.i1e12 = NaN;
  96298. this.i1e20 = NaN;
  96299. this.i1e21 = NaN;
  96300. this.i1e22 = NaN;
  96301. this.i2e00 = NaN;
  96302. this.i2e01 = NaN;
  96303. this.i2e02 = NaN;
  96304. this.i2e10 = NaN;
  96305. this.i2e11 = NaN;
  96306. this.i2e12 = NaN;
  96307. this.i2e20 = NaN;
  96308. this.i2e21 = NaN;
  96309. this.i2e22 = NaN;
  96310. this.motorDenom = NaN;
  96311. this.invMotorDenom = NaN;
  96312. this.invDenom = NaN;
  96313. this.ax = NaN;
  96314. this.ay = NaN;
  96315. this.az = NaN;
  96316. this.r1x = NaN;
  96317. this.r1y = NaN;
  96318. this.r1z = NaN;
  96319. this.r2x = NaN;
  96320. this.r2y = NaN;
  96321. this.r2z = NaN;
  96322. this.t1x = NaN;
  96323. this.t1y = NaN;
  96324. this.t1z = NaN;
  96325. this.t2x = NaN;
  96326. this.t2y = NaN;
  96327. this.t2z = NaN;
  96328. this.l1x = NaN;
  96329. this.l1y = NaN;
  96330. this.l1z = NaN;
  96331. this.l2x = NaN;
  96332. this.l2y = NaN;
  96333. this.l2z = NaN;
  96334. this.a1x = NaN;
  96335. this.a1y = NaN;
  96336. this.a1z = NaN;
  96337. this.a2x = NaN;
  96338. this.a2y = NaN;
  96339. this.a2z = NaN;
  96340. this.lowerLimit = NaN;
  96341. this.upperLimit = NaN;
  96342. this.limitVelocity = NaN;
  96343. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96344. this.enableMotor = false;
  96345. this.motorSpeed = NaN;
  96346. this.maxMotorForce = NaN;
  96347. this.maxMotorImpulse = NaN;
  96348. this.limitMotor = limitMotor;
  96349. this.b1 = joint.body1;
  96350. this.b2 = joint.body2;
  96351. this.p1 = joint.anchorPoint1;
  96352. this.p2 = joint.anchorPoint2;
  96353. this.r1 = joint.relativeAnchorPoint1;
  96354. this.r2 = joint.relativeAnchorPoint2;
  96355. this.l1 = this.b1.linearVelocity;
  96356. this.l2 = this.b2.linearVelocity;
  96357. this.a1 = this.b1.angularVelocity;
  96358. this.a2 = this.b2.angularVelocity;
  96359. this.i1 = this.b1.inverseInertia;
  96360. this.i2 = this.b2.inverseInertia;
  96361. this.limitImpulse = 0;
  96362. this.motorImpulse = 0;
  96363. }
  96364. OIMO.TranslationalConstraint.prototype = {
  96365. constructor: OIMO.TranslationalConstraint,
  96366. preSolve: function (timeStep, invTimeStep) {
  96367. this.ax = this.limitMotor.axis.x;
  96368. this.ay = this.limitMotor.axis.y;
  96369. this.az = this.limitMotor.axis.z;
  96370. this.lowerLimit = this.limitMotor.lowerLimit;
  96371. this.upperLimit = this.limitMotor.upperLimit;
  96372. this.motorSpeed = this.limitMotor.motorSpeed;
  96373. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96374. this.enableMotor = this.maxMotorForce > 0;
  96375. this.m1 = this.b1.inverseMass;
  96376. this.m2 = this.b2.inverseMass;
  96377. var ti1 = this.i1.elements;
  96378. var ti2 = this.i2.elements;
  96379. this.i1e00 = ti1[0];
  96380. this.i1e01 = ti1[1];
  96381. this.i1e02 = ti1[2];
  96382. this.i1e10 = ti1[3];
  96383. this.i1e11 = ti1[4];
  96384. this.i1e12 = ti1[5];
  96385. this.i1e20 = ti1[6];
  96386. this.i1e21 = ti1[7];
  96387. this.i1e22 = ti1[8];
  96388. this.i2e00 = ti2[0];
  96389. this.i2e01 = ti2[1];
  96390. this.i2e02 = ti2[2];
  96391. this.i2e10 = ti2[3];
  96392. this.i2e11 = ti2[4];
  96393. this.i2e12 = ti2[5];
  96394. this.i2e20 = ti2[6];
  96395. this.i2e21 = ti2[7];
  96396. this.i2e22 = ti2[8];
  96397. var dx = this.p2.x - this.p1.x;
  96398. var dy = this.p2.y - this.p1.y;
  96399. var dz = this.p2.z - this.p1.z;
  96400. var d = dx * this.ax + dy * this.ay + dz * this.az;
  96401. var frequency = this.limitMotor.frequency;
  96402. var enableSpring = frequency > 0;
  96403. var enableLimit = this.lowerLimit <= this.upperLimit;
  96404. if (enableSpring && d > 20 || d < -20) {
  96405. enableSpring = false;
  96406. }
  96407. if (enableLimit) {
  96408. if (this.lowerLimit == this.upperLimit) {
  96409. if (this.limitState != 0) {
  96410. this.limitState = 0;
  96411. this.limitImpulse = 0;
  96412. }
  96413. this.limitVelocity = this.lowerLimit - d;
  96414. if (!enableSpring) d = this.lowerLimit;
  96415. } else if (d < this.lowerLimit) {
  96416. if (this.limitState != -1) {
  96417. this.limitState = -1;
  96418. this.limitImpulse = 0;
  96419. }
  96420. this.limitVelocity = this.lowerLimit - d;
  96421. if (!enableSpring) d = this.lowerLimit;
  96422. } else if (d > this.upperLimit) {
  96423. if (this.limitState != 1) {
  96424. this.limitState = 1;
  96425. this.limitImpulse = 0;
  96426. }
  96427. this.limitVelocity = this.upperLimit - d;
  96428. if (!enableSpring) d = this.upperLimit;
  96429. } else {
  96430. this.limitState = 2;
  96431. this.limitImpulse = 0;
  96432. this.limitVelocity = 0;
  96433. }
  96434. if (!enableSpring) {
  96435. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  96436. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  96437. else this.limitVelocity = 0;
  96438. }
  96439. } else {
  96440. this.limitState = 2;
  96441. this.limitImpulse = 0;
  96442. }
  96443. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96444. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96445. } else {
  96446. this.motorImpulse = 0;
  96447. this.maxMotorImpulse = 0;
  96448. }
  96449. var rdx = d * this.ax;
  96450. var rdy = d * this.ay;
  96451. var rdz = d * this.az;
  96452. var w1 = this.m1 / (this.m1 + this.m2);
  96453. var w2 = 1 - w1;
  96454. this.r1x = this.r1.x + rdx * w1;
  96455. this.r1y = this.r1.y + rdy * w1;
  96456. this.r1z = this.r1.z + rdz * w1;
  96457. this.r2x = this.r2.x - rdx * w2;
  96458. this.r2y = this.r2.y - rdy * w2;
  96459. this.r2z = this.r2.z - rdz * w2;
  96460. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  96461. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  96462. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  96463. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  96464. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  96465. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  96466. this.l1x = this.ax * this.m1;
  96467. this.l1y = this.ay * this.m1;
  96468. this.l1z = this.az * this.m1;
  96469. this.l2x = this.ax * this.m2;
  96470. this.l2y = this.ay * this.m2;
  96471. this.l2z = this.az * this.m2;
  96472. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  96473. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  96474. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  96475. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  96476. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  96477. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  96478. this.motorDenom =
  96479. this.m1 + this.m2 +
  96480. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  96481. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  96482. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  96483. this.invMotorDenom = 1 / this.motorDenom;
  96484. if (enableSpring && this.limitState != 2) {
  96485. var omega = 6.2831853 * frequency;
  96486. var k = omega * omega * timeStep;
  96487. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96488. this.cfm = this.motorDenom * dmp;
  96489. this.limitVelocity *= k * dmp;
  96490. } else {
  96491. this.cfm = 0;
  96492. this.limitVelocity *= invTimeStep * 0.05;
  96493. }
  96494. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96495. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96496. this.l1.x += totalImpulse * this.l1x;
  96497. this.l1.y += totalImpulse * this.l1y;
  96498. this.l1.z += totalImpulse * this.l1z;
  96499. this.a1.x += totalImpulse * this.a1x;
  96500. this.a1.y += totalImpulse * this.a1y;
  96501. this.a1.z += totalImpulse * this.a1z;
  96502. this.l2.x -= totalImpulse * this.l2x;
  96503. this.l2.y -= totalImpulse * this.l2y;
  96504. this.l2.z -= totalImpulse * this.l2z;
  96505. this.a2.x -= totalImpulse * this.a2x;
  96506. this.a2.y -= totalImpulse * this.a2y;
  96507. this.a2.z -= totalImpulse * this.a2z;
  96508. },
  96509. solve: function () {
  96510. var rvn =
  96511. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  96512. 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;
  96513. // motor part
  96514. var newMotorImpulse;
  96515. if (this.enableMotor) {
  96516. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96517. var oldMotorImpulse = this.motorImpulse;
  96518. this.motorImpulse += newMotorImpulse;
  96519. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96520. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96521. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96522. rvn -= newMotorImpulse * this.motorDenom;
  96523. } else newMotorImpulse = 0;
  96524. // limit part
  96525. var newLimitImpulse;
  96526. if (this.limitState != 2) {
  96527. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96528. var oldLimitImpulse = this.limitImpulse;
  96529. this.limitImpulse += newLimitImpulse;
  96530. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96531. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96532. } else newLimitImpulse = 0;
  96533. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96534. this.l1.x += totalImpulse * this.l1x;
  96535. this.l1.y += totalImpulse * this.l1y;
  96536. this.l1.z += totalImpulse * this.l1z;
  96537. this.a1.x += totalImpulse * this.a1x;
  96538. this.a1.y += totalImpulse * this.a1y;
  96539. this.a1.z += totalImpulse * this.a1z;
  96540. this.l2.x -= totalImpulse * this.l2x;
  96541. this.l2.y -= totalImpulse * this.l2y;
  96542. this.l2.z -= totalImpulse * this.l2z;
  96543. this.a2.x -= totalImpulse * this.a2x;
  96544. this.a2.y -= totalImpulse * this.a2y;
  96545. this.a2.z -= totalImpulse * this.a2z;
  96546. }
  96547. }
  96548. /**
  96549. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  96550. * @author saharan
  96551. */
  96552. OIMO.Contact = function () {
  96553. // The first shape.
  96554. this.shape1 = null;
  96555. // The second shape.
  96556. this.shape2 = null;
  96557. // The first rigid body.
  96558. this.body1 = null;
  96559. // The second rigid body.
  96560. this.body2 = null;
  96561. // The previous contact in the world.
  96562. this.prev = null;
  96563. // The next contact in the world.
  96564. this.next = null;
  96565. // Internal
  96566. this.persisting = false;
  96567. // Whether both the rigid bodies are sleeping or not.
  96568. this.sleeping = false;
  96569. // The collision detector between two shapes.
  96570. this.detector = null;
  96571. // The contact constraint of the contact.
  96572. this.constraint = null;
  96573. // Whether the shapes are touching or not.
  96574. this.touching = false;
  96575. this.b1Link = new OIMO.ContactLink(this);
  96576. this.b2Link = new OIMO.ContactLink(this);
  96577. this.s1Link = new OIMO.ContactLink(this);
  96578. this.s2Link = new OIMO.ContactLink(this);
  96579. // The contact manifold of the contact.
  96580. this.manifold = new OIMO.ContactManifold();
  96581. this.buffer = [];// vector 4
  96582. this.buffer.length = 4;
  96583. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  96584. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  96585. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  96586. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  96587. this.points = this.manifold.points;
  96588. this.constraint = new OIMO.ContactConstraint(this.manifold);
  96589. }
  96590. OIMO.Contact.prototype = {
  96591. constructor: OIMO.Contact,
  96592. mixRestitution: function (restitution1, restitution2) {
  96593. return OIMO.sqrt(restitution1 * restitution2);
  96594. },
  96595. mixFriction: function (friction1, friction2) {
  96596. return OIMO.sqrt(friction1 * friction2);
  96597. },
  96598. /**
  96599. * Update the contact manifold.
  96600. */
  96601. updateManifold: function () {
  96602. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  96603. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  96604. var numBuffers = this.manifold.numPoints;
  96605. var i = numBuffers;
  96606. while (i--) {
  96607. //for(var i=0;i<numBuffers;i++){
  96608. var b = this.buffer[i];
  96609. var p = this.points[i];
  96610. b.lp1X = p.localPoint1.x;
  96611. b.lp1Y = p.localPoint1.y;
  96612. b.lp1Z = p.localPoint1.z;
  96613. b.lp2X = p.localPoint2.x;
  96614. b.lp2Y = p.localPoint2.y;
  96615. b.lp2Z = p.localPoint2.z;
  96616. b.impulse = p.normalImpulse;
  96617. }
  96618. this.manifold.numPoints = 0;
  96619. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  96620. var num = this.manifold.numPoints;
  96621. if (num == 0) {
  96622. this.touching = false;
  96623. return;
  96624. }
  96625. this.touching = true;
  96626. i = num;
  96627. while (i--) {
  96628. //for(i=0; i<num; i++){
  96629. p = this.points[i];
  96630. var lp1x = p.localPoint1.x;
  96631. var lp1y = p.localPoint1.y;
  96632. var lp1z = p.localPoint1.z;
  96633. var lp2x = p.localPoint2.x;
  96634. var lp2y = p.localPoint2.y;
  96635. var lp2z = p.localPoint2.z;
  96636. var index = -1;
  96637. var minDistance = 0.0004;
  96638. var j = numBuffers;
  96639. while (j--) {
  96640. //for(var j=0;j<numBuffers;j++){
  96641. b = this.buffer[j];
  96642. var dx = b.lp1X - lp1x;
  96643. var dy = b.lp1Y - lp1y;
  96644. var dz = b.lp1Z - lp1z;
  96645. var distance1 = dx * dx + dy * dy + dz * dz;
  96646. dx = b.lp2X - lp2x;
  96647. dy = b.lp2Y - lp2y;
  96648. dz = b.lp2Z - lp2z;
  96649. var distance2 = dx * dx + dy * dy + dz * dz;
  96650. if (distance1 < distance2) {
  96651. if (distance1 < minDistance) {
  96652. minDistance = distance1;
  96653. index = j;
  96654. }
  96655. } else {
  96656. if (distance2 < minDistance) {
  96657. minDistance = distance2;
  96658. index = j;
  96659. }
  96660. }
  96661. }
  96662. if (index != -1) {
  96663. var tmp = this.buffer[index];
  96664. this.buffer[index] = this.buffer[--numBuffers];
  96665. this.buffer[numBuffers] = tmp;
  96666. p.normalImpulse = tmp.impulse;
  96667. p.warmStarted = true;
  96668. } else {
  96669. p.normalImpulse = 0;
  96670. p.warmStarted = false;
  96671. }
  96672. }
  96673. },
  96674. /**
  96675. * Attach the contact to the shapes.
  96676. * @param shape1
  96677. * @param shape2
  96678. */
  96679. attach: function (shape1, shape2) {
  96680. this.shape1 = shape1;
  96681. this.shape2 = shape2;
  96682. this.body1 = shape1.parent;
  96683. this.body2 = shape2.parent;
  96684. this.manifold.body1 = this.body1;
  96685. this.manifold.body2 = this.body2;
  96686. this.constraint.body1 = this.body1;
  96687. this.constraint.body2 = this.body2;
  96688. this.constraint.attach();
  96689. this.s1Link.shape = shape2;
  96690. this.s1Link.body = this.body2;
  96691. this.s2Link.shape = shape1;
  96692. this.s2Link.body = this.body1;
  96693. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  96694. else this.s1Link.next = null;
  96695. shape1.contactLink = this.s1Link;
  96696. shape1.numContacts++;
  96697. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  96698. else this.s2Link.next = null;
  96699. shape2.contactLink = this.s2Link;
  96700. shape2.numContacts++;
  96701. this.b1Link.shape = shape2;
  96702. this.b1Link.body = this.body2;
  96703. this.b2Link.shape = shape1;
  96704. this.b2Link.body = this.body1;
  96705. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  96706. else this.b1Link.next = null;
  96707. this.body1.contactLink = this.b1Link;
  96708. this.body1.numContacts++;
  96709. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  96710. else this.b2Link.next = null;
  96711. this.body2.contactLink = this.b2Link;
  96712. this.body2.numContacts++;
  96713. this.prev = null;
  96714. this.next = null;
  96715. this.persisting = true;
  96716. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  96717. this.manifold.numPoints = 0;
  96718. },
  96719. /**
  96720. * Detach the contact from the shapes.
  96721. */
  96722. detach: function () {
  96723. var prev = this.s1Link.prev;
  96724. var next = this.s1Link.next;
  96725. if (prev !== null) prev.next = next;
  96726. if (next !== null) next.prev = prev;
  96727. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  96728. this.s1Link.prev = null;
  96729. this.s1Link.next = null;
  96730. this.s1Link.shape = null;
  96731. this.s1Link.body = null;
  96732. this.shape1.numContacts--;
  96733. prev = this.s2Link.prev;
  96734. next = this.s2Link.next;
  96735. if (prev !== null) prev.next = next;
  96736. if (next !== null) next.prev = prev;
  96737. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  96738. this.s2Link.prev = null;
  96739. this.s2Link.next = null;
  96740. this.s2Link.shape = null;
  96741. this.s2Link.body = null;
  96742. this.shape2.numContacts--;
  96743. prev = this.b1Link.prev;
  96744. next = this.b1Link.next;
  96745. if (prev !== null) prev.next = next;
  96746. if (next !== null) next.prev = prev;
  96747. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  96748. this.b1Link.prev = null;
  96749. this.b1Link.next = null;
  96750. this.b1Link.shape = null;
  96751. this.b1Link.body = null;
  96752. this.body1.numContacts--;
  96753. prev = this.b2Link.prev;
  96754. next = this.b2Link.next;
  96755. if (prev !== null) prev.next = next;
  96756. if (next !== null) next.prev = prev;
  96757. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  96758. this.b2Link.prev = null;
  96759. this.b2Link.next = null;
  96760. this.b2Link.shape = null;
  96761. this.b2Link.body = null;
  96762. this.body2.numContacts--;
  96763. this.manifold.body1 = null;
  96764. this.manifold.body2 = null;
  96765. this.constraint.body1 = null;
  96766. this.constraint.body2 = null;
  96767. this.constraint.detach();
  96768. this.shape1 = null;
  96769. this.shape2 = null;
  96770. this.body1 = null;
  96771. this.body2 = null;
  96772. }
  96773. }
  96774. /**
  96775. * ...
  96776. * @author saharan
  96777. */
  96778. OIMO.ContactConstraint = function (manifold) {
  96779. OIMO.Constraint.call(this);
  96780. // The contact manifold of the constraint.
  96781. this.manifold = manifold;
  96782. // The coefficient of restitution of the constraint.
  96783. this.restitution = NaN;
  96784. // The coefficient of friction of the constraint.
  96785. this.friction = NaN;
  96786. this.p1 = null;
  96787. this.p2 = null;
  96788. this.lv1 = null;
  96789. this.lv2 = null;
  96790. this.av1 = null;
  96791. this.av2 = null;
  96792. this.i1 = null;
  96793. this.i2 = null;
  96794. this.ii1 = null;
  96795. this.ii2 = null;
  96796. this.m1 = NaN;
  96797. this.m2 = NaN;
  96798. this.num = 0;
  96799. this.ps = manifold.points;
  96800. this.cs = new OIMO.ContactPointDataBuffer();
  96801. this.cs.next = new OIMO.ContactPointDataBuffer();
  96802. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  96803. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  96804. }
  96805. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  96806. /**
  96807. * Attach the constraint to the bodies.
  96808. */
  96809. OIMO.ContactConstraint.prototype.attach = function () {
  96810. this.p1 = this.body1.position;
  96811. this.p2 = this.body2.position;
  96812. this.lv1 = this.body1.linearVelocity;
  96813. this.av1 = this.body1.angularVelocity;
  96814. this.lv2 = this.body2.linearVelocity;
  96815. this.av2 = this.body2.angularVelocity;
  96816. this.i1 = this.body1.inverseInertia;
  96817. this.i2 = this.body2.inverseInertia;
  96818. }
  96819. /**
  96820. * Detach the constraint from the bodies.
  96821. */
  96822. OIMO.ContactConstraint.prototype.detach = function () {
  96823. this.p1 = null;
  96824. this.p2 = null;
  96825. this.lv1 = null;
  96826. this.lv2 = null;
  96827. this.av1 = null;
  96828. this.av2 = null;
  96829. this.i1 = null;
  96830. this.i2 = null;
  96831. }
  96832. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  96833. this.m1 = this.body1.inverseMass;
  96834. this.m2 = this.body2.inverseMass;
  96835. this.ii1 = this.i1.clone();
  96836. this.ii2 = this.i2.clone();
  96837. var ii1 = this.ii1.elements;
  96838. var ii2 = this.ii2.elements;
  96839. var p1x = this.p1.x;
  96840. var p1y = this.p1.y;
  96841. var p1z = this.p1.z;
  96842. var p2x = this.p2.x;
  96843. var p2y = this.p2.y;
  96844. var p2z = this.p2.z;
  96845. var m1m2 = this.m1 + this.m2;
  96846. this.num = this.manifold.numPoints;
  96847. var c = this.cs;
  96848. for (var i = 0; i < this.num; i++) {
  96849. var p = this.ps[i];
  96850. var tmp1X;
  96851. var tmp1Y;
  96852. var tmp1Z;
  96853. var tmp2X;
  96854. var tmp2Y;
  96855. var tmp2Z;
  96856. tmp1X = p.position.x;
  96857. tmp1Y = p.position.y;
  96858. tmp1Z = p.position.z;
  96859. var rp1X = tmp1X - p1x;
  96860. var rp1Y = tmp1Y - p1y;
  96861. var rp1Z = tmp1Z - p1z;
  96862. var rp2X = tmp1X - p2x;
  96863. var rp2Y = tmp1Y - p2y;
  96864. var rp2Z = tmp1Z - p2z;
  96865. c.rp1X = rp1X;
  96866. c.rp1Y = rp1Y;
  96867. c.rp1Z = rp1Z;
  96868. c.rp2X = rp2X;
  96869. c.rp2Y = rp2Y;
  96870. c.rp2Z = rp2Z;
  96871. c.norImp = p.normalImpulse;
  96872. c.tanImp = p.tangentImpulse;
  96873. c.binImp = p.binormalImpulse;
  96874. var norX = p.normal.x;
  96875. var norY = p.normal.y;
  96876. var norZ = p.normal.z;
  96877. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  96878. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  96879. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  96880. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  96881. var tanX = rvX - rvn * norX;
  96882. var tanY = rvY - rvn * norY;
  96883. var tanZ = rvZ - rvn * norZ;
  96884. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  96885. if (len > 0.04) {
  96886. len = 1 / OIMO.sqrt(len);
  96887. } else {
  96888. tanX = norY * norX - norZ * norZ;
  96889. tanY = -norZ * norY - norX * norX;
  96890. tanZ = norX * norZ + norY * norY;
  96891. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  96892. }
  96893. tanX *= len;
  96894. tanY *= len;
  96895. tanZ *= len;
  96896. var binX = norY * tanZ - norZ * tanY;
  96897. var binY = norZ * tanX - norX * tanZ;
  96898. var binZ = norX * tanY - norY * tanX;
  96899. c.norX = norX;
  96900. c.norY = norY;
  96901. c.norZ = norZ;
  96902. c.tanX = tanX;
  96903. c.tanY = tanY;
  96904. c.tanZ = tanZ;
  96905. c.binX = binX;
  96906. c.binY = binY;
  96907. c.binZ = binZ;
  96908. c.norU1X = norX * this.m1;
  96909. c.norU1Y = norY * this.m1;
  96910. c.norU1Z = norZ * this.m1;
  96911. c.norU2X = norX * this.m2;
  96912. c.norU2Y = norY * this.m2;
  96913. c.norU2Z = norZ * this.m2;
  96914. c.tanU1X = tanX * this.m1;
  96915. c.tanU1Y = tanY * this.m1;
  96916. c.tanU1Z = tanZ * this.m1;
  96917. c.tanU2X = tanX * this.m2;
  96918. c.tanU2Y = tanY * this.m2;
  96919. c.tanU2Z = tanZ * this.m2;
  96920. c.binU1X = binX * this.m1;
  96921. c.binU1Y = binY * this.m1;
  96922. c.binU1Z = binZ * this.m1;
  96923. c.binU2X = binX * this.m2;
  96924. c.binU2Y = binY * this.m2;
  96925. c.binU2Z = binZ * this.m2;
  96926. var norT1X = rp1Y * norZ - rp1Z * norY;
  96927. var norT1Y = rp1Z * norX - rp1X * norZ;
  96928. var norT1Z = rp1X * norY - rp1Y * norX;
  96929. var norT2X = rp2Y * norZ - rp2Z * norY;
  96930. var norT2Y = rp2Z * norX - rp2X * norZ;
  96931. var norT2Z = rp2X * norY - rp2Y * norX;
  96932. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  96933. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  96934. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  96935. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  96936. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  96937. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  96938. var binT1X = rp1Y * binZ - rp1Z * binY;
  96939. var binT1Y = rp1Z * binX - rp1X * binZ;
  96940. var binT1Z = rp1X * binY - rp1Y * binX;
  96941. var binT2X = rp2Y * binZ - rp2Z * binY;
  96942. var binT2Y = rp2Z * binX - rp2X * binZ;
  96943. var binT2Z = rp2X * binY - rp2Y * binX;
  96944. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  96945. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  96946. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  96947. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  96948. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  96949. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  96950. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  96951. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  96952. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  96953. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  96954. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  96955. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  96956. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  96957. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  96958. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  96959. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  96960. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  96961. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  96962. c.norT1X = norT1X;
  96963. c.norT1Y = norT1Y;
  96964. c.norT1Z = norT1Z;
  96965. c.tanT1X = tanT1X;
  96966. c.tanT1Y = tanT1Y;
  96967. c.tanT1Z = tanT1Z;
  96968. c.binT1X = binT1X;
  96969. c.binT1Y = binT1Y;
  96970. c.binT1Z = binT1Z;
  96971. c.norT2X = norT2X;
  96972. c.norT2Y = norT2Y;
  96973. c.norT2Z = norT2Z;
  96974. c.tanT2X = tanT2X;
  96975. c.tanT2Y = tanT2Y;
  96976. c.tanT2Z = tanT2Z;
  96977. c.binT2X = binT2X;
  96978. c.binT2Y = binT2Y;
  96979. c.binT2Z = binT2Z;
  96980. c.norTU1X = norTU1X;
  96981. c.norTU1Y = norTU1Y;
  96982. c.norTU1Z = norTU1Z;
  96983. c.tanTU1X = tanTU1X;
  96984. c.tanTU1Y = tanTU1Y;
  96985. c.tanTU1Z = tanTU1Z;
  96986. c.binTU1X = binTU1X;
  96987. c.binTU1Y = binTU1Y;
  96988. c.binTU1Z = binTU1Z;
  96989. c.norTU2X = norTU2X;
  96990. c.norTU2Y = norTU2Y;
  96991. c.norTU2Z = norTU2Z;
  96992. c.tanTU2X = tanTU2X;
  96993. c.tanTU2Y = tanTU2Y;
  96994. c.tanTU2Z = tanTU2Z;
  96995. c.binTU2X = binTU2X;
  96996. c.binTU2Y = binTU2Y;
  96997. c.binTU2Z = binTU2Z;
  96998. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  96999. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97000. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97001. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97002. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97003. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97004. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97005. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97006. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97007. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97008. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97009. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97010. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  97011. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97012. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97013. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97014. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97015. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97016. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97017. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97018. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97019. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97020. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97021. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97022. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97023. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  97024. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97025. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97026. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97027. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97028. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97029. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97030. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97031. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97032. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97033. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97034. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97035. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97036. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  97037. c.norDen = norDen;
  97038. c.tanDen = tanDen;
  97039. c.binDen = binDen;
  97040. if (p.warmStarted) {
  97041. var norImp = p.normalImpulse;
  97042. this.lv1.x += c.norU1X * norImp;
  97043. this.lv1.y += c.norU1Y * norImp;
  97044. this.lv1.z += c.norU1Z * norImp;
  97045. this.av1.x += norTU1X * norImp;
  97046. this.av1.y += norTU1Y * norImp;
  97047. this.av1.z += norTU1Z * norImp;
  97048. this.lv2.x -= c.norU2X * norImp;
  97049. this.lv2.y -= c.norU2Y * norImp;
  97050. this.lv2.z -= c.norU2Z * norImp;
  97051. this.av2.x -= norTU2X * norImp;
  97052. this.av2.y -= norTU2Y * norImp;
  97053. this.av2.z -= norTU2Z * norImp;
  97054. c.norImp = norImp;
  97055. c.tanImp = 0;
  97056. c.binImp = 0;
  97057. rvn = 0; // disable bouncing
  97058. } else {
  97059. c.norImp = 0;
  97060. c.tanImp = 0;
  97061. c.binImp = 0;
  97062. }
  97063. if (rvn > -1) {
  97064. rvn = 0; // disable bouncing
  97065. }
  97066. var norTar = this.restitution * -rvn;
  97067. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  97068. if (norTar < sepV) norTar = sepV;
  97069. c.norTar = norTar;
  97070. c.last = i == this.num - 1;
  97071. c = c.next;
  97072. }
  97073. }
  97074. OIMO.ContactConstraint.prototype.solve = function () {
  97075. var lv1x = this.lv1.x;
  97076. var lv1y = this.lv1.y;
  97077. var lv1z = this.lv1.z;
  97078. var lv2x = this.lv2.x;
  97079. var lv2y = this.lv2.y;
  97080. var lv2z = this.lv2.z;
  97081. var av1x = this.av1.x;
  97082. var av1y = this.av1.y;
  97083. var av1z = this.av1.z;
  97084. var av2x = this.av2.x;
  97085. var av2y = this.av2.y;
  97086. var av2z = this.av2.z;
  97087. var c = this.cs;
  97088. while (true) {
  97089. var oldImp1;
  97090. var newImp1;
  97091. var oldImp2;
  97092. var newImp2;
  97093. var rvn;
  97094. var norImp = c.norImp;
  97095. var tanImp = c.tanImp;
  97096. var binImp = c.binImp;
  97097. var max = -norImp * this.friction;
  97098. var rvX = lv2x - lv1x;
  97099. var rvY = lv2y - lv1y;
  97100. var rvZ = lv2z - lv1z;
  97101. rvn =
  97102. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  97103. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  97104. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  97105. ;
  97106. oldImp1 = tanImp;
  97107. newImp1 = rvn * c.tanDen;
  97108. tanImp += newImp1;
  97109. rvn =
  97110. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  97111. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  97112. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  97113. ;
  97114. oldImp2 = binImp;
  97115. newImp2 = rvn * c.binDen;
  97116. binImp += newImp2;
  97117. // cone friction clamp
  97118. var len = tanImp * tanImp + binImp * binImp;
  97119. if (len > max * max) {
  97120. len = max / OIMO.sqrt(len);
  97121. tanImp *= len;
  97122. binImp *= len;
  97123. }
  97124. newImp1 = tanImp - oldImp1;
  97125. newImp2 = binImp - oldImp2;
  97126. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  97127. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  97128. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  97129. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  97130. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  97131. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  97132. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  97133. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  97134. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  97135. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  97136. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  97137. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  97138. // restitution part
  97139. rvn =
  97140. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  97141. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  97142. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  97143. oldImp1 = norImp;
  97144. newImp1 = (rvn - c.norTar) * c.norDen;
  97145. norImp += newImp1;
  97146. if (norImp > 0) norImp = 0;
  97147. newImp1 = norImp - oldImp1;
  97148. lv1x += c.norU1X * newImp1;
  97149. lv1y += c.norU1Y * newImp1;
  97150. lv1z += c.norU1Z * newImp1;
  97151. av1x += c.norTU1X * newImp1;
  97152. av1y += c.norTU1Y * newImp1;
  97153. av1z += c.norTU1Z * newImp1;
  97154. lv2x -= c.norU2X * newImp1;
  97155. lv2y -= c.norU2Y * newImp1;
  97156. lv2z -= c.norU2Z * newImp1;
  97157. av2x -= c.norTU2X * newImp1;
  97158. av2y -= c.norTU2Y * newImp1;
  97159. av2z -= c.norTU2Z * newImp1;
  97160. c.norImp = norImp;
  97161. c.tanImp = tanImp;
  97162. c.binImp = binImp;
  97163. if (c.last) break;
  97164. c = c.next;
  97165. }
  97166. this.lv1.x = lv1x;
  97167. this.lv1.y = lv1y;
  97168. this.lv1.z = lv1z;
  97169. this.lv2.x = lv2x;
  97170. this.lv2.y = lv2y;
  97171. this.lv2.z = lv2z;
  97172. this.av1.x = av1x;
  97173. this.av1.y = av1y;
  97174. this.av1.z = av1z;
  97175. this.av2.x = av2x;
  97176. this.av2.y = av2y;
  97177. this.av2.z = av2z;
  97178. }
  97179. OIMO.ContactConstraint.prototype.postSolve = function () {
  97180. var c = this.cs;
  97181. var i = this.num;
  97182. while (i--) {
  97183. //for(var i=0;i<this.num;i++){
  97184. var p = this.ps[i];
  97185. p.normal.x = c.norX;
  97186. p.normal.y = c.norY;
  97187. p.normal.z = c.norZ;
  97188. p.tangent.x = c.tanX;
  97189. p.tangent.y = c.tanY;
  97190. p.tangent.z = c.tanZ;
  97191. p.binormal.x = c.binX;
  97192. p.binormal.y = c.binY;
  97193. p.binormal.z = c.binZ;
  97194. p.normalImpulse = c.norImp;
  97195. p.tangentImpulse = c.tanImp;
  97196. p.binormalImpulse = c.binImp;
  97197. p.normalDenominator = c.norDen;
  97198. p.tangentDenominator = c.tanDen;
  97199. p.binormalDenominator = c.binDen;
  97200. c = c.next;
  97201. }
  97202. }
  97203. /**
  97204. * A link list of contacts.
  97205. * @author saharan
  97206. */
  97207. OIMO.ContactLink = function (contact) {
  97208. // The previous contact link.
  97209. this.prev = null;
  97210. // The next contact link.
  97211. this.next = null;
  97212. // The shape of the contact.
  97213. this.shape = null;
  97214. // The other rigid body.
  97215. this.body = null;
  97216. // The contact of the link.
  97217. this.contact = contact;
  97218. }
  97219. /**
  97220. * A contact manifold between two shapes.
  97221. * @author saharan
  97222. */
  97223. OIMO.ContactManifold = function () {
  97224. // The first rigid body.
  97225. this.body1 = null;
  97226. // The second rigid body.
  97227. this.body2 = null;
  97228. // The number of manifold points.
  97229. this.numPoints = 0;
  97230. // The manifold points.
  97231. this.points = [];
  97232. this.points.length = 4;
  97233. this.points[0] = new OIMO.ManifoldPoint();
  97234. this.points[1] = new OIMO.ManifoldPoint();
  97235. this.points[2] = new OIMO.ManifoldPoint();
  97236. this.points[3] = new OIMO.ManifoldPoint();
  97237. }
  97238. OIMO.ContactManifold.prototype = {
  97239. constructor: OIMO.ContactManifold,
  97240. /**
  97241. * Reset the manifold.
  97242. * @param shape1
  97243. * @param shape2
  97244. */
  97245. reset: function (shape1, shape2) {
  97246. this.body1 = shape1.parent;
  97247. this.body2 = shape2.parent;
  97248. this.numPoints = 0;
  97249. },
  97250. /**
  97251. * Add a point into this manifold.
  97252. * @param x
  97253. * @param y
  97254. * @param z
  97255. * @param normalX
  97256. * @param normalY
  97257. * @param normalZ
  97258. * @param penetration
  97259. * @param flip
  97260. */
  97261. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  97262. var p = this.points[this.numPoints++];
  97263. p.position.x = x;
  97264. p.position.y = y;
  97265. p.position.z = z;
  97266. var r = this.body1.rotation;
  97267. var rx = x - this.body1.position.x;
  97268. var ry = y - this.body1.position.y;
  97269. var rz = z - this.body1.position.z;
  97270. var tr = r.elements;
  97271. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  97272. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  97273. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  97274. r = this.body2.rotation;
  97275. rx = x - this.body2.position.x;
  97276. ry = y - this.body2.position.y;
  97277. rz = z - this.body2.position.z;
  97278. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  97279. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  97280. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  97281. p.normalImpulse = 0;
  97282. if (flip) {
  97283. p.normal.x = -normalX;
  97284. p.normal.y = -normalY;
  97285. p.normal.z = -normalZ;
  97286. } else {
  97287. p.normal.x = normalX;
  97288. p.normal.y = normalY;
  97289. p.normal.z = normalZ;
  97290. }
  97291. p.penetration = penetration;
  97292. p.warmStarted = false;
  97293. }
  97294. }
  97295. OIMO.ContactPointDataBuffer = function () {
  97296. this.norX = NaN;
  97297. this.norY = NaN;
  97298. this.norZ = NaN;
  97299. this.tanX = NaN;
  97300. this.tanY = NaN;
  97301. this.tanZ = NaN;
  97302. this.binX = NaN;
  97303. this.binY = NaN;
  97304. this.binZ = NaN;
  97305. this.rp1X = NaN;
  97306. this.rp1Y = NaN;
  97307. this.rp1Z = NaN;
  97308. this.rp2X = NaN;
  97309. this.rp2Y = NaN;
  97310. this.rp2Z = NaN;
  97311. this.norU1X = NaN;
  97312. this.norU1Y = NaN;
  97313. this.norU1Z = NaN;
  97314. this.norU2X = NaN;
  97315. this.norU2Y = NaN;
  97316. this.norU2Z = NaN;
  97317. this.tanU1X = NaN;
  97318. this.tanU1Y = NaN;
  97319. this.tanU1Z = NaN;
  97320. this.tanU2X = NaN;
  97321. this.tanU2Y = NaN;
  97322. this.tanU2Z = NaN;
  97323. this.binU1X = NaN;
  97324. this.binU1Y = NaN;
  97325. this.binU1Z = NaN;
  97326. this.binU2X = NaN;
  97327. this.binU2Y = NaN;
  97328. this.binU2Z = NaN;
  97329. this.norT1X = NaN;
  97330. this.norT1Y = NaN;
  97331. this.norT1Z = NaN;
  97332. this.norT2X = NaN;
  97333. this.norT2Y = NaN;
  97334. this.norT2Z = NaN;
  97335. this.tanT1X = NaN;
  97336. this.tanT1Y = NaN;
  97337. this.tanT1Z = NaN;
  97338. this.tanT2X = NaN;
  97339. this.tanT2Y = NaN;
  97340. this.tanT2Z = NaN;
  97341. this.binT1X = NaN;
  97342. this.binT1Y = NaN;
  97343. this.binT1Z = NaN;
  97344. this.binT2X = NaN;
  97345. this.binT2Y = NaN;
  97346. this.binT2Z = NaN;
  97347. this.norTU1X = NaN;
  97348. this.norTU1Y = NaN;
  97349. this.norTU1Z = NaN;
  97350. this.norTU2X = NaN;
  97351. this.norTU2Y = NaN;
  97352. this.norTU2Z = NaN;
  97353. this.tanTU1X = NaN;
  97354. this.tanTU1Y = NaN;
  97355. this.tanTU1Z = NaN;
  97356. this.tanTU2X = NaN;
  97357. this.tanTU2Y = NaN;
  97358. this.tanTU2Z = NaN;
  97359. this.binTU1X = NaN;
  97360. this.binTU1Y = NaN;
  97361. this.binTU1Z = NaN;
  97362. this.binTU2X = NaN;
  97363. this.binTU2Y = NaN;
  97364. this.binTU2Z = NaN;
  97365. this.norImp = NaN;
  97366. this.tanImp = NaN;
  97367. this.binImp = NaN;
  97368. this.norDen = NaN;
  97369. this.tanDen = NaN;
  97370. this.binDen = NaN;
  97371. this.norTar = NaN;
  97372. this.next = null;
  97373. this.last = false;
  97374. }
  97375. OIMO.ImpulseDataBuffer = function () {
  97376. this.lp1X = NaN;
  97377. this.lp1Y = NaN;
  97378. this.lp1Z = NaN;
  97379. this.lp2X = NaN;
  97380. this.lp2Y = NaN;
  97381. this.lp2Z = NaN;
  97382. this.impulse = NaN;
  97383. }
  97384. /**
  97385. * The class holds details of the contact point.
  97386. * @author saharan
  97387. */
  97388. OIMO.ManifoldPoint = function () {
  97389. // Whether this manifold point is persisting or not.
  97390. this.warmStarted = false;
  97391. // The position of this manifold point.
  97392. this.position = new OIMO.Vec3();
  97393. // The position in the first shape's coordinate.
  97394. this.localPoint1 = new OIMO.Vec3();
  97395. // The position in the second shape's coordinate.
  97396. this.localPoint2 = new OIMO.Vec3();
  97397. // The normal vector of this manifold point.
  97398. this.normal = new OIMO.Vec3();
  97399. // The tangent vector of this manifold point.
  97400. this.tangent = new OIMO.Vec3();
  97401. // The binormal vector of this manifold point.
  97402. this.binormal = new OIMO.Vec3();
  97403. // The impulse in normal direction.
  97404. this.normalImpulse = 0;
  97405. // The impulse in tangent direction.
  97406. this.tangentImpulse = 0;
  97407. // The impulse in binormal direction.
  97408. this.binormalImpulse = 0;
  97409. // The denominator in normal direction.
  97410. this.normalDenominator = 0;
  97411. // The denominator in tangent direction.
  97412. this.tangentDenominator = 0;
  97413. // The denominator in binormal direction.
  97414. this.binormalDenominator = 0;
  97415. // The depth of penetration.
  97416. this.penetration = 0;
  97417. }
  97418. /**
  97419. * This class holds mass information of a shape.
  97420. * @author saharan
  97421. */
  97422. OIMO.MassInfo = function () {
  97423. // Mass of the shape.
  97424. this.mass = 0;
  97425. // The moment inertia of the shape.
  97426. this.inertia = new OIMO.Mat33();
  97427. };
  97428. /**
  97429. * A shape is used to detect collisions of rigid bodies.
  97430. * @author saharan
  97431. * @author lo-th
  97432. */
  97433. OIMO.Shape = function (config) {
  97434. this.type = OIMO.SHAPE_NULL;
  97435. // The global identification of the shape should be unique to the shape.
  97436. this.id = OIMO.nextID++;
  97437. // The previous shape in parent rigid body.
  97438. this.prev = null;
  97439. // The next shape in parent rigid body.
  97440. this.next = null;
  97441. // The proxy of the shape used for broad-phase collision detection.
  97442. this.proxy = null;
  97443. // The parent rigid body of the shape.
  97444. this.parent = null;
  97445. // The linked list of the contacts with the shape.
  97446. this.contactLink = null;
  97447. // The number of the contacts with the shape.
  97448. this.numContacts = 0;
  97449. // The center of gravity of the shape in world coordinate system.
  97450. this.position = new OIMO.Vec3();
  97451. // The rotation matrix of the shape in world coordinate system
  97452. this.rotation = new OIMO.Mat33();
  97453. // The position of the shape in parent's coordinate system.
  97454. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  97455. // The rotation matrix of the shape in parent's coordinate system.
  97456. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  97457. // The axis-aligned bounding box of the shape.
  97458. this.aabb = new OIMO.AABB();
  97459. // The density of the shape.
  97460. this.density = config.density;
  97461. // The coefficient of friction of the shape.
  97462. this.friction = config.friction;
  97463. // The coefficient of restitution of the shape.
  97464. this.restitution = config.restitution;
  97465. // The bits of the collision groups to which the shape belongs.
  97466. this.belongsTo = config.belongsTo;
  97467. // The bits of the collision groups with which the shape collides.
  97468. this.collidesWith = config.collidesWith;
  97469. };
  97470. OIMO.Shape.prototype = {
  97471. constructor: OIMO.Shape,
  97472. // Calculate the mass information of the shape.
  97473. calculateMassInfo: function (out) {
  97474. OIMO.Error("Shape", "Inheritance error.");
  97475. },
  97476. // Update the proxy of the shape.
  97477. updateProxy: function () {
  97478. OIMO.Error("Shape", "Inheritance error.");
  97479. }
  97480. };
  97481. /**
  97482. * A shape configuration holds common configuration data for constructing a shape.
  97483. * Shape configurations can be reused safely.
  97484. * @author saharan
  97485. */
  97486. OIMO.ShapeConfig = function () {
  97487. // The position of the shape in parent's coordinate system.
  97488. this.relativePosition = new OIMO.Vec3();
  97489. // The rotation matrix of the shape in parent's coordinate system.
  97490. this.relativeRotation = new OIMO.Mat33();
  97491. // The coefficient of friction of the shape.
  97492. this.friction = 0.4;
  97493. // The coefficient of restitution of the shape.
  97494. this.restitution = 0.2;
  97495. // The density of the shape.
  97496. this.density = 1;
  97497. // The bits of the collision groups to which the shape belongs.
  97498. this.belongsTo = 1;
  97499. // The bits of the collision groups with which the shape collides.
  97500. this.collidesWith = 0xffffffff;
  97501. };
  97502. /**
  97503. * A box shape.
  97504. * @author saharan
  97505. * @author lo-th
  97506. */
  97507. OIMO.BoxShape = function (config, Width, Height, Depth) {
  97508. OIMO.Shape.call(this, config);
  97509. this.type = OIMO.SHAPE_BOX;
  97510. // The width of the box.
  97511. this.width = Width;
  97512. // The height of the box.
  97513. this.height = Height;
  97514. // The depth of the box.
  97515. this.depth = Depth;
  97516. // The half-width of the box.
  97517. this.halfWidth = Width * 0.5;
  97518. // The half-height of the box.
  97519. this.halfHeight = Height * 0.5;
  97520. // The half-depth of the box.
  97521. this.halfDepth = Depth * 0.5;
  97522. this.dimentions = new OIMO_ARRAY_TYPE(18);
  97523. this.elements = new OIMO_ARRAY_TYPE(24);
  97524. };
  97525. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  97526. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  97527. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  97528. var mass = this.width * this.height * this.depth * this.density;
  97529. var divid = 1 / 12;
  97530. out.mass = mass;
  97531. out.inertia.set(
  97532. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  97533. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  97534. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  97535. );
  97536. };
  97537. OIMO.BoxShape.prototype.updateProxy = function () {
  97538. var te = this.rotation.elements;
  97539. var di = this.dimentions;
  97540. // Width
  97541. di[0] = te[0];
  97542. di[1] = te[3];
  97543. di[2] = te[6];
  97544. // Height
  97545. di[3] = te[1];
  97546. di[4] = te[4];
  97547. di[5] = te[7];
  97548. // Depth
  97549. di[6] = te[2];
  97550. di[7] = te[5];
  97551. di[8] = te[8];
  97552. // halp Width
  97553. di[9] = te[0] * this.halfWidth;
  97554. di[10] = te[3] * this.halfWidth;
  97555. di[11] = te[6] * this.halfWidth;
  97556. // halp Height
  97557. di[12] = te[1] * this.halfHeight;
  97558. di[13] = te[4] * this.halfHeight;
  97559. di[14] = te[7] * this.halfHeight;
  97560. // halp Depth
  97561. di[15] = te[2] * this.halfDepth;
  97562. di[16] = te[5] * this.halfDepth;
  97563. di[17] = te[8] * this.halfDepth;
  97564. var wx = di[9];
  97565. var wy = di[10];
  97566. var wz = di[11];
  97567. var hx = di[12];
  97568. var hy = di[13];
  97569. var hz = di[14];
  97570. var dx = di[15];
  97571. var dy = di[16];
  97572. var dz = di[17];
  97573. var x = this.position.x;
  97574. var y = this.position.y;
  97575. var z = this.position.z;
  97576. var v = this.elements;
  97577. //v1
  97578. v[0] = x + wx + hx + dx;
  97579. v[1] = y + wy + hy + dy;
  97580. v[2] = z + wz + hz + dz;
  97581. //v2
  97582. v[3] = x + wx + hx - dx;
  97583. v[4] = y + wy + hy - dy;
  97584. v[5] = z + wz + hz - dz;
  97585. //v3
  97586. v[6] = x + wx - hx + dx;
  97587. v[7] = y + wy - hy + dy;
  97588. v[8] = z + wz - hz + dz;
  97589. //v4
  97590. v[9] = x + wx - hx - dx;
  97591. v[10] = y + wy - hy - dy;
  97592. v[11] = z + wz - hz - dz;
  97593. //v5
  97594. v[12] = x - wx + hx + dx;
  97595. v[13] = y - wy + hy + dy;
  97596. v[14] = z - wz + hz + dz;
  97597. //v6
  97598. v[15] = x - wx + hx - dx;
  97599. v[16] = y - wy + hy - dy;
  97600. v[17] = z - wz + hz - dz;
  97601. //v7
  97602. v[18] = x - wx - hx + dx;
  97603. v[19] = y - wy - hy + dy;
  97604. v[20] = z - wz - hz + dz;
  97605. //v8
  97606. v[21] = x - wx - hx - dx;
  97607. v[22] = y - wy - hy - dy;
  97608. v[23] = z - wz - hz - dz;
  97609. var w = di[9] < 0 ? -di[9] : di[9];
  97610. var h = di[10] < 0 ? -di[10] : di[10];
  97611. var d = di[11] < 0 ? -di[11] : di[11];
  97612. w = di[12] < 0 ? w - di[12] : w + di[12];
  97613. h = di[13] < 0 ? h - di[13] : h + di[13];
  97614. d = di[14] < 0 ? d - di[14] : d + di[14];
  97615. w = di[15] < 0 ? w - di[15] : w + di[15];
  97616. h = di[16] < 0 ? h - di[16] : h + di[16];
  97617. d = di[17] < 0 ? d - di[17] : d + di[17];
  97618. var p = OIMO.AABB_PROX;
  97619. this.aabb.set(
  97620. this.position.x - w - p, this.position.x + w + p,
  97621. this.position.y - h - p, this.position.y + h + p,
  97622. this.position.z - d - p, this.position.z + d + p
  97623. );
  97624. if (this.proxy != null) this.proxy.update();
  97625. };
  97626. /**
  97627. * A sphere shape.
  97628. * @author saharan
  97629. * @author lo-th
  97630. */
  97631. OIMO.SphereShape = function (config, radius) {
  97632. OIMO.Shape.call(this, config);
  97633. this.type = OIMO.SHAPE_SPHERE;
  97634. // The radius of the shape.
  97635. this.radius = radius;
  97636. };
  97637. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  97638. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  97639. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  97640. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  97641. out.mass = mass;
  97642. var inertia = mass * this.radius * this.radius * 0.4;
  97643. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  97644. };
  97645. OIMO.SphereShape.prototype.updateProxy = function () {
  97646. var p = OIMO.AABB_PROX;
  97647. this.aabb.set(
  97648. this.position.x - this.radius - p, this.position.x + this.radius + p,
  97649. this.position.y - this.radius - p, this.position.y + this.radius + p,
  97650. this.position.z - this.radius - p, this.position.z + this.radius + p
  97651. );
  97652. if (this.proxy != null) this.proxy.update();
  97653. };
  97654. /**
  97655. * A cylinder shap.
  97656. * @author saharan
  97657. * @author lo-th
  97658. */
  97659. OIMO.CylinderShape = function (config, radius, height) {
  97660. OIMO.Shape.call(this, config);
  97661. this.type = OIMO.SHAPE_CYLINDER;
  97662. this.radius = radius;
  97663. this.height = height;
  97664. this.halfHeight = height * 0.5;
  97665. this.normalDirection = new OIMO.Vec3();
  97666. this.halfDirection = new OIMO.Vec3();
  97667. };
  97668. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  97669. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  97670. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  97671. var rsq = this.radius * this.radius;
  97672. var mass = OIMO.PI * rsq * this.height * this.density;
  97673. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  97674. var inertiaY = 0.5 * rsq;
  97675. out.mass = mass;
  97676. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  97677. };
  97678. OIMO.CylinderShape.prototype.updateProxy = function () {
  97679. var te = this.rotation.elements;
  97680. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  97681. xx = te[1] * te[1];
  97682. yy = te[4] * te[4];
  97683. zz = te[7] * te[7];
  97684. this.normalDirection.set(te[1], te[4], te[7]);
  97685. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  97686. wx = 1 - xx;
  97687. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  97688. if (len > 0) len = this.radius / len;
  97689. wx *= len;
  97690. hy = 1 - yy;
  97691. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  97692. if (len > 0) len = this.radius / len;
  97693. hy *= len;
  97694. dz = 1 - zz;
  97695. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  97696. if (len > 0) len = this.radius / len;
  97697. dz *= len;
  97698. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  97699. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  97700. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  97701. w = wx < 0 ? w - wx : w + wx;
  97702. h = hy < 0 ? h - hy : h + hy;
  97703. d = dz < 0 ? d - dz : d + dz;
  97704. p = OIMO.AABB_PROX;
  97705. this.aabb.set(
  97706. this.position.x - w - p, this.position.x + w + p,
  97707. this.position.y - h - p, this.position.y + h + p,
  97708. this.position.z - d - p, this.position.z + d + p
  97709. );
  97710. if (this.proxy != null) this.proxy.update();
  97711. };
  97712. /**
  97713. * A tetra shape.
  97714. * @author xprogram
  97715. */
  97716. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  97717. OIMO.Shape.call(this, config);
  97718. this.type = OIMO.SHAPE_TETRA;
  97719. // Vertices and faces of tetra
  97720. this.verts = [p1, p2, p3, p4];
  97721. this.faces = [
  97722. mtri(0, 1, 2),
  97723. mtri(1, 2, 3),
  97724. mtri(2, 3, 4),
  97725. mtri(4, 0, 1),
  97726. ];
  97727. };
  97728. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  97729. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  97730. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  97731. // I guess you could calculate box mass and split it
  97732. // in half for the tetra...
  97733. };
  97734. OIMO.TetraShape.prototype.updateProxy = function () {
  97735. this.aabb.setFromPoints(this.verts);
  97736. if (this.proxy !== null)
  97737. this.proxy.update();
  97738. };
  97739. function mtri(a, b, c) {
  97740. return { a: a, b: b, c: c };
  97741. }
  97742. OIMO.CollisionDetector = function () {
  97743. this.flip = false;
  97744. };
  97745. OIMO.CollisionDetector.prototype = {
  97746. constructor: OIMO.CollisionDetector,
  97747. detectCollision: function (shape1, shape2, manifold) {
  97748. OIMO.Error("CollisionDetector", "Inheritance error.");
  97749. }
  97750. };
  97751. /**
  97752. * A collision detector which detects collisions between two boxes.
  97753. * @author saharan
  97754. */
  97755. OIMO.BoxBoxCollisionDetector = function () {
  97756. OIMO.CollisionDetector.call(this);
  97757. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  97758. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  97759. this.used = new OIMO_ARRAY_TYPE(8);
  97760. this.INF = 1 / 0;
  97761. };
  97762. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97763. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  97764. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97765. // What you are doing
  97766. // · I to prepare a separate axis of the fifteen
  97767. //-Six in each of three normal vectors of the xyz direction of the box both
  97768. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  97769. // · Calculate the depth to the separation axis
  97770. // Calculates the distance using the inner product and put the amount of embedment
  97771. // · However a vertical separation axis and side to weight a little to avoid vibration
  97772. // And end when there is a separate axis that is remote even one
  97773. // · I look for separation axis with little to dent most
  97774. // Men and if separation axis of the first six - end collision
  97775. // Heng If it separate axis of nine other - side collision
  97776. // Heng - case of a side collision
  97777. // · Find points of two sides on which you made ​​the separation axis
  97778. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  97779. //-Surface - the case of the plane crash
  97780. //-Box A, box B and the other a box of better made ​​a separate axis
  97781. // • 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
  97782. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  97783. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  97784. // • If more than one candidate 5 exists, scraping up to four
  97785. // For potential collision points of all, to examine the distance between the surface A
  97786. // • If you were on the inside surface of A, and the collision point
  97787. var b1;
  97788. var b2;
  97789. if (shape1.id < shape2.id) {
  97790. b1 = (shape1);
  97791. b2 = (shape2);
  97792. } else {
  97793. b1 = (shape2);
  97794. b2 = (shape1);
  97795. }
  97796. var V1 = b1.elements;
  97797. var V2 = b2.elements;
  97798. var D1 = b1.dimentions;
  97799. var D2 = b2.dimentions;
  97800. var p1 = b1.position;
  97801. var p2 = b2.position;
  97802. var p1x = p1.x;
  97803. var p1y = p1.y;
  97804. var p1z = p1.z;
  97805. var p2x = p2.x;
  97806. var p2y = p2.y;
  97807. var p2z = p2.z;
  97808. // diff
  97809. var dx = p2x - p1x;
  97810. var dy = p2y - p1y;
  97811. var dz = p2z - p1z;
  97812. // distance
  97813. var w1 = b1.halfWidth;
  97814. var h1 = b1.halfHeight;
  97815. var d1 = b1.halfDepth;
  97816. var w2 = b2.halfWidth;
  97817. var h2 = b2.halfHeight;
  97818. var d2 = b2.halfDepth;
  97819. // direction
  97820. // ----------------------------
  97821. // 15 separating axes
  97822. // 1~6: face
  97823. // 7~f: edge
  97824. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  97825. // ----------------------------
  97826. var a1x = D1[0];
  97827. var a1y = D1[1];
  97828. var a1z = D1[2];
  97829. var a2x = D1[3];
  97830. var a2y = D1[4];
  97831. var a2z = D1[5];
  97832. var a3x = D1[6];
  97833. var a3y = D1[7];
  97834. var a3z = D1[8];
  97835. var d1x = D1[9];
  97836. var d1y = D1[10];
  97837. var d1z = D1[11];
  97838. var d2x = D1[12];
  97839. var d2y = D1[13];
  97840. var d2z = D1[14];
  97841. var d3x = D1[15];
  97842. var d3y = D1[16];
  97843. var d3z = D1[17];
  97844. var a4x = D2[0];
  97845. var a4y = D2[1];
  97846. var a4z = D2[2];
  97847. var a5x = D2[3];
  97848. var a5y = D2[4];
  97849. var a5z = D2[5];
  97850. var a6x = D2[6];
  97851. var a6y = D2[7];
  97852. var a6z = D2[8];
  97853. var d4x = D2[9];
  97854. var d4y = D2[10];
  97855. var d4z = D2[11];
  97856. var d5x = D2[12];
  97857. var d5y = D2[13];
  97858. var d5z = D2[14];
  97859. var d6x = D2[15];
  97860. var d6y = D2[16];
  97861. var d6z = D2[17];
  97862. var a7x = a1y * a4z - a1z * a4y;
  97863. var a7y = a1z * a4x - a1x * a4z;
  97864. var a7z = a1x * a4y - a1y * a4x;
  97865. var a8x = a1y * a5z - a1z * a5y;
  97866. var a8y = a1z * a5x - a1x * a5z;
  97867. var a8z = a1x * a5y - a1y * a5x;
  97868. var a9x = a1y * a6z - a1z * a6y;
  97869. var a9y = a1z * a6x - a1x * a6z;
  97870. var a9z = a1x * a6y - a1y * a6x;
  97871. var aax = a2y * a4z - a2z * a4y;
  97872. var aay = a2z * a4x - a2x * a4z;
  97873. var aaz = a2x * a4y - a2y * a4x;
  97874. var abx = a2y * a5z - a2z * a5y;
  97875. var aby = a2z * a5x - a2x * a5z;
  97876. var abz = a2x * a5y - a2y * a5x;
  97877. var acx = a2y * a6z - a2z * a6y;
  97878. var acy = a2z * a6x - a2x * a6z;
  97879. var acz = a2x * a6y - a2y * a6x;
  97880. var adx = a3y * a4z - a3z * a4y;
  97881. var ady = a3z * a4x - a3x * a4z;
  97882. var adz = a3x * a4y - a3y * a4x;
  97883. var aex = a3y * a5z - a3z * a5y;
  97884. var aey = a3z * a5x - a3x * a5z;
  97885. var aez = a3x * a5y - a3y * a5x;
  97886. var afx = a3y * a6z - a3z * a6y;
  97887. var afy = a3z * a6x - a3x * a6z;
  97888. var afz = a3x * a6y - a3y * a6x;
  97889. // right or left flags
  97890. var right1;
  97891. var right2;
  97892. var right3;
  97893. var right4;
  97894. var right5;
  97895. var right6;
  97896. var right7;
  97897. var right8;
  97898. var right9;
  97899. var righta;
  97900. var rightb;
  97901. var rightc;
  97902. var rightd;
  97903. var righte;
  97904. var rightf;
  97905. // overlapping distances
  97906. var overlap1;
  97907. var overlap2;
  97908. var overlap3;
  97909. var overlap4;
  97910. var overlap5;
  97911. var overlap6;
  97912. var overlap7;
  97913. var overlap8;
  97914. var overlap9;
  97915. var overlapa;
  97916. var overlapb;
  97917. var overlapc;
  97918. var overlapd;
  97919. var overlape;
  97920. var overlapf;
  97921. // invalid flags
  97922. var invalid7 = false;
  97923. var invalid8 = false;
  97924. var invalid9 = false;
  97925. var invalida = false;
  97926. var invalidb = false;
  97927. var invalidc = false;
  97928. var invalidd = false;
  97929. var invalide = false;
  97930. var invalidf = false;
  97931. // temporary variables
  97932. var len;
  97933. var len1;
  97934. var len2;
  97935. var dot1;
  97936. var dot2;
  97937. var dot3;
  97938. // try axis 1
  97939. len = a1x * dx + a1y * dy + a1z * dz;
  97940. right1 = len > 0;
  97941. if (!right1) len = -len;
  97942. len1 = w1;
  97943. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  97944. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  97945. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  97946. if (dot1 < 0) dot1 = -dot1;
  97947. if (dot2 < 0) dot2 = -dot2;
  97948. if (dot3 < 0) dot3 = -dot3;
  97949. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  97950. overlap1 = len - len1 - len2;
  97951. if (overlap1 > 0) return;
  97952. // try axis 2
  97953. len = a2x * dx + a2y * dy + a2z * dz;
  97954. right2 = len > 0;
  97955. if (!right2) len = -len;
  97956. len1 = h1;
  97957. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  97958. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  97959. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  97960. if (dot1 < 0) dot1 = -dot1;
  97961. if (dot2 < 0) dot2 = -dot2;
  97962. if (dot3 < 0) dot3 = -dot3;
  97963. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  97964. overlap2 = len - len1 - len2;
  97965. if (overlap2 > 0) return;
  97966. // try axis 3
  97967. len = a3x * dx + a3y * dy + a3z * dz;
  97968. right3 = len > 0;
  97969. if (!right3) len = -len;
  97970. len1 = d1;
  97971. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  97972. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  97973. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  97974. if (dot1 < 0) dot1 = -dot1;
  97975. if (dot2 < 0) dot2 = -dot2;
  97976. if (dot3 < 0) dot3 = -dot3;
  97977. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  97978. overlap3 = len - len1 - len2;
  97979. if (overlap3 > 0) return;
  97980. // try axis 4
  97981. len = a4x * dx + a4y * dy + a4z * dz;
  97982. right4 = len > 0;
  97983. if (!right4) len = -len;
  97984. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  97985. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  97986. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  97987. if (dot1 < 0) dot1 = -dot1;
  97988. if (dot2 < 0) dot2 = -dot2;
  97989. if (dot3 < 0) dot3 = -dot3;
  97990. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  97991. len2 = w2;
  97992. overlap4 = (len - len1 - len2) * 1.0;
  97993. if (overlap4 > 0) return;
  97994. // try axis 5
  97995. len = a5x * dx + a5y * dy + a5z * dz;
  97996. right5 = len > 0;
  97997. if (!right5) len = -len;
  97998. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  97999. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  98000. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  98001. if (dot1 < 0) dot1 = -dot1;
  98002. if (dot2 < 0) dot2 = -dot2;
  98003. if (dot3 < 0) dot3 = -dot3;
  98004. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98005. len2 = h2;
  98006. overlap5 = (len - len1 - len2) * 1.0;
  98007. if (overlap5 > 0) return;
  98008. // try axis 6
  98009. len = a6x * dx + a6y * dy + a6z * dz;
  98010. right6 = len > 0;
  98011. if (!right6) len = -len;
  98012. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  98013. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  98014. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  98015. if (dot1 < 0) dot1 = -dot1;
  98016. if (dot2 < 0) dot2 = -dot2;
  98017. if (dot3 < 0) dot3 = -dot3;
  98018. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98019. len2 = d2;
  98020. overlap6 = (len - len1 - len2) * 1.0;
  98021. if (overlap6 > 0) return;
  98022. // try axis 7
  98023. len = a7x * a7x + a7y * a7y + a7z * a7z;
  98024. if (len > 1e-5) {
  98025. len = 1 / OIMO.sqrt(len);
  98026. a7x *= len;
  98027. a7y *= len;
  98028. a7z *= len;
  98029. len = a7x * dx + a7y * dy + a7z * dz;
  98030. right7 = len > 0;
  98031. if (!right7) len = -len;
  98032. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  98033. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  98034. if (dot1 < 0) dot1 = -dot1;
  98035. if (dot2 < 0) dot2 = -dot2;
  98036. len1 = dot1 * h1 + dot2 * d1;
  98037. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  98038. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  98039. if (dot1 < 0) dot1 = -dot1;
  98040. if (dot2 < 0) dot2 = -dot2;
  98041. len2 = dot1 * h2 + dot2 * d2;
  98042. overlap7 = len - len1 - len2;
  98043. if (overlap7 > 0) return;
  98044. } else {
  98045. right7 = false;
  98046. overlap7 = 0;
  98047. invalid7 = true;
  98048. }
  98049. // try axis 8
  98050. len = a8x * a8x + a8y * a8y + a8z * a8z;
  98051. if (len > 1e-5) {
  98052. len = 1 / OIMO.sqrt(len);
  98053. a8x *= len;
  98054. a8y *= len;
  98055. a8z *= len;
  98056. len = a8x * dx + a8y * dy + a8z * dz;
  98057. right8 = len > 0;
  98058. if (!right8) len = -len;
  98059. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  98060. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  98061. if (dot1 < 0) dot1 = -dot1;
  98062. if (dot2 < 0) dot2 = -dot2;
  98063. len1 = dot1 * h1 + dot2 * d1;
  98064. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  98065. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  98066. if (dot1 < 0) dot1 = -dot1;
  98067. if (dot2 < 0) dot2 = -dot2;
  98068. len2 = dot1 * w2 + dot2 * d2;
  98069. overlap8 = len - len1 - len2;
  98070. if (overlap8 > 0) return;
  98071. } else {
  98072. right8 = false;
  98073. overlap8 = 0;
  98074. invalid8 = true;
  98075. }
  98076. // try axis 9
  98077. len = a9x * a9x + a9y * a9y + a9z * a9z;
  98078. if (len > 1e-5) {
  98079. len = 1 / OIMO.sqrt(len);
  98080. a9x *= len;
  98081. a9y *= len;
  98082. a9z *= len;
  98083. len = a9x * dx + a9y * dy + a9z * dz;
  98084. right9 = len > 0;
  98085. if (!right9) len = -len;
  98086. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  98087. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  98088. if (dot1 < 0) dot1 = -dot1;
  98089. if (dot2 < 0) dot2 = -dot2;
  98090. len1 = dot1 * h1 + dot2 * d1;
  98091. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  98092. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  98093. if (dot1 < 0) dot1 = -dot1;
  98094. if (dot2 < 0) dot2 = -dot2;
  98095. len2 = dot1 * w2 + dot2 * h2;
  98096. overlap9 = len - len1 - len2;
  98097. if (overlap9 > 0) return;
  98098. } else {
  98099. right9 = false;
  98100. overlap9 = 0;
  98101. invalid9 = true;
  98102. }
  98103. // try axis 10
  98104. len = aax * aax + aay * aay + aaz * aaz;
  98105. if (len > 1e-5) {
  98106. len = 1 / OIMO.sqrt(len);
  98107. aax *= len;
  98108. aay *= len;
  98109. aaz *= len;
  98110. len = aax * dx + aay * dy + aaz * dz;
  98111. righta = len > 0;
  98112. if (!righta) len = -len;
  98113. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  98114. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  98115. if (dot1 < 0) dot1 = -dot1;
  98116. if (dot2 < 0) dot2 = -dot2;
  98117. len1 = dot1 * w1 + dot2 * d1;
  98118. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  98119. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  98120. if (dot1 < 0) dot1 = -dot1;
  98121. if (dot2 < 0) dot2 = -dot2;
  98122. len2 = dot1 * h2 + dot2 * d2;
  98123. overlapa = len - len1 - len2;
  98124. if (overlapa > 0) return;
  98125. } else {
  98126. righta = false;
  98127. overlapa = 0;
  98128. invalida = true;
  98129. }
  98130. // try axis 11
  98131. len = abx * abx + aby * aby + abz * abz;
  98132. if (len > 1e-5) {
  98133. len = 1 / OIMO.sqrt(len);
  98134. abx *= len;
  98135. aby *= len;
  98136. abz *= len;
  98137. len = abx * dx + aby * dy + abz * dz;
  98138. rightb = len > 0;
  98139. if (!rightb) len = -len;
  98140. dot1 = abx * a1x + aby * a1y + abz * a1z;
  98141. dot2 = abx * a3x + aby * a3y + abz * a3z;
  98142. if (dot1 < 0) dot1 = -dot1;
  98143. if (dot2 < 0) dot2 = -dot2;
  98144. len1 = dot1 * w1 + dot2 * d1;
  98145. dot1 = abx * a4x + aby * a4y + abz * a4z;
  98146. dot2 = abx * a6x + aby * a6y + abz * a6z;
  98147. if (dot1 < 0) dot1 = -dot1;
  98148. if (dot2 < 0) dot2 = -dot2;
  98149. len2 = dot1 * w2 + dot2 * d2;
  98150. overlapb = len - len1 - len2;
  98151. if (overlapb > 0) return;
  98152. } else {
  98153. rightb = false;
  98154. overlapb = 0;
  98155. invalidb = true;
  98156. }
  98157. // try axis 12
  98158. len = acx * acx + acy * acy + acz * acz;
  98159. if (len > 1e-5) {
  98160. len = 1 / OIMO.sqrt(len);
  98161. acx *= len;
  98162. acy *= len;
  98163. acz *= len;
  98164. len = acx * dx + acy * dy + acz * dz;
  98165. rightc = len > 0;
  98166. if (!rightc) len = -len;
  98167. dot1 = acx * a1x + acy * a1y + acz * a1z;
  98168. dot2 = acx * a3x + acy * a3y + acz * a3z;
  98169. if (dot1 < 0) dot1 = -dot1;
  98170. if (dot2 < 0) dot2 = -dot2;
  98171. len1 = dot1 * w1 + dot2 * d1;
  98172. dot1 = acx * a4x + acy * a4y + acz * a4z;
  98173. dot2 = acx * a5x + acy * a5y + acz * a5z;
  98174. if (dot1 < 0) dot1 = -dot1;
  98175. if (dot2 < 0) dot2 = -dot2;
  98176. len2 = dot1 * w2 + dot2 * h2;
  98177. overlapc = len - len1 - len2;
  98178. if (overlapc > 0) return;
  98179. } else {
  98180. rightc = false;
  98181. overlapc = 0;
  98182. invalidc = true;
  98183. }
  98184. // try axis 13
  98185. len = adx * adx + ady * ady + adz * adz;
  98186. if (len > 1e-5) {
  98187. len = 1 / OIMO.sqrt(len);
  98188. adx *= len;
  98189. ady *= len;
  98190. adz *= len;
  98191. len = adx * dx + ady * dy + adz * dz;
  98192. rightd = len > 0;
  98193. if (!rightd) len = -len;
  98194. dot1 = adx * a1x + ady * a1y + adz * a1z;
  98195. dot2 = adx * a2x + ady * a2y + adz * a2z;
  98196. if (dot1 < 0) dot1 = -dot1;
  98197. if (dot2 < 0) dot2 = -dot2;
  98198. len1 = dot1 * w1 + dot2 * h1;
  98199. dot1 = adx * a5x + ady * a5y + adz * a5z;
  98200. dot2 = adx * a6x + ady * a6y + adz * a6z;
  98201. if (dot1 < 0) dot1 = -dot1;
  98202. if (dot2 < 0) dot2 = -dot2;
  98203. len2 = dot1 * h2 + dot2 * d2;
  98204. overlapd = len - len1 - len2;
  98205. if (overlapd > 0) return;
  98206. } else {
  98207. rightd = false;
  98208. overlapd = 0;
  98209. invalidd = true;
  98210. }
  98211. // try axis 14
  98212. len = aex * aex + aey * aey + aez * aez;
  98213. if (len > 1e-5) {
  98214. len = 1 / OIMO.sqrt(len);
  98215. aex *= len;
  98216. aey *= len;
  98217. aez *= len;
  98218. len = aex * dx + aey * dy + aez * dz;
  98219. righte = len > 0;
  98220. if (!righte) len = -len;
  98221. dot1 = aex * a1x + aey * a1y + aez * a1z;
  98222. dot2 = aex * a2x + aey * a2y + aez * a2z;
  98223. if (dot1 < 0) dot1 = -dot1;
  98224. if (dot2 < 0) dot2 = -dot2;
  98225. len1 = dot1 * w1 + dot2 * h1;
  98226. dot1 = aex * a4x + aey * a4y + aez * a4z;
  98227. dot2 = aex * a6x + aey * a6y + aez * a6z;
  98228. if (dot1 < 0) dot1 = -dot1;
  98229. if (dot2 < 0) dot2 = -dot2;
  98230. len2 = dot1 * w2 + dot2 * d2;
  98231. overlape = len - len1 - len2;
  98232. if (overlape > 0) return;
  98233. } else {
  98234. righte = false;
  98235. overlape = 0;
  98236. invalide = true;
  98237. }
  98238. // try axis 15
  98239. len = afx * afx + afy * afy + afz * afz;
  98240. if (len > 1e-5) {
  98241. len = 1 / OIMO.sqrt(len);
  98242. afx *= len;
  98243. afy *= len;
  98244. afz *= len;
  98245. len = afx * dx + afy * dy + afz * dz;
  98246. rightf = len > 0;
  98247. if (!rightf) len = -len;
  98248. dot1 = afx * a1x + afy * a1y + afz * a1z;
  98249. dot2 = afx * a2x + afy * a2y + afz * a2z;
  98250. if (dot1 < 0) dot1 = -dot1;
  98251. if (dot2 < 0) dot2 = -dot2;
  98252. len1 = dot1 * w1 + dot2 * h1;
  98253. dot1 = afx * a4x + afy * a4y + afz * a4z;
  98254. dot2 = afx * a5x + afy * a5y + afz * a5z;
  98255. if (dot1 < 0) dot1 = -dot1;
  98256. if (dot2 < 0) dot2 = -dot2;
  98257. len2 = dot1 * w2 + dot2 * h2;
  98258. overlapf = len - len1 - len2;
  98259. if (overlapf > 0) return;
  98260. } else {
  98261. rightf = false;
  98262. overlapf = 0;
  98263. invalidf = true;
  98264. }
  98265. // boxes are overlapping
  98266. var depth = overlap1;
  98267. var depth2 = overlap1;
  98268. var minIndex = 0;
  98269. var right = right1;
  98270. if (overlap2 > depth2) {
  98271. depth = overlap2;
  98272. depth2 = overlap2;
  98273. minIndex = 1;
  98274. right = right2;
  98275. }
  98276. if (overlap3 > depth2) {
  98277. depth = overlap3;
  98278. depth2 = overlap3;
  98279. minIndex = 2;
  98280. right = right3;
  98281. }
  98282. if (overlap4 > depth2) {
  98283. depth = overlap4;
  98284. depth2 = overlap4;
  98285. minIndex = 3;
  98286. right = right4;
  98287. }
  98288. if (overlap5 > depth2) {
  98289. depth = overlap5;
  98290. depth2 = overlap5;
  98291. minIndex = 4;
  98292. right = right5;
  98293. }
  98294. if (overlap6 > depth2) {
  98295. depth = overlap6;
  98296. depth2 = overlap6;
  98297. minIndex = 5;
  98298. right = right6;
  98299. }
  98300. if (overlap7 - 0.01 > depth2 && !invalid7) {
  98301. depth = overlap7;
  98302. depth2 = overlap7 - 0.01;
  98303. minIndex = 6;
  98304. right = right7;
  98305. }
  98306. if (overlap8 - 0.01 > depth2 && !invalid8) {
  98307. depth = overlap8;
  98308. depth2 = overlap8 - 0.01;
  98309. minIndex = 7;
  98310. right = right8;
  98311. }
  98312. if (overlap9 - 0.01 > depth2 && !invalid9) {
  98313. depth = overlap9;
  98314. depth2 = overlap9 - 0.01;
  98315. minIndex = 8;
  98316. right = right9;
  98317. }
  98318. if (overlapa - 0.01 > depth2 && !invalida) {
  98319. depth = overlapa;
  98320. depth2 = overlapa - 0.01;
  98321. minIndex = 9;
  98322. right = righta;
  98323. }
  98324. if (overlapb - 0.01 > depth2 && !invalidb) {
  98325. depth = overlapb;
  98326. depth2 = overlapb - 0.01;
  98327. minIndex = 10;
  98328. right = rightb;
  98329. }
  98330. if (overlapc - 0.01 > depth2 && !invalidc) {
  98331. depth = overlapc;
  98332. depth2 = overlapc - 0.01;
  98333. minIndex = 11;
  98334. right = rightc;
  98335. }
  98336. if (overlapd - 0.01 > depth2 && !invalidd) {
  98337. depth = overlapd;
  98338. depth2 = overlapd - 0.01;
  98339. minIndex = 12;
  98340. right = rightd;
  98341. }
  98342. if (overlape - 0.01 > depth2 && !invalide) {
  98343. depth = overlape;
  98344. depth2 = overlape - 0.01;
  98345. minIndex = 13;
  98346. right = righte;
  98347. }
  98348. if (overlapf - 0.01 > depth2 && !invalidf) {
  98349. depth = overlapf;
  98350. minIndex = 14;
  98351. right = rightf;
  98352. }
  98353. // normal
  98354. var nx = 0;
  98355. var ny = 0;
  98356. var nz = 0;
  98357. // edge line or face side normal
  98358. var n1x = 0;
  98359. var n1y = 0;
  98360. var n1z = 0;
  98361. var n2x = 0;
  98362. var n2y = 0;
  98363. var n2z = 0;
  98364. // center of current face
  98365. var cx = 0;
  98366. var cy = 0;
  98367. var cz = 0;
  98368. // face side
  98369. var s1x = 0;
  98370. var s1y = 0;
  98371. var s1z = 0;
  98372. var s2x = 0;
  98373. var s2y = 0;
  98374. var s2z = 0;
  98375. // swap b1 b2
  98376. var swap = false;
  98377. //_______________________________________
  98378. if (minIndex == 0) {// b1.x * b2
  98379. if (right) {
  98380. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  98381. nx = a1x; ny = a1y; nz = a1z;
  98382. } else {
  98383. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  98384. nx = -a1x; ny = -a1y; nz = -a1z;
  98385. }
  98386. s1x = d2x; s1y = d2y; s1z = d2z;
  98387. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  98388. s2x = d3x; s2y = d3y; s2z = d3z;
  98389. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  98390. }
  98391. else if (minIndex == 1) {// b1.y * b2
  98392. if (right) {
  98393. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  98394. nx = a2x; ny = a2y; nz = a2z;
  98395. } else {
  98396. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  98397. nx = -a2x; ny = -a2y; nz = -a2z;
  98398. }
  98399. s1x = d1x; s1y = d1y; s1z = d1z;
  98400. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  98401. s2x = d3x; s2y = d3y; s2z = d3z;
  98402. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  98403. }
  98404. else if (minIndex == 2) {// b1.z * b2
  98405. if (right) {
  98406. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  98407. nx = a3x; ny = a3y; nz = a3z;
  98408. } else {
  98409. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  98410. nx = -a3x; ny = -a3y; nz = -a3z;
  98411. }
  98412. s1x = d1x; s1y = d1y; s1z = d1z;
  98413. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  98414. s2x = d2x; s2y = d2y; s2z = d2z;
  98415. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  98416. }
  98417. else if (minIndex == 3) {// b2.x * b1
  98418. swap = true;
  98419. if (!right) {
  98420. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  98421. nx = a4x; ny = a4y; nz = a4z;
  98422. } else {
  98423. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  98424. nx = -a4x; ny = -a4y; nz = -a4z;
  98425. }
  98426. s1x = d5x; s1y = d5y; s1z = d5z;
  98427. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  98428. s2x = d6x; s2y = d6y; s2z = d6z;
  98429. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  98430. }
  98431. else if (minIndex == 4) {// b2.y * b1
  98432. swap = true;
  98433. if (!right) {
  98434. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  98435. nx = a5x; ny = a5y; nz = a5z;
  98436. } else {
  98437. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  98438. nx = -a5x; ny = -a5y; nz = -a5z;
  98439. }
  98440. s1x = d4x; s1y = d4y; s1z = d4z;
  98441. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  98442. s2x = d6x; s2y = d6y; s2z = d6z;
  98443. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  98444. }
  98445. else if (minIndex == 5) {// b2.z * b1
  98446. swap = true;
  98447. if (!right) {
  98448. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  98449. nx = a6x; ny = a6y; nz = a6z;
  98450. } else {
  98451. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  98452. nx = -a6x; ny = -a6y; nz = -a6z;
  98453. }
  98454. s1x = d4x; s1y = d4y; s1z = d4z;
  98455. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  98456. s2x = d5x; s2y = d5y; s2z = d5z;
  98457. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  98458. }
  98459. else if (minIndex == 6) {// b1.x * b2.x
  98460. nx = a7x; ny = a7y; nz = a7z;
  98461. n1x = a1x; n1y = a1y; n1z = a1z;
  98462. n2x = a4x; n2y = a4y; n2z = a4z;
  98463. }
  98464. else if (minIndex == 7) {// b1.x * b2.y
  98465. nx = a8x; ny = a8y; nz = a8z;
  98466. n1x = a1x; n1y = a1y; n1z = a1z;
  98467. n2x = a5x; n2y = a5y; n2z = a5z;
  98468. }
  98469. else if (minIndex == 8) {// b1.x * b2.z
  98470. nx = a9x; ny = a9y; nz = a9z;
  98471. n1x = a1x; n1y = a1y; n1z = a1z;
  98472. n2x = a6x; n2y = a6y; n2z = a6z;
  98473. }
  98474. else if (minIndex == 9) {// b1.y * b2.x
  98475. nx = aax; ny = aay; nz = aaz;
  98476. n1x = a2x; n1y = a2y; n1z = a2z;
  98477. n2x = a4x; n2y = a4y; n2z = a4z
  98478. }
  98479. else if (minIndex == 10) {// b1.y * b2.y
  98480. nx = abx; ny = aby; nz = abz;
  98481. n1x = a2x; n1y = a2y; n1z = a2z;
  98482. n2x = a5x; n2y = a5y; n2z = a5z;
  98483. }
  98484. else if (minIndex == 11) {// b1.y * b2.z
  98485. nx = acx; ny = acy; nz = acz;
  98486. n1x = a2x; n1y = a2y; n1z = a2z;
  98487. n2x = a6x; n2y = a6y; n2z = a6z;
  98488. }
  98489. else if (minIndex == 12) {// b1.z * b2.x
  98490. nx = adx; ny = ady; nz = adz;
  98491. n1x = a3x; n1y = a3y; n1z = a3z;
  98492. n2x = a4x; n2y = a4y; n2z = a4z;
  98493. }
  98494. else if (minIndex == 13) {// b1.z * b2.y
  98495. nx = aex; ny = aey; nz = aez;
  98496. n1x = a3x; n1y = a3y; n1z = a3z;
  98497. n2x = a5x; n2y = a5y; n2z = a5z;
  98498. }
  98499. else if (minIndex == 14) {// b1.z * b2.z
  98500. nx = afx; ny = afy; nz = afz;
  98501. n1x = a3x; n1y = a3y; n1z = a3z;
  98502. n2x = a6x; n2y = a6y; n2z = a6z;
  98503. }
  98504. //__________________________________________
  98505. var v;
  98506. if (minIndex > 5) {
  98507. if (!right) {
  98508. nx = -nx; ny = -ny; nz = -nz;
  98509. }
  98510. var distance;
  98511. var maxDistance;
  98512. var vx;
  98513. var vy;
  98514. var vz;
  98515. var v1x;
  98516. var v1y;
  98517. var v1z;
  98518. var v2x;
  98519. var v2y;
  98520. var v2z;
  98521. //vertex1;
  98522. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  98523. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  98524. //vertex2;
  98525. vx = V1[3]; vy = V1[4]; vz = V1[5];
  98526. distance = nx * vx + ny * vy + nz * vz;
  98527. if (distance > maxDistance) {
  98528. maxDistance = distance;
  98529. v1x = vx; v1y = vy; v1z = vz;
  98530. }
  98531. //vertex3;
  98532. vx = V1[6]; vy = V1[7]; vz = V1[8];
  98533. distance = nx * vx + ny * vy + nz * vz;
  98534. if (distance > maxDistance) {
  98535. maxDistance = distance;
  98536. v1x = vx; v1y = vy; v1z = vz;
  98537. }
  98538. //vertex4;
  98539. vx = V1[9]; vy = V1[10]; vz = V1[11];
  98540. distance = nx * vx + ny * vy + nz * vz;
  98541. if (distance > maxDistance) {
  98542. maxDistance = distance;
  98543. v1x = vx; v1y = vy; v1z = vz;
  98544. }
  98545. //vertex5;
  98546. vx = V1[12]; vy = V1[13]; vz = V1[14];
  98547. distance = nx * vx + ny * vy + nz * vz;
  98548. if (distance > maxDistance) {
  98549. maxDistance = distance;
  98550. v1x = vx; v1y = vy; v1z = vz;
  98551. }
  98552. //vertex6;
  98553. vx = V1[15]; vy = V1[16]; vz = V1[17];
  98554. distance = nx * vx + ny * vy + nz * vz;
  98555. if (distance > maxDistance) {
  98556. maxDistance = distance;
  98557. v1x = vx; v1y = vy; v1z = vz;
  98558. }
  98559. //vertex7;
  98560. vx = V1[18]; vy = V1[19]; vz = V1[20];
  98561. distance = nx * vx + ny * vy + nz * vz;
  98562. if (distance > maxDistance) {
  98563. maxDistance = distance;
  98564. v1x = vx; v1y = vy; v1z = vz;
  98565. }
  98566. //vertex8;
  98567. vx = V1[21]; vy = V1[22]; vz = V1[23];
  98568. distance = nx * vx + ny * vy + nz * vz;
  98569. if (distance > maxDistance) {
  98570. maxDistance = distance;
  98571. v1x = vx; v1y = vy; v1z = vz;
  98572. }
  98573. //vertex1;
  98574. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  98575. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  98576. //vertex2;
  98577. vx = V2[3]; vy = V2[4]; vz = V2[5];
  98578. distance = nx * vx + ny * vy + nz * vz;
  98579. if (distance < maxDistance) {
  98580. maxDistance = distance;
  98581. v2x = vx; v2y = vy; v2z = vz;
  98582. }
  98583. //vertex3;
  98584. vx = V2[6]; vy = V2[7]; vz = V2[8];
  98585. distance = nx * vx + ny * vy + nz * vz;
  98586. if (distance < maxDistance) {
  98587. maxDistance = distance;
  98588. v2x = vx; v2y = vy; v2z = vz;
  98589. }
  98590. //vertex4;
  98591. vx = V2[9]; vy = V2[10]; vz = V2[11];
  98592. distance = nx * vx + ny * vy + nz * vz;
  98593. if (distance < maxDistance) {
  98594. maxDistance = distance;
  98595. v2x = vx; v2y = vy; v2z = vz;
  98596. }
  98597. //vertex5;
  98598. vx = V2[12]; vy = V2[13]; vz = V2[14];
  98599. distance = nx * vx + ny * vy + nz * vz;
  98600. if (distance < maxDistance) {
  98601. maxDistance = distance;
  98602. v2x = vx; v2y = vy; v2z = vz;
  98603. }
  98604. //vertex6;
  98605. vx = V2[15]; vy = V2[16]; vz = V2[17];
  98606. distance = nx * vx + ny * vy + nz * vz;
  98607. if (distance < maxDistance) {
  98608. maxDistance = distance;
  98609. v2x = vx; v2y = vy; v2z = vz;
  98610. }
  98611. //vertex7;
  98612. vx = V2[18]; vy = V2[19]; vz = V2[20];
  98613. distance = nx * vx + ny * vy + nz * vz;
  98614. if (distance < maxDistance) {
  98615. maxDistance = distance;
  98616. v2x = vx; v2y = vy; v2z = vz;
  98617. }
  98618. //vertex8;
  98619. vx = V2[21]; vy = V2[22]; vz = V2[23];
  98620. distance = nx * vx + ny * vy + nz * vz;
  98621. if (distance < maxDistance) {
  98622. maxDistance = distance;
  98623. v2x = vx; v2y = vy; v2z = vz;
  98624. }
  98625. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  98626. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  98627. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  98628. 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);
  98629. return;
  98630. }
  98631. // now detect face-face collision...
  98632. // target quad
  98633. var q1x;
  98634. var q1y;
  98635. var q1z;
  98636. var q2x;
  98637. var q2y;
  98638. var q2z;
  98639. var q3x;
  98640. var q3y;
  98641. var q3z;
  98642. var q4x;
  98643. var q4y;
  98644. var q4z;
  98645. // search support face and vertex
  98646. var minDot = 1;
  98647. var dot = 0;
  98648. var minDotIndex = 0;
  98649. if (swap) {
  98650. dot = a1x * nx + a1y * ny + a1z * nz;
  98651. if (dot < minDot) {
  98652. minDot = dot;
  98653. minDotIndex = 0;
  98654. }
  98655. if (-dot < minDot) {
  98656. minDot = -dot;
  98657. minDotIndex = 1;
  98658. }
  98659. dot = a2x * nx + a2y * ny + a2z * nz;
  98660. if (dot < minDot) {
  98661. minDot = dot;
  98662. minDotIndex = 2;
  98663. }
  98664. if (-dot < minDot) {
  98665. minDot = -dot;
  98666. minDotIndex = 3;
  98667. }
  98668. dot = a3x * nx + a3y * ny + a3z * nz;
  98669. if (dot < minDot) {
  98670. minDot = dot;
  98671. minDotIndex = 4;
  98672. }
  98673. if (-dot < minDot) {
  98674. minDot = -dot;
  98675. minDotIndex = 5;
  98676. }
  98677. if (minDotIndex == 0) {// x+ face
  98678. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  98679. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  98680. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  98681. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  98682. }
  98683. else if (minDotIndex == 1) {// x- face
  98684. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  98685. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  98686. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  98687. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  98688. }
  98689. else if (minDotIndex == 2) {// y+ face
  98690. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  98691. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  98692. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  98693. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  98694. }
  98695. else if (minDotIndex == 3) {// y- face
  98696. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  98697. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  98698. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  98699. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  98700. }
  98701. else if (minDotIndex == 4) {// z+ face
  98702. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  98703. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  98704. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  98705. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  98706. }
  98707. else if (minDotIndex == 5) {// z- face
  98708. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  98709. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  98710. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  98711. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  98712. }
  98713. } else {
  98714. dot = a4x * nx + a4y * ny + a4z * nz;
  98715. if (dot < minDot) {
  98716. minDot = dot;
  98717. minDotIndex = 0;
  98718. }
  98719. if (-dot < minDot) {
  98720. minDot = -dot;
  98721. minDotIndex = 1;
  98722. }
  98723. dot = a5x * nx + a5y * ny + a5z * nz;
  98724. if (dot < minDot) {
  98725. minDot = dot;
  98726. minDotIndex = 2;
  98727. }
  98728. if (-dot < minDot) {
  98729. minDot = -dot;
  98730. minDotIndex = 3;
  98731. }
  98732. dot = a6x * nx + a6y * ny + a6z * nz;
  98733. if (dot < minDot) {
  98734. minDot = dot;
  98735. minDotIndex = 4;
  98736. }
  98737. if (-dot < minDot) {
  98738. minDot = -dot;
  98739. minDotIndex = 5;
  98740. }
  98741. //______________________________________________________
  98742. if (minDotIndex == 0) {// x+ face
  98743. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  98744. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  98745. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  98746. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  98747. }
  98748. else if (minDotIndex == 1) {// x- face
  98749. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  98750. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  98751. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  98752. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  98753. }
  98754. else if (minDotIndex == 2) {// y+ face
  98755. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  98756. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  98757. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  98758. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  98759. }
  98760. else if (minDotIndex == 3) {// y- face
  98761. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  98762. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  98763. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  98764. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  98765. }
  98766. else if (minDotIndex == 4) {// z+ face
  98767. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  98768. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  98769. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  98770. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  98771. }
  98772. else if (minDotIndex == 5) {// z- face
  98773. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  98774. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  98775. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  98776. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  98777. }
  98778. }
  98779. // clip vertices
  98780. var numClipVertices;
  98781. var numAddedClipVertices;
  98782. var index;
  98783. var x1;
  98784. var y1;
  98785. var z1;
  98786. var x2;
  98787. var y2;
  98788. var z2;
  98789. this.clipVertices1[0] = q1x;
  98790. this.clipVertices1[1] = q1y;
  98791. this.clipVertices1[2] = q1z;
  98792. this.clipVertices1[3] = q2x;
  98793. this.clipVertices1[4] = q2y;
  98794. this.clipVertices1[5] = q2z;
  98795. this.clipVertices1[6] = q3x;
  98796. this.clipVertices1[7] = q3y;
  98797. this.clipVertices1[8] = q3z;
  98798. this.clipVertices1[9] = q4x;
  98799. this.clipVertices1[10] = q4y;
  98800. this.clipVertices1[11] = q4z;
  98801. numAddedClipVertices = 0;
  98802. x1 = this.clipVertices1[9];
  98803. y1 = this.clipVertices1[10];
  98804. z1 = this.clipVertices1[11];
  98805. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  98806. //var i = 4;
  98807. //while(i--){
  98808. for (var i = 0; i < 4; i++) {
  98809. index = i * 3;
  98810. x2 = this.clipVertices1[index];
  98811. y2 = this.clipVertices1[index + 1];
  98812. z2 = this.clipVertices1[index + 2];
  98813. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  98814. if (dot1 > 0) {
  98815. if (dot2 > 0) {
  98816. index = numAddedClipVertices * 3;
  98817. numAddedClipVertices++;
  98818. this.clipVertices2[index] = x2;
  98819. this.clipVertices2[index + 1] = y2;
  98820. this.clipVertices2[index + 2] = z2;
  98821. } else {
  98822. index = numAddedClipVertices * 3;
  98823. numAddedClipVertices++;
  98824. t = dot1 / (dot1 - dot2);
  98825. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  98826. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  98827. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  98828. }
  98829. } else {
  98830. if (dot2 > 0) {
  98831. index = numAddedClipVertices * 3;
  98832. numAddedClipVertices++;
  98833. t = dot1 / (dot1 - dot2);
  98834. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  98835. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  98836. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  98837. index = numAddedClipVertices * 3;
  98838. numAddedClipVertices++;
  98839. this.clipVertices2[index] = x2;
  98840. this.clipVertices2[index + 1] = y2;
  98841. this.clipVertices2[index + 2] = z2;
  98842. }
  98843. }
  98844. x1 = x2;
  98845. y1 = y2;
  98846. z1 = z2;
  98847. dot1 = dot2;
  98848. }
  98849. numClipVertices = numAddedClipVertices;
  98850. if (numClipVertices == 0) return;
  98851. numAddedClipVertices = 0;
  98852. index = (numClipVertices - 1) * 3;
  98853. x1 = this.clipVertices2[index];
  98854. y1 = this.clipVertices2[index + 1];
  98855. z1 = this.clipVertices2[index + 2];
  98856. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  98857. //i = numClipVertices;
  98858. //while(i--){
  98859. for (i = 0; i < numClipVertices; i++) {
  98860. index = i * 3;
  98861. x2 = this.clipVertices2[index];
  98862. y2 = this.clipVertices2[index + 1];
  98863. z2 = this.clipVertices2[index + 2];
  98864. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  98865. if (dot1 > 0) {
  98866. if (dot2 > 0) {
  98867. index = numAddedClipVertices * 3;
  98868. numAddedClipVertices++;
  98869. this.clipVertices1[index] = x2;
  98870. this.clipVertices1[index + 1] = y2;
  98871. this.clipVertices1[index + 2] = z2;
  98872. } else {
  98873. index = numAddedClipVertices * 3;
  98874. numAddedClipVertices++;
  98875. t = dot1 / (dot1 - dot2);
  98876. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  98877. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  98878. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  98879. }
  98880. } else {
  98881. if (dot2 > 0) {
  98882. index = numAddedClipVertices * 3;
  98883. numAddedClipVertices++;
  98884. t = dot1 / (dot1 - dot2);
  98885. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  98886. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  98887. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  98888. index = numAddedClipVertices * 3;
  98889. numAddedClipVertices++;
  98890. this.clipVertices1[index] = x2;
  98891. this.clipVertices1[index + 1] = y2;
  98892. this.clipVertices1[index + 2] = z2;
  98893. }
  98894. }
  98895. x1 = x2;
  98896. y1 = y2;
  98897. z1 = z2;
  98898. dot1 = dot2;
  98899. }
  98900. numClipVertices = numAddedClipVertices;
  98901. if (numClipVertices == 0) return;
  98902. numAddedClipVertices = 0;
  98903. index = (numClipVertices - 1) * 3;
  98904. x1 = this.clipVertices1[index];
  98905. y1 = this.clipVertices1[index + 1];
  98906. z1 = this.clipVertices1[index + 2];
  98907. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  98908. //i = numClipVertices;
  98909. //while(i--){
  98910. for (i = 0; i < numClipVertices; i++) {
  98911. index = i * 3;
  98912. x2 = this.clipVertices1[index];
  98913. y2 = this.clipVertices1[index + 1];
  98914. z2 = this.clipVertices1[index + 2];
  98915. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  98916. if (dot1 > 0) {
  98917. if (dot2 > 0) {
  98918. index = numAddedClipVertices * 3;
  98919. numAddedClipVertices++;
  98920. this.clipVertices2[index] = x2;
  98921. this.clipVertices2[index + 1] = y2;
  98922. this.clipVertices2[index + 2] = z2;
  98923. } else {
  98924. index = numAddedClipVertices * 3;
  98925. numAddedClipVertices++;
  98926. t = dot1 / (dot1 - dot2);
  98927. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  98928. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  98929. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  98930. }
  98931. } else {
  98932. if (dot2 > 0) {
  98933. index = numAddedClipVertices * 3;
  98934. numAddedClipVertices++;
  98935. t = dot1 / (dot1 - dot2);
  98936. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  98937. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  98938. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  98939. index = numAddedClipVertices * 3;
  98940. numAddedClipVertices++;
  98941. this.clipVertices2[index] = x2;
  98942. this.clipVertices2[index + 1] = y2;
  98943. this.clipVertices2[index + 2] = z2;
  98944. }
  98945. }
  98946. x1 = x2;
  98947. y1 = y2;
  98948. z1 = z2;
  98949. dot1 = dot2;
  98950. }
  98951. numClipVertices = numAddedClipVertices;
  98952. if (numClipVertices == 0) return;
  98953. numAddedClipVertices = 0;
  98954. index = (numClipVertices - 1) * 3;
  98955. x1 = this.clipVertices2[index];
  98956. y1 = this.clipVertices2[index + 1];
  98957. z1 = this.clipVertices2[index + 2];
  98958. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  98959. //i = numClipVertices;
  98960. //while(i--){
  98961. for (i = 0; i < numClipVertices; i++) {
  98962. index = i * 3;
  98963. x2 = this.clipVertices2[index];
  98964. y2 = this.clipVertices2[index + 1];
  98965. z2 = this.clipVertices2[index + 2];
  98966. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  98967. if (dot1 > 0) {
  98968. if (dot2 > 0) {
  98969. index = numAddedClipVertices * 3;
  98970. numAddedClipVertices++;
  98971. this.clipVertices1[index] = x2;
  98972. this.clipVertices1[index + 1] = y2;
  98973. this.clipVertices1[index + 2] = z2;
  98974. } else {
  98975. index = numAddedClipVertices * 3;
  98976. numAddedClipVertices++;
  98977. t = dot1 / (dot1 - dot2);
  98978. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  98979. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  98980. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  98981. }
  98982. } else {
  98983. if (dot2 > 0) {
  98984. index = numAddedClipVertices * 3;
  98985. numAddedClipVertices++;
  98986. t = dot1 / (dot1 - dot2);
  98987. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  98988. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  98989. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  98990. index = numAddedClipVertices * 3;
  98991. numAddedClipVertices++;
  98992. this.clipVertices1[index] = x2;
  98993. this.clipVertices1[index + 1] = y2;
  98994. this.clipVertices1[index + 2] = z2;
  98995. }
  98996. }
  98997. x1 = x2;
  98998. y1 = y2;
  98999. z1 = z2;
  99000. dot1 = dot2;
  99001. }
  99002. numClipVertices = numAddedClipVertices;
  99003. if (swap) {
  99004. var tb = b1;
  99005. b1 = b2;
  99006. b2 = tb;
  99007. }
  99008. if (numClipVertices == 0) return;
  99009. var flipped = b1 != shape1;
  99010. if (numClipVertices > 4) {
  99011. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  99012. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  99013. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  99014. n1x = q1x - x1;
  99015. n1y = q1y - y1;
  99016. n1z = q1z - z1;
  99017. n2x = q2x - x1;
  99018. n2y = q2y - y1;
  99019. n2z = q2z - z1;
  99020. var index1 = 0;
  99021. var index2 = 0;
  99022. var index3 = 0;
  99023. var index4 = 0;
  99024. var maxDot = -this.INF;
  99025. minDot = this.INF;
  99026. //i = numClipVertices;
  99027. //while(i--){
  99028. for (i = 0; i < numClipVertices; i++) {
  99029. this.used[i] = false;
  99030. index = i * 3;
  99031. x1 = this.clipVertices1[index];
  99032. y1 = this.clipVertices1[index + 1];
  99033. z1 = this.clipVertices1[index + 2];
  99034. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  99035. if (dot < minDot) {
  99036. minDot = dot;
  99037. index1 = i;
  99038. }
  99039. if (dot > maxDot) {
  99040. maxDot = dot;
  99041. index3 = i;
  99042. }
  99043. }
  99044. this.used[index1] = true;
  99045. this.used[index3] = true;
  99046. maxDot = -this.INF;
  99047. minDot = this.INF;
  99048. //i = numClipVertices;
  99049. //while(i--){
  99050. for (i = 0; i < numClipVertices; i++) {
  99051. if (this.used[i]) continue;
  99052. index = i * 3;
  99053. x1 = this.clipVertices1[index];
  99054. y1 = this.clipVertices1[index + 1];
  99055. z1 = this.clipVertices1[index + 2];
  99056. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  99057. if (dot < minDot) {
  99058. minDot = dot;
  99059. index2 = i;
  99060. }
  99061. if (dot > maxDot) {
  99062. maxDot = dot;
  99063. index4 = i;
  99064. }
  99065. }
  99066. index = index1 * 3;
  99067. x1 = this.clipVertices1[index];
  99068. y1 = this.clipVertices1[index + 1];
  99069. z1 = this.clipVertices1[index + 2];
  99070. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99071. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99072. index = index2 * 3;
  99073. x1 = this.clipVertices1[index];
  99074. y1 = this.clipVertices1[index + 1];
  99075. z1 = this.clipVertices1[index + 2];
  99076. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99077. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99078. index = index3 * 3;
  99079. x1 = this.clipVertices1[index];
  99080. y1 = this.clipVertices1[index + 1];
  99081. z1 = this.clipVertices1[index + 2];
  99082. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99083. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99084. index = index4 * 3;
  99085. x1 = this.clipVertices1[index];
  99086. y1 = this.clipVertices1[index + 1];
  99087. z1 = this.clipVertices1[index + 2];
  99088. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99089. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99090. } else {
  99091. //i = numClipVertices;
  99092. //while(i--){
  99093. for (i = 0; i < numClipVertices; i++) {
  99094. index = i * 3;
  99095. x1 = this.clipVertices1[index];
  99096. y1 = this.clipVertices1[index + 1];
  99097. z1 = this.clipVertices1[index + 2];
  99098. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99099. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99100. }
  99101. }
  99102. };
  99103. /**
  99104. * A collision detector which detects collisions between sphere and box.
  99105. * @author saharan
  99106. */
  99107. OIMO.SphereBoxCollisionDetector = function (flip) {
  99108. OIMO.CollisionDetector.call(this);
  99109. this.flip = flip;
  99110. };
  99111. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99112. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  99113. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99114. var s;
  99115. var b;
  99116. if (this.flip) {
  99117. s = (shape2);
  99118. b = (shape1);
  99119. } else {
  99120. s = (shape1);
  99121. b = (shape2);
  99122. }
  99123. var D = b.dimentions;
  99124. var ps = s.position;
  99125. var psx = ps.x;
  99126. var psy = ps.y;
  99127. var psz = ps.z;
  99128. var pb = b.position;
  99129. var pbx = pb.x;
  99130. var pby = pb.y;
  99131. var pbz = pb.z;
  99132. var rad = s.radius;
  99133. var hw = b.halfWidth;
  99134. var hh = b.halfHeight;
  99135. var hd = b.halfDepth;
  99136. var dx = psx - pbx;
  99137. var dy = psy - pby;
  99138. var dz = psz - pbz;
  99139. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  99140. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  99141. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  99142. var cx;
  99143. var cy;
  99144. var cz;
  99145. var len;
  99146. var invLen;
  99147. var overlap = 0;
  99148. if (sx > hw) {
  99149. sx = hw;
  99150. } else if (sx < -hw) {
  99151. sx = -hw;
  99152. } else {
  99153. overlap = 1;
  99154. }
  99155. if (sy > hh) {
  99156. sy = hh;
  99157. } else if (sy < -hh) {
  99158. sy = -hh;
  99159. } else {
  99160. overlap |= 2;
  99161. }
  99162. if (sz > hd) {
  99163. sz = hd;
  99164. } else if (sz < -hd) {
  99165. sz = -hd;
  99166. } else {
  99167. overlap |= 4;
  99168. }
  99169. if (overlap == 7) {
  99170. // center of sphere is in the box
  99171. if (sx < 0) {
  99172. dx = hw + sx;
  99173. } else {
  99174. dx = hw - sx;
  99175. }
  99176. if (sy < 0) {
  99177. dy = hh + sy;
  99178. } else {
  99179. dy = hh - sy;
  99180. }
  99181. if (sz < 0) {
  99182. dz = hd + sz;
  99183. } else {
  99184. dz = hd - sz;
  99185. }
  99186. if (dx < dy) {
  99187. if (dx < dz) {
  99188. len = dx - hw;
  99189. if (sx < 0) {
  99190. sx = -hw;
  99191. dx = D[0];
  99192. dy = D[1];
  99193. dz = D[2];
  99194. } else {
  99195. sx = hw;
  99196. dx = -D[0];
  99197. dy = -D[1];
  99198. dz = -D[2];
  99199. }
  99200. } else {
  99201. len = dz - hd;
  99202. if (sz < 0) {
  99203. sz = -hd;
  99204. dx = D[6];
  99205. dy = D[7];
  99206. dz = D[8];
  99207. } else {
  99208. sz = hd;
  99209. dx = -D[6];
  99210. dy = -D[7];
  99211. dz = -D[8];
  99212. }
  99213. }
  99214. } else {
  99215. if (dy < dz) {
  99216. len = dy - hh;
  99217. if (sy < 0) {
  99218. sy = -hh;
  99219. dx = D[3];
  99220. dy = D[4];
  99221. dz = D[5];
  99222. } else {
  99223. sy = hh;
  99224. dx = -D[3];
  99225. dy = -D[4];
  99226. dz = -D[5];
  99227. }
  99228. } else {
  99229. len = dz - hd;
  99230. if (sz < 0) {
  99231. sz = -hd;
  99232. dx = D[6];
  99233. dy = D[7];
  99234. dz = D[8];
  99235. } else {
  99236. sz = hd;
  99237. dx = -D[6];
  99238. dy = -D[7];
  99239. dz = -D[8];
  99240. }
  99241. }
  99242. }
  99243. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  99244. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  99245. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  99246. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  99247. } else {
  99248. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  99249. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  99250. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  99251. dx = cx - ps.x;
  99252. dy = cy - ps.y;
  99253. dz = cz - ps.z;
  99254. len = dx * dx + dy * dy + dz * dz;
  99255. if (len > 0 && len < rad * rad) {
  99256. len = OIMO.sqrt(len);
  99257. invLen = 1 / len;
  99258. dx *= invLen;
  99259. dy *= invLen;
  99260. dz *= invLen;
  99261. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  99262. }
  99263. }
  99264. };
  99265. /**
  99266. * A collision detector which detects collisions between two spheres.
  99267. * @author saharan
  99268. */
  99269. OIMO.SphereSphereCollisionDetector = function () {
  99270. OIMO.CollisionDetector.call(this);
  99271. };
  99272. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99273. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  99274. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99275. var s1 = shape1;
  99276. var s2 = shape2;
  99277. var p1 = s1.position;
  99278. var p2 = s2.position;
  99279. var dx = p2.x - p1.x;
  99280. var dy = p2.y - p1.y;
  99281. var dz = p2.z - p1.z;
  99282. var len = dx * dx + dy * dy + dz * dz;
  99283. var r1 = s1.radius;
  99284. var r2 = s2.radius;
  99285. var rad = r1 + r2;
  99286. if (len > 0 && len < rad * rad) {
  99287. len = OIMO.sqrt(len);
  99288. var invLen = 1 / len;
  99289. dx *= invLen;
  99290. dy *= invLen;
  99291. dz *= invLen;
  99292. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  99293. }
  99294. };
  99295. OIMO.BoxCylinderCollisionDetector = function (flip) {
  99296. OIMO.CollisionDetector.call(this);
  99297. this.flip = flip;
  99298. };
  99299. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99300. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  99301. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  99302. var t1x;
  99303. var t1y;
  99304. var t1z;
  99305. var t2x;
  99306. var t2y;
  99307. var t2z;
  99308. var sup = new OIMO.Vec3();
  99309. var len;
  99310. var p1x;
  99311. var p1y;
  99312. var p1z;
  99313. var p2x;
  99314. var p2y;
  99315. var p2z;
  99316. var v01x = c1.position.x;
  99317. var v01y = c1.position.y;
  99318. var v01z = c1.position.z;
  99319. var v02x = c2.position.x;
  99320. var v02y = c2.position.y;
  99321. var v02z = c2.position.z;
  99322. var v0x = v02x - v01x;
  99323. var v0y = v02y - v01y;
  99324. var v0z = v02z - v01z;
  99325. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  99326. var nx = -v0x;
  99327. var ny = -v0y;
  99328. var nz = -v0z;
  99329. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99330. var v11x = sup.x;
  99331. var v11y = sup.y;
  99332. var v11z = sup.z;
  99333. this.supportPointC(c2, nx, ny, nz, sup);
  99334. var v12x = sup.x;
  99335. var v12y = sup.y;
  99336. var v12z = sup.z;
  99337. var v1x = v12x - v11x;
  99338. var v1y = v12y - v11y;
  99339. var v1z = v12z - v11z;
  99340. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  99341. return false;
  99342. }
  99343. nx = v1y * v0z - v1z * v0y;
  99344. ny = v1z * v0x - v1x * v0z;
  99345. nz = v1x * v0y - v1y * v0x;
  99346. if (nx * nx + ny * ny + nz * nz == 0) {
  99347. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  99348. sep.normalize(sep);
  99349. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  99350. return true;
  99351. }
  99352. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99353. var v21x = sup.x;
  99354. var v21y = sup.y;
  99355. var v21z = sup.z;
  99356. this.supportPointC(c2, nx, ny, nz, sup);
  99357. var v22x = sup.x;
  99358. var v22y = sup.y;
  99359. var v22z = sup.z;
  99360. var v2x = v22x - v21x;
  99361. var v2y = v22y - v21y;
  99362. var v2z = v22z - v21z;
  99363. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  99364. return false;
  99365. }
  99366. t1x = v1x - v0x;
  99367. t1y = v1y - v0y;
  99368. t1z = v1z - v0z;
  99369. t2x = v2x - v0x;
  99370. t2y = v2y - v0y;
  99371. t2z = v2z - v0z;
  99372. nx = t1y * t2z - t1z * t2y;
  99373. ny = t1z * t2x - t1x * t2z;
  99374. nz = t1x * t2y - t1y * t2x;
  99375. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  99376. t1x = v1x;
  99377. t1y = v1y;
  99378. t1z = v1z;
  99379. v1x = v2x;
  99380. v1y = v2y;
  99381. v1z = v2z;
  99382. v2x = t1x;
  99383. v2y = t1y;
  99384. v2z = t1z;
  99385. t1x = v11x;
  99386. t1y = v11y;
  99387. t1z = v11z;
  99388. v11x = v21x;
  99389. v11y = v21y;
  99390. v11z = v21z;
  99391. v21x = t1x;
  99392. v21y = t1y;
  99393. v21z = t1z;
  99394. t1x = v12x;
  99395. t1y = v12y;
  99396. t1z = v12z;
  99397. v12x = v22x;
  99398. v12y = v22y;
  99399. v12z = v22z;
  99400. v22x = t1x;
  99401. v22y = t1y;
  99402. v22z = t1z;
  99403. nx = -nx;
  99404. ny = -ny;
  99405. nz = -nz;
  99406. }
  99407. var iterations = 0;
  99408. while (true) {
  99409. if (++iterations > 100) {
  99410. return false;
  99411. }
  99412. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99413. var v31x = sup.x;
  99414. var v31y = sup.y;
  99415. var v31z = sup.z;
  99416. this.supportPointC(c2, nx, ny, nz, sup);
  99417. var v32x = sup.x;
  99418. var v32y = sup.y;
  99419. var v32z = sup.z;
  99420. var v3x = v32x - v31x;
  99421. var v3y = v32y - v31y;
  99422. var v3z = v32z - v31z;
  99423. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  99424. return false;
  99425. }
  99426. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  99427. v2x = v3x;
  99428. v2y = v3y;
  99429. v2z = v3z;
  99430. v21x = v31x;
  99431. v21y = v31y;
  99432. v21z = v31z;
  99433. v22x = v32x;
  99434. v22y = v32y;
  99435. v22z = v32z;
  99436. t1x = v1x - v0x;
  99437. t1y = v1y - v0y;
  99438. t1z = v1z - v0z;
  99439. t2x = v3x - v0x;
  99440. t2y = v3y - v0y;
  99441. t2z = v3z - v0z;
  99442. nx = t1y * t2z - t1z * t2y;
  99443. ny = t1z * t2x - t1x * t2z;
  99444. nz = t1x * t2y - t1y * t2x;
  99445. continue;
  99446. }
  99447. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  99448. v1x = v3x;
  99449. v1y = v3y;
  99450. v1z = v3z;
  99451. v11x = v31x;
  99452. v11y = v31y;
  99453. v11z = v31z;
  99454. v12x = v32x;
  99455. v12y = v32y;
  99456. v12z = v32z;
  99457. t1x = v3x - v0x;
  99458. t1y = v3y - v0y;
  99459. t1z = v3z - v0z;
  99460. t2x = v2x - v0x;
  99461. t2y = v2y - v0y;
  99462. t2z = v2z - v0z;
  99463. nx = t1y * t2z - t1z * t2y;
  99464. ny = t1z * t2x - t1x * t2z;
  99465. nz = t1x * t2y - t1y * t2x;
  99466. continue;
  99467. }
  99468. var hit = false;
  99469. while (true) {
  99470. t1x = v2x - v1x;
  99471. t1y = v2y - v1y;
  99472. t1z = v2z - v1z;
  99473. t2x = v3x - v1x;
  99474. t2y = v3y - v1y;
  99475. t2z = v3z - v1z;
  99476. nx = t1y * t2z - t1z * t2y;
  99477. ny = t1z * t2x - t1x * t2z;
  99478. nz = t1x * t2y - t1y * t2x;
  99479. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  99480. nx *= len;
  99481. ny *= len;
  99482. nz *= len;
  99483. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  99484. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  99485. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  99486. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  99487. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  99488. var sum = b0 + b1 + b2 + b3;
  99489. if (sum <= 0) {
  99490. b0 = 0;
  99491. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  99492. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  99493. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  99494. sum = b1 + b2 + b3;
  99495. }
  99496. var inv = 1 / sum;
  99497. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  99498. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  99499. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  99500. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  99501. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  99502. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  99503. hit = true;
  99504. }
  99505. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99506. var v41x = sup.x;
  99507. var v41y = sup.y;
  99508. var v41z = sup.z;
  99509. this.supportPointC(c2, nx, ny, nz, sup);
  99510. var v42x = sup.x;
  99511. var v42y = sup.y;
  99512. var v42z = sup.z;
  99513. var v4x = v42x - v41x;
  99514. var v4y = v42y - v41y;
  99515. var v4z = v42z - v41z;
  99516. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  99517. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  99518. if (hit) {
  99519. sep.init(-nx, -ny, -nz);
  99520. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  99521. dep.x = separation;
  99522. return true;
  99523. }
  99524. return false;
  99525. }
  99526. if (
  99527. (v4y * v1z - v4z * v1y) * v0x +
  99528. (v4z * v1x - v4x * v1z) * v0y +
  99529. (v4x * v1y - v4y * v1x) * v0z < 0
  99530. ) {
  99531. if (
  99532. (v4y * v2z - v4z * v2y) * v0x +
  99533. (v4z * v2x - v4x * v2z) * v0y +
  99534. (v4x * v2y - v4y * v2x) * v0z < 0
  99535. ) {
  99536. v1x = v4x;
  99537. v1y = v4y;
  99538. v1z = v4z;
  99539. v11x = v41x;
  99540. v11y = v41y;
  99541. v11z = v41z;
  99542. v12x = v42x;
  99543. v12y = v42y;
  99544. v12z = v42z;
  99545. } else {
  99546. v3x = v4x;
  99547. v3y = v4y;
  99548. v3z = v4z;
  99549. v31x = v41x;
  99550. v31y = v41y;
  99551. v31z = v41z;
  99552. v32x = v42x;
  99553. v32y = v42y;
  99554. v32z = v42z;
  99555. }
  99556. } else {
  99557. if (
  99558. (v4y * v3z - v4z * v3y) * v0x +
  99559. (v4z * v3x - v4x * v3z) * v0y +
  99560. (v4x * v3y - v4y * v3x) * v0z < 0
  99561. ) {
  99562. v2x = v4x;
  99563. v2y = v4y;
  99564. v2z = v4z;
  99565. v21x = v41x;
  99566. v21y = v41y;
  99567. v21z = v41z;
  99568. v22x = v42x;
  99569. v22y = v42y;
  99570. v22z = v42z;
  99571. } else {
  99572. v1x = v4x;
  99573. v1y = v4y;
  99574. v1z = v4z;
  99575. v11x = v41x;
  99576. v11y = v41y;
  99577. v11z = v41z;
  99578. v12x = v42x;
  99579. v12y = v42y;
  99580. v12z = v42z;
  99581. }
  99582. }
  99583. }
  99584. }
  99585. //return false;
  99586. };
  99587. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  99588. var rot = c.rotation.elements;
  99589. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99590. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99591. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99592. var w = c.halfWidth;
  99593. var h = c.halfHeight;
  99594. var d = c.halfDepth;
  99595. var ox;
  99596. var oy;
  99597. var oz;
  99598. if (ldx < 0) ox = -w;
  99599. else ox = w;
  99600. if (ldy < 0) oy = -h;
  99601. else oy = h;
  99602. if (ldz < 0) oz = -d;
  99603. else oz = d;
  99604. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99605. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99606. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99607. out.init(ldx, ldy, ldz);
  99608. };
  99609. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  99610. var rot = c.rotation.elements;
  99611. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99612. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99613. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99614. var radx = ldx;
  99615. var radz = ldz;
  99616. var len = radx * radx + radz * radz;
  99617. var rad = c.radius;
  99618. var hh = c.halfHeight;
  99619. var ox;
  99620. var oy;
  99621. var oz;
  99622. if (len == 0) {
  99623. if (ldy < 0) {
  99624. ox = rad;
  99625. oy = -hh;
  99626. oz = 0;
  99627. } else {
  99628. ox = rad;
  99629. oy = hh;
  99630. oz = 0;
  99631. }
  99632. } else {
  99633. len = c.radius / OIMO.sqrt(len);
  99634. if (ldy < 0) {
  99635. ox = radx * len;
  99636. oy = -hh;
  99637. oz = radz * len;
  99638. } else {
  99639. ox = radx * len;
  99640. oy = hh;
  99641. oz = radz * len;
  99642. }
  99643. }
  99644. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99645. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99646. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99647. out.init(ldx, ldy, ldz);
  99648. };
  99649. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99650. var b;
  99651. var c;
  99652. if (this.flip) {
  99653. b = shape2;
  99654. c = shape1;
  99655. } else {
  99656. b = shape1;
  99657. c = shape2;
  99658. }
  99659. var sep = new OIMO.Vec3();
  99660. var pos = new OIMO.Vec3();
  99661. var dep = new OIMO.Vec3();
  99662. var co;
  99663. if (!this.getSep(b, c, sep, pos, dep)) return;
  99664. var pbx = b.position.x;
  99665. var pby = b.position.y;
  99666. var pbz = b.position.z;
  99667. var pcx = c.position.x;
  99668. var pcy = c.position.y;
  99669. var pcz = c.position.z;
  99670. var bw = b.halfWidth;
  99671. var bh = b.halfHeight;
  99672. var bd = b.halfDepth;
  99673. var ch = c.halfHeight;
  99674. var r = c.radius;
  99675. var D = b.dimentions;
  99676. var nwx = D[0];//b.normalDirectionWidth.x;
  99677. var nwy = D[1];//b.normalDirectionWidth.y;
  99678. var nwz = D[2];//b.normalDirectionWidth.z;
  99679. var nhx = D[3];//b.normalDirectionHeight.x;
  99680. var nhy = D[4];//b.normalDirectionHeight.y;
  99681. var nhz = D[5];//b.normalDirectionHeight.z;
  99682. var ndx = D[6];//b.normalDirectionDepth.x;
  99683. var ndy = D[7];//b.normalDirectionDepth.y;
  99684. var ndz = D[8];//b.normalDirectionDepth.z;
  99685. var dwx = D[9];//b.halfDirectionWidth.x;
  99686. var dwy = D[10];//b.halfDirectionWidth.y;
  99687. var dwz = D[11];//b.halfDirectionWidth.z;
  99688. var dhx = D[12];//b.halfDirectionHeight.x;
  99689. var dhy = D[13];//b.halfDirectionHeight.y;
  99690. var dhz = D[14];//b.halfDirectionHeight.z;
  99691. var ddx = D[15];//b.halfDirectionDepth.x;
  99692. var ddy = D[16];//b.halfDirectionDepth.y;
  99693. var ddz = D[17];//b.halfDirectionDepth.z;
  99694. var ncx = c.normalDirection.x;
  99695. var ncy = c.normalDirection.y;
  99696. var ncz = c.normalDirection.z;
  99697. var dcx = c.halfDirection.x;
  99698. var dcy = c.halfDirection.y;
  99699. var dcz = c.halfDirection.z;
  99700. var nx = sep.x;
  99701. var ny = sep.y;
  99702. var nz = sep.z;
  99703. var dotw = nx * nwx + ny * nwy + nz * nwz;
  99704. var doth = nx * nhx + ny * nhy + nz * nhz;
  99705. var dotd = nx * ndx + ny * ndy + nz * ndz;
  99706. var dotc = nx * ncx + ny * ncy + nz * ncz;
  99707. var right1 = dotw > 0;
  99708. var right2 = doth > 0;
  99709. var right3 = dotd > 0;
  99710. var right4 = dotc > 0;
  99711. if (!right1) dotw = -dotw;
  99712. if (!right2) doth = -doth;
  99713. if (!right3) dotd = -dotd;
  99714. if (!right4) dotc = -dotc;
  99715. var state = 0;
  99716. if (dotc > 0.999) {
  99717. if (dotw > 0.999) {
  99718. if (dotw > dotc) state = 1;
  99719. else state = 4;
  99720. } else if (doth > 0.999) {
  99721. if (doth > dotc) state = 2;
  99722. else state = 4;
  99723. } else if (dotd > 0.999) {
  99724. if (dotd > dotc) state = 3;
  99725. else state = 4;
  99726. } else state = 4;
  99727. } else {
  99728. if (dotw > 0.999) state = 1;
  99729. else if (doth > 0.999) state = 2;
  99730. else if (dotd > 0.999) state = 3;
  99731. }
  99732. var cbx;
  99733. var cby;
  99734. var cbz;
  99735. var ccx;
  99736. var ccy;
  99737. var ccz;
  99738. var r00;
  99739. var r01;
  99740. var r02;
  99741. var r10;
  99742. var r11;
  99743. var r12;
  99744. var r20;
  99745. var r21;
  99746. var r22;
  99747. var px;
  99748. var py;
  99749. var pz;
  99750. var pd;
  99751. var dot;
  99752. var len;
  99753. var tx;
  99754. var ty;
  99755. var tz;
  99756. var td;
  99757. var dx;
  99758. var dy;
  99759. var dz;
  99760. var d1x;
  99761. var d1y;
  99762. var d1z;
  99763. var d2x;
  99764. var d2y;
  99765. var d2z;
  99766. var sx;
  99767. var sy;
  99768. var sz;
  99769. var sd;
  99770. var ex;
  99771. var ey;
  99772. var ez;
  99773. var ed;
  99774. var dot1;
  99775. var dot2;
  99776. var t1;
  99777. var t2;
  99778. var dir1x;
  99779. var dir1y;
  99780. var dir1z;
  99781. var dir2x;
  99782. var dir2y;
  99783. var dir2z;
  99784. var dir1l;
  99785. var dir2l;
  99786. if (state == 0) {
  99787. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  99788. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  99789. } else if (state == 4) {
  99790. if (right4) {
  99791. ccx = pcx - dcx;
  99792. ccy = pcy - dcy;
  99793. ccz = pcz - dcz;
  99794. nx = -ncx;
  99795. ny = -ncy;
  99796. nz = -ncz;
  99797. } else {
  99798. ccx = pcx + dcx;
  99799. ccy = pcy + dcy;
  99800. ccz = pcz + dcz;
  99801. nx = ncx;
  99802. ny = ncy;
  99803. nz = ncz;
  99804. }
  99805. var v1x;
  99806. var v1y;
  99807. var v1z;
  99808. var v2x;
  99809. var v2y;
  99810. var v2z;
  99811. var v3x;
  99812. var v3y;
  99813. var v3z;
  99814. var v4x;
  99815. var v4y;
  99816. var v4z;
  99817. dot = 1;
  99818. state = 0;
  99819. dot1 = nwx * nx + nwy * ny + nwz * nz;
  99820. if (dot1 < dot) {
  99821. dot = dot1;
  99822. state = 0;
  99823. }
  99824. if (-dot1 < dot) {
  99825. dot = -dot1;
  99826. state = 1;
  99827. }
  99828. dot1 = nhx * nx + nhy * ny + nhz * nz;
  99829. if (dot1 < dot) {
  99830. dot = dot1;
  99831. state = 2;
  99832. }
  99833. if (-dot1 < dot) {
  99834. dot = -dot1;
  99835. state = 3;
  99836. }
  99837. dot1 = ndx * nx + ndy * ny + ndz * nz;
  99838. if (dot1 < dot) {
  99839. dot = dot1;
  99840. state = 4;
  99841. }
  99842. if (-dot1 < dot) {
  99843. dot = -dot1;
  99844. state = 5;
  99845. }
  99846. var v = b.elements;
  99847. switch (state) {
  99848. case 0:
  99849. //v=b.vertex1;
  99850. v1x = v[0];//v.x;
  99851. v1y = v[1];//v.y;
  99852. v1z = v[2];//v.z;
  99853. //v=b.vertex3;
  99854. v2x = v[6];//v.x;
  99855. v2y = v[7];//v.y;
  99856. v2z = v[8];//v.z;
  99857. //v=b.vertex4;
  99858. v3x = v[9];//v.x;
  99859. v3y = v[10];//v.y;
  99860. v3z = v[11];//v.z;
  99861. //v=b.vertex2;
  99862. v4x = v[3];//v.x;
  99863. v4y = v[4];//v.y;
  99864. v4z = v[5];//v.z;
  99865. break;
  99866. case 1:
  99867. //v=b.vertex6;
  99868. v1x = v[15];//v.x;
  99869. v1y = v[16];//v.y;
  99870. v1z = v[17];//v.z;
  99871. //v=b.vertex8;
  99872. v2x = v[21];//v.x;
  99873. v2y = v[22];//v.y;
  99874. v2z = v[23];//v.z;
  99875. //v=b.vertex7;
  99876. v3x = v[18];//v.x;
  99877. v3y = v[19];//v.y;
  99878. v3z = v[20];//v.z;
  99879. //v=b.vertex5;
  99880. v4x = v[12];//v.x;
  99881. v4y = v[13];//v.y;
  99882. v4z = v[14];//v.z;
  99883. break;
  99884. case 2:
  99885. //v=b.vertex5;
  99886. v1x = v[12];//v.x;
  99887. v1y = v[13];//v.y;
  99888. v1z = v[14];//v.z;
  99889. //v=b.vertex1;
  99890. v2x = v[0];//v.x;
  99891. v2y = v[1];//v.y;
  99892. v2z = v[2];//v.z;
  99893. //v=b.vertex2;
  99894. v3x = v[3];//v.x;
  99895. v3y = v[4];//v.y;
  99896. v3z = v[5];//v.z;
  99897. //v=b.vertex6;
  99898. v4x = v[15];//v.x;
  99899. v4y = v[16];//v.y;
  99900. v4z = v[17];//v.z;
  99901. break;
  99902. case 3:
  99903. //v=b.vertex8;
  99904. v1x = v[21];//v.x;
  99905. v1y = v[22];//v.y;
  99906. v1z = v[23];//v.z;
  99907. //v=b.vertex4;
  99908. v2x = v[9];//v.x;
  99909. v2y = v[10];//v.y;
  99910. v2z = v[11];//v.z;
  99911. //v=b.vertex3;
  99912. v3x = v[6];//v.x;
  99913. v3y = v[7];//v.y;
  99914. v3z = v[8];//v.z;
  99915. //v=b.vertex7;
  99916. v4x = v[18];//v.x;
  99917. v4y = v[19];//v.y;
  99918. v4z = v[20];//v.z;
  99919. break;
  99920. case 4:
  99921. //v=b.vertex5;
  99922. v1x = v[12];//v.x;
  99923. v1y = v[13];//v.y;
  99924. v1z = v[14];//v.z;
  99925. //v=b.vertex7;
  99926. v2x = v[18];//v.x;
  99927. v2y = v[19];//v.y;
  99928. v2z = v[20];//v.z;
  99929. //v=b.vertex3;
  99930. v3x = v[6];//v.x;
  99931. v3y = v[7];//v.y;
  99932. v3z = v[8];//v.z;
  99933. //v=b.vertex1;
  99934. v4x = v[0];//v.x;
  99935. v4y = v[1];//v.y;
  99936. v4z = v[2];//v.z;
  99937. break;
  99938. case 5:
  99939. //v=b.vertex2;
  99940. v1x = v[3];//v.x;
  99941. v1y = v[4];//v.y;
  99942. v1z = v[5];//v.z;
  99943. //v=b.vertex4;
  99944. v2x = v[9];//v.x;
  99945. v2y = v[10];//v.y;
  99946. v2z = v[11];//v.z;
  99947. //v=b.vertex8;
  99948. v3x = v[21];//v.x;
  99949. v3y = v[22];//v.y;
  99950. v3z = v[23];//v.z;
  99951. //v=b.vertex6;
  99952. v4x = v[15];//v.x;
  99953. v4y = v[16];//v.y;
  99954. v4z = v[17];//v.z;
  99955. break;
  99956. }
  99957. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  99958. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  99959. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  99960. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  99961. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  99962. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  99963. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  99964. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  99965. } else {
  99966. switch (state) {
  99967. case 1:
  99968. if (right1) {
  99969. cbx = pbx + dwx;
  99970. cby = pby + dwy;
  99971. cbz = pbz + dwz;
  99972. nx = nwx;
  99973. ny = nwy;
  99974. nz = nwz;
  99975. } else {
  99976. cbx = pbx - dwx;
  99977. cby = pby - dwy;
  99978. cbz = pbz - dwz;
  99979. nx = -nwx;
  99980. ny = -nwy;
  99981. nz = -nwz;
  99982. }
  99983. dir1x = nhx;
  99984. dir1y = nhy;
  99985. dir1z = nhz;
  99986. dir1l = bh;
  99987. dir2x = ndx;
  99988. dir2y = ndy;
  99989. dir2z = ndz;
  99990. dir2l = bd;
  99991. break;
  99992. case 2:
  99993. if (right2) {
  99994. cbx = pbx + dhx;
  99995. cby = pby + dhy;
  99996. cbz = pbz + dhz;
  99997. nx = nhx;
  99998. ny = nhy;
  99999. nz = nhz;
  100000. } else {
  100001. cbx = pbx - dhx;
  100002. cby = pby - dhy;
  100003. cbz = pbz - dhz;
  100004. nx = -nhx;
  100005. ny = -nhy;
  100006. nz = -nhz;
  100007. }
  100008. dir1x = nwx;
  100009. dir1y = nwy;
  100010. dir1z = nwz;
  100011. dir1l = bw;
  100012. dir2x = ndx;
  100013. dir2y = ndy;
  100014. dir2z = ndz;
  100015. dir2l = bd;
  100016. break;
  100017. case 3:
  100018. if (right3) {
  100019. cbx = pbx + ddx;
  100020. cby = pby + ddy;
  100021. cbz = pbz + ddz;
  100022. nx = ndx;
  100023. ny = ndy;
  100024. nz = ndz;
  100025. } else {
  100026. cbx = pbx - ddx;
  100027. cby = pby - ddy;
  100028. cbz = pbz - ddz;
  100029. nx = -ndx;
  100030. ny = -ndy;
  100031. nz = -ndz;
  100032. }
  100033. dir1x = nwx;
  100034. dir1y = nwy;
  100035. dir1z = nwz;
  100036. dir1l = bw;
  100037. dir2x = nhx;
  100038. dir2y = nhy;
  100039. dir2z = nhz;
  100040. dir2l = bh;
  100041. break;
  100042. }
  100043. dot = nx * ncx + ny * ncy + nz * ncz;
  100044. if (dot < 0) len = ch;
  100045. else len = -ch;
  100046. ccx = pcx + len * ncx;
  100047. ccy = pcy + len * ncy;
  100048. ccz = pcz + len * ncz;
  100049. if (dotc >= 0.999999) {
  100050. tx = -ny;
  100051. ty = nz;
  100052. tz = nx;
  100053. } else {
  100054. tx = nx;
  100055. ty = ny;
  100056. tz = nz;
  100057. }
  100058. len = tx * ncx + ty * ncy + tz * ncz;
  100059. dx = len * ncx - tx;
  100060. dy = len * ncy - ty;
  100061. dz = len * ncz - tz;
  100062. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100063. if (len == 0) return;
  100064. len = r / len;
  100065. dx *= len;
  100066. dy *= len;
  100067. dz *= len;
  100068. tx = ccx + dx;
  100069. ty = ccy + dy;
  100070. tz = ccz + dz;
  100071. if (dot < -0.96 || dot > 0.96) {
  100072. r00 = ncx * ncx * 1.5 - 0.5;
  100073. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  100074. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  100075. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  100076. r11 = ncy * ncy * 1.5 - 0.5;
  100077. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  100078. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  100079. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  100080. r22 = ncz * ncz * 1.5 - 0.5;
  100081. px = tx;
  100082. py = ty;
  100083. pz = tz;
  100084. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100085. tx = px - pd * nx - cbx;
  100086. ty = py - pd * ny - cby;
  100087. tz = pz - pd * nz - cbz;
  100088. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100089. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100090. if (sd < -dir1l) sd = -dir1l;
  100091. else if (sd > dir1l) sd = dir1l;
  100092. if (ed < -dir2l) ed = -dir2l;
  100093. else if (ed > dir2l) ed = dir2l;
  100094. tx = sd * dir1x + ed * dir2x;
  100095. ty = sd * dir1y + ed * dir2y;
  100096. tz = sd * dir1z + ed * dir2z;
  100097. px = cbx + tx;
  100098. py = cby + ty;
  100099. pz = cbz + tz;
  100100. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100101. px = dx * r00 + dy * r01 + dz * r02;
  100102. py = dx * r10 + dy * r11 + dz * r12;
  100103. pz = dx * r20 + dy * r21 + dz * r22;
  100104. px = (dx = px) + ccx;
  100105. py = (dy = py) + ccy;
  100106. pz = (dz = pz) + ccz;
  100107. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100108. if (pd <= 0) {
  100109. tx = px - pd * nx - cbx;
  100110. ty = py - pd * ny - cby;
  100111. tz = pz - pd * nz - cbz;
  100112. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100113. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100114. if (sd < -dir1l) sd = -dir1l;
  100115. else if (sd > dir1l) sd = dir1l;
  100116. if (ed < -dir2l) ed = -dir2l;
  100117. else if (ed > dir2l) ed = dir2l;
  100118. tx = sd * dir1x + ed * dir2x;
  100119. ty = sd * dir1y + ed * dir2y;
  100120. tz = sd * dir1z + ed * dir2z;
  100121. px = cbx + tx;
  100122. py = cby + ty;
  100123. pz = cbz + tz;
  100124. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  100125. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100126. }
  100127. px = dx * r00 + dy * r01 + dz * r02;
  100128. py = dx * r10 + dy * r11 + dz * r12;
  100129. pz = dx * r20 + dy * r21 + dz * r22;
  100130. px = (dx = px) + ccx;
  100131. py = (dy = py) + ccy;
  100132. pz = (dz = pz) + ccz;
  100133. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100134. if (pd <= 0) {
  100135. tx = px - pd * nx - cbx;
  100136. ty = py - pd * ny - cby;
  100137. tz = pz - pd * nz - cbz;
  100138. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100139. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100140. if (sd < -dir1l) sd = -dir1l;
  100141. else if (sd > dir1l) sd = dir1l;
  100142. if (ed < -dir2l) ed = -dir2l;
  100143. else if (ed > dir2l) ed = dir2l;
  100144. tx = sd * dir1x + ed * dir2x;
  100145. ty = sd * dir1y + ed * dir2y;
  100146. tz = sd * dir1z + ed * dir2z;
  100147. px = cbx + tx;
  100148. py = cby + ty;
  100149. pz = cbz + tz;
  100150. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  100151. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100152. }
  100153. } else {
  100154. sx = tx;
  100155. sy = ty;
  100156. sz = tz;
  100157. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  100158. sx -= sd * nx;
  100159. sy -= sd * ny;
  100160. sz -= sd * nz;
  100161. if (dot > 0) {
  100162. ex = tx + dcx * 2;
  100163. ey = ty + dcy * 2;
  100164. ez = tz + dcz * 2;
  100165. } else {
  100166. ex = tx - dcx * 2;
  100167. ey = ty - dcy * 2;
  100168. ez = tz - dcz * 2;
  100169. }
  100170. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  100171. ex -= ed * nx;
  100172. ey -= ed * ny;
  100173. ez -= ed * nz;
  100174. d1x = sx - cbx;
  100175. d1y = sy - cby;
  100176. d1z = sz - cbz;
  100177. d2x = ex - cbx;
  100178. d2y = ey - cby;
  100179. d2z = ez - cbz;
  100180. tx = ex - sx;
  100181. ty = ey - sy;
  100182. tz = ez - sz;
  100183. td = ed - sd;
  100184. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100185. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100186. dot1 = dotw - dir1l;
  100187. dot2 = doth - dir1l;
  100188. if (dot1 > 0) {
  100189. if (dot2 > 0) return;
  100190. t1 = dot1 / (dot1 - dot2);
  100191. sx = sx + tx * t1;
  100192. sy = sy + ty * t1;
  100193. sz = sz + tz * t1;
  100194. sd = sd + td * t1;
  100195. d1x = sx - cbx;
  100196. d1y = sy - cby;
  100197. d1z = sz - cbz;
  100198. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100199. tx = ex - sx;
  100200. ty = ey - sy;
  100201. tz = ez - sz;
  100202. td = ed - sd;
  100203. } else if (dot2 > 0) {
  100204. t1 = dot1 / (dot1 - dot2);
  100205. ex = sx + tx * t1;
  100206. ey = sy + ty * t1;
  100207. ez = sz + tz * t1;
  100208. ed = sd + td * t1;
  100209. d2x = ex - cbx;
  100210. d2y = ey - cby;
  100211. d2z = ez - cbz;
  100212. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100213. tx = ex - sx;
  100214. ty = ey - sy;
  100215. tz = ez - sz;
  100216. td = ed - sd;
  100217. }
  100218. dot1 = dotw + dir1l;
  100219. dot2 = doth + dir1l;
  100220. if (dot1 < 0) {
  100221. if (dot2 < 0) return;
  100222. t1 = dot1 / (dot1 - dot2);
  100223. sx = sx + tx * t1;
  100224. sy = sy + ty * t1;
  100225. sz = sz + tz * t1;
  100226. sd = sd + td * t1;
  100227. d1x = sx - cbx;
  100228. d1y = sy - cby;
  100229. d1z = sz - cbz;
  100230. tx = ex - sx;
  100231. ty = ey - sy;
  100232. tz = ez - sz;
  100233. td = ed - sd;
  100234. } else if (dot2 < 0) {
  100235. t1 = dot1 / (dot1 - dot2);
  100236. ex = sx + tx * t1;
  100237. ey = sy + ty * t1;
  100238. ez = sz + tz * t1;
  100239. ed = sd + td * t1;
  100240. d2x = ex - cbx;
  100241. d2y = ey - cby;
  100242. d2z = ez - cbz;
  100243. tx = ex - sx;
  100244. ty = ey - sy;
  100245. tz = ez - sz;
  100246. td = ed - sd;
  100247. }
  100248. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  100249. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  100250. dot1 = dotw - dir2l;
  100251. dot2 = doth - dir2l;
  100252. if (dot1 > 0) {
  100253. if (dot2 > 0) return;
  100254. t1 = dot1 / (dot1 - dot2);
  100255. sx = sx + tx * t1;
  100256. sy = sy + ty * t1;
  100257. sz = sz + tz * t1;
  100258. sd = sd + td * t1;
  100259. d1x = sx - cbx;
  100260. d1y = sy - cby;
  100261. d1z = sz - cbz;
  100262. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  100263. tx = ex - sx;
  100264. ty = ey - sy;
  100265. tz = ez - sz;
  100266. td = ed - sd;
  100267. } else if (dot2 > 0) {
  100268. t1 = dot1 / (dot1 - dot2);
  100269. ex = sx + tx * t1;
  100270. ey = sy + ty * t1;
  100271. ez = sz + tz * t1;
  100272. ed = sd + td * t1;
  100273. d2x = ex - cbx;
  100274. d2y = ey - cby;
  100275. d2z = ez - cbz;
  100276. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  100277. tx = ex - sx;
  100278. ty = ey - sy;
  100279. tz = ez - sz;
  100280. td = ed - sd;
  100281. }
  100282. dot1 = dotw + dir2l;
  100283. dot2 = doth + dir2l;
  100284. if (dot1 < 0) {
  100285. if (dot2 < 0) return;
  100286. t1 = dot1 / (dot1 - dot2);
  100287. sx = sx + tx * t1;
  100288. sy = sy + ty * t1;
  100289. sz = sz + tz * t1;
  100290. sd = sd + td * t1;
  100291. } else if (dot2 < 0) {
  100292. t1 = dot1 / (dot1 - dot2);
  100293. ex = sx + tx * t1;
  100294. ey = sy + ty * t1;
  100295. ez = sz + tz * t1;
  100296. ed = sd + td * t1;
  100297. }
  100298. if (sd < 0) {
  100299. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  100300. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  100301. }
  100302. if (ed < 0) {
  100303. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  100304. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  100305. }
  100306. }
  100307. }
  100308. };
  100309. OIMO.CylinderCylinderCollisionDetector = function () {
  100310. OIMO.CollisionDetector.call(this);
  100311. };
  100312. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100313. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  100314. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100315. var t1x;
  100316. var t1y;
  100317. var t1z;
  100318. var t2x;
  100319. var t2y;
  100320. var t2z;
  100321. var sup = new OIMO.Vec3();
  100322. var len;
  100323. var p1x;
  100324. var p1y;
  100325. var p1z;
  100326. var p2x;
  100327. var p2y;
  100328. var p2z;
  100329. var v01x = c1.position.x;
  100330. var v01y = c1.position.y;
  100331. var v01z = c1.position.z;
  100332. var v02x = c2.position.x;
  100333. var v02y = c2.position.y;
  100334. var v02z = c2.position.z;
  100335. var v0x = v02x - v01x;
  100336. var v0y = v02y - v01y;
  100337. var v0z = v02z - v01z;
  100338. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100339. var nx = -v0x;
  100340. var ny = -v0y;
  100341. var nz = -v0z;
  100342. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100343. var v11x = sup.x;
  100344. var v11y = sup.y;
  100345. var v11z = sup.z;
  100346. this.supportPoint(c2, nx, ny, nz, sup);
  100347. var v12x = sup.x;
  100348. var v12y = sup.y;
  100349. var v12z = sup.z;
  100350. var v1x = v12x - v11x;
  100351. var v1y = v12y - v11y;
  100352. var v1z = v12z - v11z;
  100353. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100354. return false;
  100355. }
  100356. nx = v1y * v0z - v1z * v0y;
  100357. ny = v1z * v0x - v1x * v0z;
  100358. nz = v1x * v0y - v1y * v0x;
  100359. if (nx * nx + ny * ny + nz * nz == 0) {
  100360. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100361. sep.normalize(sep);
  100362. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100363. return true;
  100364. }
  100365. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100366. var v21x = sup.x;
  100367. var v21y = sup.y;
  100368. var v21z = sup.z;
  100369. this.supportPoint(c2, nx, ny, nz, sup);
  100370. var v22x = sup.x;
  100371. var v22y = sup.y;
  100372. var v22z = sup.z;
  100373. var v2x = v22x - v21x;
  100374. var v2y = v22y - v21y;
  100375. var v2z = v22z - v21z;
  100376. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100377. return false;
  100378. }
  100379. t1x = v1x - v0x;
  100380. t1y = v1y - v0y;
  100381. t1z = v1z - v0z;
  100382. t2x = v2x - v0x;
  100383. t2y = v2y - v0y;
  100384. t2z = v2z - v0z;
  100385. nx = t1y * t2z - t1z * t2y;
  100386. ny = t1z * t2x - t1x * t2z;
  100387. nz = t1x * t2y - t1y * t2x;
  100388. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100389. t1x = v1x;
  100390. t1y = v1y;
  100391. t1z = v1z;
  100392. v1x = v2x;
  100393. v1y = v2y;
  100394. v1z = v2z;
  100395. v2x = t1x;
  100396. v2y = t1y;
  100397. v2z = t1z;
  100398. t1x = v11x;
  100399. t1y = v11y;
  100400. t1z = v11z;
  100401. v11x = v21x;
  100402. v11y = v21y;
  100403. v11z = v21z;
  100404. v21x = t1x;
  100405. v21y = t1y;
  100406. v21z = t1z;
  100407. t1x = v12x;
  100408. t1y = v12y;
  100409. t1z = v12z;
  100410. v12x = v22x;
  100411. v12y = v22y;
  100412. v12z = v22z;
  100413. v22x = t1x;
  100414. v22y = t1y;
  100415. v22z = t1z;
  100416. nx = -nx;
  100417. ny = -ny;
  100418. nz = -nz;
  100419. }
  100420. var iterations = 0;
  100421. while (true) {
  100422. if (++iterations > 100) {
  100423. return false;
  100424. }
  100425. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100426. var v31x = sup.x;
  100427. var v31y = sup.y;
  100428. var v31z = sup.z;
  100429. this.supportPoint(c2, nx, ny, nz, sup);
  100430. var v32x = sup.x;
  100431. var v32y = sup.y;
  100432. var v32z = sup.z;
  100433. var v3x = v32x - v31x;
  100434. var v3y = v32y - v31y;
  100435. var v3z = v32z - v31z;
  100436. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100437. return false;
  100438. }
  100439. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100440. v2x = v3x;
  100441. v2y = v3y;
  100442. v2z = v3z;
  100443. v21x = v31x;
  100444. v21y = v31y;
  100445. v21z = v31z;
  100446. v22x = v32x;
  100447. v22y = v32y;
  100448. v22z = v32z;
  100449. t1x = v1x - v0x;
  100450. t1y = v1y - v0y;
  100451. t1z = v1z - v0z;
  100452. t2x = v3x - v0x;
  100453. t2y = v3y - v0y;
  100454. t2z = v3z - v0z;
  100455. nx = t1y * t2z - t1z * t2y;
  100456. ny = t1z * t2x - t1x * t2z;
  100457. nz = t1x * t2y - t1y * t2x;
  100458. continue;
  100459. }
  100460. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100461. v1x = v3x;
  100462. v1y = v3y;
  100463. v1z = v3z;
  100464. v11x = v31x;
  100465. v11y = v31y;
  100466. v11z = v31z;
  100467. v12x = v32x;
  100468. v12y = v32y;
  100469. v12z = v32z;
  100470. t1x = v3x - v0x;
  100471. t1y = v3y - v0y;
  100472. t1z = v3z - v0z;
  100473. t2x = v2x - v0x;
  100474. t2y = v2y - v0y;
  100475. t2z = v2z - v0z;
  100476. nx = t1y * t2z - t1z * t2y;
  100477. ny = t1z * t2x - t1x * t2z;
  100478. nz = t1x * t2y - t1y * t2x;
  100479. continue;
  100480. }
  100481. var hit = false;
  100482. while (true) {
  100483. t1x = v2x - v1x;
  100484. t1y = v2y - v1y;
  100485. t1z = v2z - v1z;
  100486. t2x = v3x - v1x;
  100487. t2y = v3y - v1y;
  100488. t2z = v3z - v1z;
  100489. nx = t1y * t2z - t1z * t2y;
  100490. ny = t1z * t2x - t1x * t2z;
  100491. nz = t1x * t2y - t1y * t2x;
  100492. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100493. nx *= len;
  100494. ny *= len;
  100495. nz *= len;
  100496. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100497. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100498. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100499. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100500. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100501. var sum = b0 + b1 + b2 + b3;
  100502. if (sum <= 0) {
  100503. b0 = 0;
  100504. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100505. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100506. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100507. sum = b1 + b2 + b3;
  100508. }
  100509. var inv = 1 / sum;
  100510. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100511. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100512. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100513. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100514. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100515. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100516. hit = true;
  100517. }
  100518. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100519. var v41x = sup.x;
  100520. var v41y = sup.y;
  100521. var v41z = sup.z;
  100522. this.supportPoint(c2, nx, ny, nz, sup);
  100523. var v42x = sup.x;
  100524. var v42y = sup.y;
  100525. var v42z = sup.z;
  100526. var v4x = v42x - v41x;
  100527. var v4y = v42y - v41y;
  100528. var v4z = v42z - v41z;
  100529. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100530. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100531. if (hit) {
  100532. sep.init(-nx, -ny, -nz);
  100533. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100534. dep.x = separation;
  100535. return true;
  100536. }
  100537. return false;
  100538. }
  100539. if (
  100540. (v4y * v1z - v4z * v1y) * v0x +
  100541. (v4z * v1x - v4x * v1z) * v0y +
  100542. (v4x * v1y - v4y * v1x) * v0z < 0
  100543. ) {
  100544. if (
  100545. (v4y * v2z - v4z * v2y) * v0x +
  100546. (v4z * v2x - v4x * v2z) * v0y +
  100547. (v4x * v2y - v4y * v2x) * v0z < 0
  100548. ) {
  100549. v1x = v4x;
  100550. v1y = v4y;
  100551. v1z = v4z;
  100552. v11x = v41x;
  100553. v11y = v41y;
  100554. v11z = v41z;
  100555. v12x = v42x;
  100556. v12y = v42y;
  100557. v12z = v42z;
  100558. } else {
  100559. v3x = v4x;
  100560. v3y = v4y;
  100561. v3z = v4z;
  100562. v31x = v41x;
  100563. v31y = v41y;
  100564. v31z = v41z;
  100565. v32x = v42x;
  100566. v32y = v42y;
  100567. v32z = v42z;
  100568. }
  100569. } else {
  100570. if (
  100571. (v4y * v3z - v4z * v3y) * v0x +
  100572. (v4z * v3x - v4x * v3z) * v0y +
  100573. (v4x * v3y - v4y * v3x) * v0z < 0
  100574. ) {
  100575. v2x = v4x;
  100576. v2y = v4y;
  100577. v2z = v4z;
  100578. v21x = v41x;
  100579. v21y = v41y;
  100580. v21z = v41z;
  100581. v22x = v42x;
  100582. v22y = v42y;
  100583. v22z = v42z;
  100584. } else {
  100585. v1x = v4x;
  100586. v1y = v4y;
  100587. v1z = v4z;
  100588. v11x = v41x;
  100589. v11y = v41y;
  100590. v11z = v41z;
  100591. v12x = v42x;
  100592. v12y = v42y;
  100593. v12z = v42z;
  100594. }
  100595. }
  100596. }
  100597. }
  100598. //return false;
  100599. };
  100600. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  100601. var rot = c.rotation.elements;
  100602. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100603. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100604. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100605. var radx = ldx;
  100606. var radz = ldz;
  100607. var len = radx * radx + radz * radz;
  100608. var rad = c.radius;
  100609. var hh = c.halfHeight;
  100610. var ox;
  100611. var oy;
  100612. var oz;
  100613. if (len == 0) {
  100614. if (ldy < 0) {
  100615. ox = rad;
  100616. oy = -hh;
  100617. oz = 0;
  100618. } else {
  100619. ox = rad;
  100620. oy = hh;
  100621. oz = 0;
  100622. }
  100623. } else {
  100624. len = c.radius / OIMO.sqrt(len);
  100625. if (ldy < 0) {
  100626. ox = radx * len;
  100627. oy = -hh;
  100628. oz = radz * len;
  100629. } else {
  100630. ox = radx * len;
  100631. oy = hh;
  100632. oz = radz * len;
  100633. }
  100634. }
  100635. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100636. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100637. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100638. out.init(ldx, ldy, ldz);
  100639. };
  100640. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100641. var c1;
  100642. var c2;
  100643. if (shape1.id < shape2.id) {
  100644. c1 = shape1;
  100645. c2 = shape2;
  100646. } else {
  100647. c1 = shape2;
  100648. c2 = shape1;
  100649. }
  100650. var p1 = c1.position;
  100651. var p2 = c2.position;
  100652. var p1x = p1.x;
  100653. var p1y = p1.y;
  100654. var p1z = p1.z;
  100655. var p2x = p2.x;
  100656. var p2y = p2.y;
  100657. var p2z = p2.z;
  100658. var h1 = c1.halfHeight;
  100659. var h2 = c2.halfHeight;
  100660. var n1 = c1.normalDirection;
  100661. var n2 = c2.normalDirection;
  100662. var d1 = c1.halfDirection;
  100663. var d2 = c2.halfDirection;
  100664. var r1 = c1.radius;
  100665. var r2 = c2.radius;
  100666. var n1x = n1.x;
  100667. var n1y = n1.y;
  100668. var n1z = n1.z;
  100669. var n2x = n2.x;
  100670. var n2y = n2.y;
  100671. var n2z = n2.z;
  100672. var d1x = d1.x;
  100673. var d1y = d1.y;
  100674. var d1z = d1.z;
  100675. var d2x = d2.x;
  100676. var d2y = d2.y;
  100677. var d2z = d2.z;
  100678. var dx = p1x - p2x;
  100679. var dy = p1y - p2y;
  100680. var dz = p1z - p2z;
  100681. var len;
  100682. var len1;
  100683. var len2;
  100684. var c;
  100685. var c1x;
  100686. var c1y;
  100687. var c1z;
  100688. var c2x;
  100689. var c2y;
  100690. var c2z;
  100691. var tx;
  100692. var ty;
  100693. var tz;
  100694. var sx;
  100695. var sy;
  100696. var sz;
  100697. var ex;
  100698. var ey;
  100699. var ez;
  100700. var depth1;
  100701. var depth2;
  100702. var dot;
  100703. var t1;
  100704. var t2;
  100705. var sep = new OIMO.Vec3();
  100706. var pos = new OIMO.Vec3();
  100707. var dep = new OIMO.Vec3();
  100708. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  100709. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  100710. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  100711. var right1 = dot1 > 0;
  100712. var right2 = dot2 > 0;
  100713. if (!right1) dot1 = -dot1;
  100714. if (!right2) dot2 = -dot2;
  100715. var state = 0;
  100716. if (dot1 > 0.999 || dot2 > 0.999) {
  100717. if (dot1 > dot2) state = 1;
  100718. else state = 2;
  100719. }
  100720. var nx;
  100721. var ny;
  100722. var nz;
  100723. var depth = dep.x;
  100724. var r00;
  100725. var r01;
  100726. var r02;
  100727. var r10;
  100728. var r11;
  100729. var r12;
  100730. var r20;
  100731. var r21;
  100732. var r22;
  100733. var px;
  100734. var py;
  100735. var pz;
  100736. var pd;
  100737. var a;
  100738. var b;
  100739. var e;
  100740. var f;
  100741. nx = sep.x;
  100742. ny = sep.y;
  100743. nz = sep.z;
  100744. switch (state) {
  100745. case 0:
  100746. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  100747. break;
  100748. case 1:
  100749. if (right1) {
  100750. c1x = p1x + d1x;
  100751. c1y = p1y + d1y;
  100752. c1z = p1z + d1z;
  100753. nx = n1x;
  100754. ny = n1y;
  100755. nz = n1z;
  100756. } else {
  100757. c1x = p1x - d1x;
  100758. c1y = p1y - d1y;
  100759. c1z = p1z - d1z;
  100760. nx = -n1x;
  100761. ny = -n1y;
  100762. nz = -n1z;
  100763. }
  100764. dot = nx * n2x + ny * n2y + nz * n2z;
  100765. if (dot < 0) len = h2;
  100766. else len = -h2;
  100767. c2x = p2x + len * n2x;
  100768. c2y = p2y + len * n2y;
  100769. c2z = p2z + len * n2z;
  100770. if (dot2 >= 0.999999) {
  100771. tx = -ny;
  100772. ty = nz;
  100773. tz = nx;
  100774. } else {
  100775. tx = nx;
  100776. ty = ny;
  100777. tz = nz;
  100778. }
  100779. len = tx * n2x + ty * n2y + tz * n2z;
  100780. dx = len * n2x - tx;
  100781. dy = len * n2y - ty;
  100782. dz = len * n2z - tz;
  100783. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100784. if (len == 0) break;
  100785. len = r2 / len;
  100786. dx *= len;
  100787. dy *= len;
  100788. dz *= len;
  100789. tx = c2x + dx;
  100790. ty = c2y + dy;
  100791. tz = c2z + dz;
  100792. if (dot < -0.96 || dot > 0.96) {
  100793. r00 = n2x * n2x * 1.5 - 0.5;
  100794. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  100795. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  100796. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  100797. r11 = n2y * n2y * 1.5 - 0.5;
  100798. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  100799. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  100800. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  100801. r22 = n2z * n2z * 1.5 - 0.5;
  100802. px = tx;
  100803. py = ty;
  100804. pz = tz;
  100805. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  100806. tx = px - pd * nx - c1x;
  100807. ty = py - pd * ny - c1y;
  100808. tz = pz - pd * nz - c1z;
  100809. len = tx * tx + ty * ty + tz * tz;
  100810. if (len > r1 * r1) {
  100811. len = r1 / OIMO.sqrt(len);
  100812. tx *= len;
  100813. ty *= len;
  100814. tz *= len;
  100815. }
  100816. px = c1x + tx;
  100817. py = c1y + ty;
  100818. pz = c1z + tz;
  100819. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  100820. px = dx * r00 + dy * r01 + dz * r02;
  100821. py = dx * r10 + dy * r11 + dz * r12;
  100822. pz = dx * r20 + dy * r21 + dz * r22;
  100823. px = (dx = px) + c2x;
  100824. py = (dy = py) + c2y;
  100825. pz = (dz = pz) + c2z;
  100826. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  100827. if (pd <= 0) {
  100828. tx = px - pd * nx - c1x;
  100829. ty = py - pd * ny - c1y;
  100830. tz = pz - pd * nz - c1z;
  100831. len = tx * tx + ty * ty + tz * tz;
  100832. if (len > r1 * r1) {
  100833. len = r1 / OIMO.sqrt(len);
  100834. tx *= len;
  100835. ty *= len;
  100836. tz *= len;
  100837. }
  100838. px = c1x + tx;
  100839. py = c1y + ty;
  100840. pz = c1z + tz;
  100841. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  100842. }
  100843. px = dx * r00 + dy * r01 + dz * r02;
  100844. py = dx * r10 + dy * r11 + dz * r12;
  100845. pz = dx * r20 + dy * r21 + dz * r22;
  100846. px = (dx = px) + c2x;
  100847. py = (dy = py) + c2y;
  100848. pz = (dz = pz) + c2z;
  100849. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  100850. if (pd <= 0) {
  100851. tx = px - pd * nx - c1x;
  100852. ty = py - pd * ny - c1y;
  100853. tz = pz - pd * nz - c1z;
  100854. len = tx * tx + ty * ty + tz * tz;
  100855. if (len > r1 * r1) {
  100856. len = r1 / OIMO.sqrt(len);
  100857. tx *= len;
  100858. ty *= len;
  100859. tz *= len;
  100860. }
  100861. px = c1x + tx;
  100862. py = c1y + ty;
  100863. pz = c1z + tz;
  100864. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  100865. }
  100866. } else {
  100867. sx = tx;
  100868. sy = ty;
  100869. sz = tz;
  100870. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  100871. sx -= depth1 * nx;
  100872. sy -= depth1 * ny;
  100873. sz -= depth1 * nz;
  100874. if (dot > 0) {
  100875. ex = tx + n2x * h2 * 2;
  100876. ey = ty + n2y * h2 * 2;
  100877. ez = tz + n2z * h2 * 2;
  100878. } else {
  100879. ex = tx - n2x * h2 * 2;
  100880. ey = ty - n2y * h2 * 2;
  100881. ez = tz - n2z * h2 * 2;
  100882. }
  100883. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  100884. ex -= depth2 * nx;
  100885. ey -= depth2 * ny;
  100886. ez -= depth2 * nz;
  100887. dx = c1x - sx;
  100888. dy = c1y - sy;
  100889. dz = c1z - sz;
  100890. tx = ex - sx;
  100891. ty = ey - sy;
  100892. tz = ez - sz;
  100893. a = dx * dx + dy * dy + dz * dz;
  100894. b = dx * tx + dy * ty + dz * tz;
  100895. e = tx * tx + ty * ty + tz * tz;
  100896. f = b * b - e * (a - r1 * r1);
  100897. if (f < 0) break;
  100898. f = OIMO.sqrt(f);
  100899. t1 = (b + f) / e;
  100900. t2 = (b - f) / e;
  100901. if (t2 < t1) {
  100902. len = t1;
  100903. t1 = t2;
  100904. t2 = len;
  100905. }
  100906. if (t2 > 1) t2 = 1;
  100907. if (t1 < 0) t1 = 0;
  100908. tx = sx + (ex - sx) * t1;
  100909. ty = sy + (ey - sy) * t1;
  100910. tz = sz + (ez - sz) * t1;
  100911. ex = sx + (ex - sx) * t2;
  100912. ey = sy + (ey - sy) * t2;
  100913. ez = sz + (ez - sz) * t2;
  100914. sx = tx;
  100915. sy = ty;
  100916. sz = tz;
  100917. len = depth1 + (depth2 - depth1) * t1;
  100918. depth2 = depth1 + (depth2 - depth1) * t2;
  100919. depth1 = len;
  100920. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  100921. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  100922. }
  100923. break;
  100924. case 2:
  100925. if (right2) {
  100926. c2x = p2x - d2x;
  100927. c2y = p2y - d2y;
  100928. c2z = p2z - d2z;
  100929. nx = -n2x;
  100930. ny = -n2y;
  100931. nz = -n2z;
  100932. } else {
  100933. c2x = p2x + d2x;
  100934. c2y = p2y + d2y;
  100935. c2z = p2z + d2z;
  100936. nx = n2x;
  100937. ny = n2y;
  100938. nz = n2z;
  100939. }
  100940. dot = nx * n1x + ny * n1y + nz * n1z;
  100941. if (dot < 0) len = h1;
  100942. else len = -h1;
  100943. c1x = p1x + len * n1x;
  100944. c1y = p1y + len * n1y;
  100945. c1z = p1z + len * n1z;
  100946. if (dot1 >= 0.999999) {
  100947. tx = -ny;
  100948. ty = nz;
  100949. tz = nx;
  100950. } else {
  100951. tx = nx;
  100952. ty = ny;
  100953. tz = nz;
  100954. }
  100955. len = tx * n1x + ty * n1y + tz * n1z;
  100956. dx = len * n1x - tx;
  100957. dy = len * n1y - ty;
  100958. dz = len * n1z - tz;
  100959. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100960. if (len == 0) break;
  100961. len = r1 / len;
  100962. dx *= len;
  100963. dy *= len;
  100964. dz *= len;
  100965. tx = c1x + dx;
  100966. ty = c1y + dy;
  100967. tz = c1z + dz;
  100968. if (dot < -0.96 || dot > 0.96) {
  100969. r00 = n1x * n1x * 1.5 - 0.5;
  100970. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  100971. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  100972. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  100973. r11 = n1y * n1y * 1.5 - 0.5;
  100974. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  100975. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  100976. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  100977. r22 = n1z * n1z * 1.5 - 0.5;
  100978. px = tx;
  100979. py = ty;
  100980. pz = tz;
  100981. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  100982. tx = px - pd * nx - c2x;
  100983. ty = py - pd * ny - c2y;
  100984. tz = pz - pd * nz - c2z;
  100985. len = tx * tx + ty * ty + tz * tz;
  100986. if (len > r2 * r2) {
  100987. len = r2 / OIMO.sqrt(len);
  100988. tx *= len;
  100989. ty *= len;
  100990. tz *= len;
  100991. }
  100992. px = c2x + tx;
  100993. py = c2y + ty;
  100994. pz = c2z + tz;
  100995. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  100996. px = dx * r00 + dy * r01 + dz * r02;
  100997. py = dx * r10 + dy * r11 + dz * r12;
  100998. pz = dx * r20 + dy * r21 + dz * r22;
  100999. px = (dx = px) + c1x;
  101000. py = (dy = py) + c1y;
  101001. pz = (dz = pz) + c1z;
  101002. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101003. if (pd <= 0) {
  101004. tx = px - pd * nx - c2x;
  101005. ty = py - pd * ny - c2y;
  101006. tz = pz - pd * nz - c2z;
  101007. len = tx * tx + ty * ty + tz * tz;
  101008. if (len > r2 * r2) {
  101009. len = r2 / OIMO.sqrt(len);
  101010. tx *= len;
  101011. ty *= len;
  101012. tz *= len;
  101013. }
  101014. px = c2x + tx;
  101015. py = c2y + ty;
  101016. pz = c2z + tz;
  101017. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101018. }
  101019. px = dx * r00 + dy * r01 + dz * r02;
  101020. py = dx * r10 + dy * r11 + dz * r12;
  101021. pz = dx * r20 + dy * r21 + dz * r22;
  101022. px = (dx = px) + c1x;
  101023. py = (dy = py) + c1y;
  101024. pz = (dz = pz) + c1z;
  101025. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101026. if (pd <= 0) {
  101027. tx = px - pd * nx - c2x;
  101028. ty = py - pd * ny - c2y;
  101029. tz = pz - pd * nz - c2z;
  101030. len = tx * tx + ty * ty + tz * tz;
  101031. if (len > r2 * r2) {
  101032. len = r2 / OIMO.sqrt(len);
  101033. tx *= len;
  101034. ty *= len;
  101035. tz *= len;
  101036. }
  101037. px = c2x + tx;
  101038. py = c2y + ty;
  101039. pz = c2z + tz;
  101040. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101041. }
  101042. } else {
  101043. sx = tx;
  101044. sy = ty;
  101045. sz = tz;
  101046. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  101047. sx -= depth1 * nx;
  101048. sy -= depth1 * ny;
  101049. sz -= depth1 * nz;
  101050. if (dot > 0) {
  101051. ex = tx + n1x * h1 * 2;
  101052. ey = ty + n1y * h1 * 2;
  101053. ez = tz + n1z * h1 * 2;
  101054. } else {
  101055. ex = tx - n1x * h1 * 2;
  101056. ey = ty - n1y * h1 * 2;
  101057. ez = tz - n1z * h1 * 2;
  101058. }
  101059. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  101060. ex -= depth2 * nx;
  101061. ey -= depth2 * ny;
  101062. ez -= depth2 * nz;
  101063. dx = c2x - sx;
  101064. dy = c2y - sy;
  101065. dz = c2z - sz;
  101066. tx = ex - sx;
  101067. ty = ey - sy;
  101068. tz = ez - sz;
  101069. a = dx * dx + dy * dy + dz * dz;
  101070. b = dx * tx + dy * ty + dz * tz;
  101071. e = tx * tx + ty * ty + tz * tz;
  101072. f = b * b - e * (a - r2 * r2);
  101073. if (f < 0) break;
  101074. f = OIMO.sqrt(f);
  101075. t1 = (b + f) / e;
  101076. t2 = (b - f) / e;
  101077. if (t2 < t1) {
  101078. len = t1;
  101079. t1 = t2;
  101080. t2 = len;
  101081. }
  101082. if (t2 > 1) t2 = 1;
  101083. if (t1 < 0) t1 = 0;
  101084. tx = sx + (ex - sx) * t1;
  101085. ty = sy + (ey - sy) * t1;
  101086. tz = sz + (ez - sz) * t1;
  101087. ex = sx + (ex - sx) * t2;
  101088. ey = sy + (ey - sy) * t2;
  101089. ez = sz + (ez - sz) * t2;
  101090. sx = tx;
  101091. sy = ty;
  101092. sz = tz;
  101093. len = depth1 + (depth2 - depth1) * t1;
  101094. depth2 = depth1 + (depth2 - depth1) * t2;
  101095. depth1 = len;
  101096. if (depth1 < 0) {
  101097. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  101098. }
  101099. if (depth2 < 0) {
  101100. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  101101. }
  101102. }
  101103. break;
  101104. }
  101105. };
  101106. OIMO.SphereCylinderCollisionDetector = function (flip) {
  101107. OIMO.CollisionDetector.call(this);
  101108. this.flip = flip;
  101109. };
  101110. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101111. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  101112. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101113. var s;
  101114. var c;
  101115. if (this.flip) {
  101116. s = shape2;
  101117. c = shape1;
  101118. } else {
  101119. s = shape1;
  101120. c = shape2;
  101121. }
  101122. var ps = s.position;
  101123. var psx = ps.x;
  101124. var psy = ps.y;
  101125. var psz = ps.z;
  101126. var pc = c.position;
  101127. var pcx = pc.x;
  101128. var pcy = pc.y;
  101129. var pcz = pc.z;
  101130. var dirx = c.normalDirection.x;
  101131. var diry = c.normalDirection.y;
  101132. var dirz = c.normalDirection.z;
  101133. var rads = s.radius;
  101134. var radc = c.radius;
  101135. var rad2 = rads + radc;
  101136. var halfh = c.halfHeight;
  101137. var dx = psx - pcx;
  101138. var dy = psy - pcy;
  101139. var dz = psz - pcz;
  101140. var dot = dx * dirx + dy * diry + dz * dirz;
  101141. if (dot < -halfh - rads || dot > halfh + rads) return;
  101142. var cx = pcx + dot * dirx;
  101143. var cy = pcy + dot * diry;
  101144. var cz = pcz + dot * dirz;
  101145. var d2x = psx - cx;
  101146. var d2y = psy - cy;
  101147. var d2z = psz - cz;
  101148. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  101149. if (len > rad2 * rad2) return;
  101150. if (len > radc * radc) {
  101151. len = radc / OIMO.sqrt(len);
  101152. d2x *= len;
  101153. d2y *= len;
  101154. d2z *= len;
  101155. }
  101156. if (dot < -halfh) dot = -halfh;
  101157. else if (dot > halfh) dot = halfh;
  101158. cx = pcx + dot * dirx + d2x;
  101159. cy = pcy + dot * diry + d2y;
  101160. cz = pcz + dot * dirz + d2z;
  101161. dx = cx - psx;
  101162. dy = cy - psy;
  101163. dz = cz - psz;
  101164. len = dx * dx + dy * dy + dz * dz;
  101165. var invLen;
  101166. if (len > 0 && len < rads * rads) {
  101167. len = OIMO.sqrt(len);
  101168. invLen = 1 / len;
  101169. dx *= invLen;
  101170. dy *= invLen;
  101171. dz *= invLen;
  101172. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  101173. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  101174. }
  101175. };
  101176. /**
  101177. * Class for checking collisions between 2 tetras,
  101178. * a shape that is made with 4 vertices and 4 faces
  101179. * arranged in triangles. With this algorigthm, soft
  101180. * body physics are possible and easier to implement.
  101181. * @author xprogram
  101182. */
  101183. OIMO.TetraTetraCollisionDetector = function () {
  101184. OIMO.CollisionDetector.call(this);
  101185. };
  101186. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101187. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  101188. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  101189. /*
  101190. * What we are doing:
  101191. * Each tetra is represented by four 3D triangles. The only
  101192. * quick way of finding if another tetra is within the other
  101193. * tetra is to see if a single vertex is within the triangles
  101194. * of the other tetra. So, for example, a tetra is represented
  101195. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  101196. * There is another tetra with a vertex A which was detected for
  101197. * collision by the broadphase. Now, if the point A is between ALL
  101198. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  101199. * is valid and we can pass point A to the manifold. Since the only
  101200. * points on the tetra are the 4 vertices, collision detection is
  101201. * not so complex. However, it can be time-consuming because we
  101202. * need to split the 3D triangles into three 2D triangles each for
  101203. * collision detection.
  101204. */
  101205. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  101206. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  101207. // fs is undeclared
  101208. var fs = fs1;
  101209. for (i = 0; i < 4; i++) {
  101210. vec = vs1[i];
  101211. for (j = 0; j < 4; j++) {
  101212. j1 = vs2[fs[i].a];
  101213. j2 = vs2[fs[i].b];
  101214. j3 = vs2[fs[i].c];
  101215. if (
  101216. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  101217. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  101218. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  101219. )
  101220. ts++;
  101221. if (ts === 4) // Only add point if it is inside all 4 triangles
  101222. manifold.addPoint(vec);
  101223. }
  101224. }
  101225. };
  101226. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  101227. function tricheck(p, p0, p1, p2) {
  101228. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  101229. var sg = A < 0 ? -1 : 1;
  101230. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  101231. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  101232. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  101233. }
  101234. function pt(x, y) { return { x: x, y: y }; }
  101235. /**
  101236. * An axis-aligned bounding box.
  101237. * @author saharan
  101238. * @author lo-th
  101239. */
  101240. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  101241. this.elements = new OIMO_ARRAY_TYPE(6);
  101242. var te = this.elements;
  101243. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  101244. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  101245. };
  101246. OIMO.AABB.prototype = {
  101247. constructor: OIMO.AABB,
  101248. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  101249. var te = this.elements;
  101250. te[0] = minX; te[3] = maxX;
  101251. te[1] = minY; te[4] = maxY;
  101252. te[2] = minZ; te[5] = maxZ;
  101253. return this;
  101254. },
  101255. intersectTest: function (aabb) {
  101256. var te = this.elements;
  101257. var ue = aabb.elements;
  101258. 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];
  101259. },
  101260. intersectTestTwo: function (aabb) {
  101261. var te = this.elements;
  101262. var ue = aabb.elements;
  101263. 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];
  101264. },
  101265. clone: function () {
  101266. return new this.constructor().fromArray(this.elements);
  101267. },
  101268. copy: function (aabb, margin) {
  101269. var m = margin || 0;
  101270. var me = aabb.elements;
  101271. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  101272. return this;
  101273. },
  101274. fromArray: function (array) {
  101275. this.elements.set(array);
  101276. return this;
  101277. },
  101278. // Set this AABB to the combined AABB of aabb1 and aabb2.
  101279. combine: function (aabb1, aabb2) {
  101280. var a = aabb1.elements;
  101281. var b = aabb2.elements;
  101282. var te = this.elements;
  101283. te[0] = a[0] < b[0] ? a[0] : b[0];
  101284. te[1] = a[1] < b[1] ? a[1] : b[1];
  101285. te[2] = a[2] < b[2] ? a[2] : b[2];
  101286. te[3] = a[3] > b[3] ? a[3] : b[3];
  101287. te[4] = a[4] > b[4] ? a[4] : b[4];
  101288. te[5] = a[5] > b[5] ? a[5] : b[5];
  101289. return this;
  101290. },
  101291. // Get the surface area.
  101292. surfaceArea: function () {
  101293. var te = this.elements;
  101294. var a = te[3] - te[0];
  101295. var h = te[4] - te[1];
  101296. var d = te[5] - te[2];
  101297. return 2 * (a * (h + d) + h * d);
  101298. },
  101299. // Get whether the AABB intersects with the point or not.
  101300. intersectsWithPoint: function (x, y, z) {
  101301. var te = this.elements;
  101302. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  101303. },
  101304. /**
  101305. * Set the AABB from an array
  101306. * of vertices. From THREE.
  101307. * @author mrdoob
  101308. * @author xprogram
  101309. */
  101310. setFromPoints: function (arr) {
  101311. this.makeEmpty();
  101312. for (var i = 0; i < arr.length; i++) {
  101313. this.expandByPoint(arr[i]);
  101314. }
  101315. },
  101316. makeEmpty: function () {
  101317. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  101318. },
  101319. expandByPoint: function (pt) {
  101320. var te = this.elements;
  101321. this.set(
  101322. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  101323. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  101324. );
  101325. }
  101326. };
  101327. /**
  101328. * A proxy is used for broad-phase collecting pairs that can be colliding.
  101329. */
  101330. OIMO.Proxy = function (shape) {
  101331. // The parent shape.
  101332. this.shape = shape;
  101333. // The axis-aligned bounding box.
  101334. this.aabb = shape.aabb;
  101335. };
  101336. OIMO.Proxy.prototype = {
  101337. constructor: OIMO.Proxy,
  101338. // Update the proxy.
  101339. update: function () {
  101340. OIMO.Error("Proxy", "Inheritance error.");
  101341. }
  101342. };
  101343. /**
  101344. * A basic implementation of proxies.
  101345. * @author saharan
  101346. */
  101347. OIMO.BasicProxy = function (shape) {
  101348. OIMO.Proxy.call(this, shape);
  101349. this.id = OIMO.proxyID++;
  101350. };
  101351. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  101352. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  101353. OIMO.BasicProxy.prototype.update = function () {
  101354. };
  101355. /**
  101356. * The broad-phase is used for collecting all possible pairs for collision.
  101357. */
  101358. OIMO.BroadPhase = function () {
  101359. this.types = OIMO.BR_NULL;
  101360. this.numPairChecks = 0;
  101361. this.numPairs = 0;
  101362. this.pairs = [];
  101363. };
  101364. OIMO.BroadPhase.prototype = {
  101365. constructor: OIMO.BroadPhase,
  101366. /**
  101367. * Create a new proxy.
  101368. * @param shape
  101369. * @return
  101370. */
  101371. createProxy: function (shape) {
  101372. OIMO.Error("BroadPhase", "Inheritance error.");
  101373. },
  101374. /**
  101375. * Add the proxy into the broad-phase.
  101376. * @param proxy
  101377. */
  101378. addProxy: function (proxy) {
  101379. OIMO.Error("BroadPhase", "Inheritance error.");
  101380. },
  101381. /**
  101382. * Remove the proxy from the broad-phase.
  101383. * @param proxy
  101384. */
  101385. removeProxy: function (proxy) {
  101386. OIMO.Error("BroadPhase", "Inheritance error.");
  101387. },
  101388. /**
  101389. * Returns whether the pair is available or not.
  101390. * @param s1
  101391. * @param s2
  101392. * @return
  101393. */
  101394. isAvailablePair: function (s1, s2) {
  101395. var b1 = s1.parent;
  101396. var b2 = s2.parent;
  101397. if (b1 == b2 || // same parents
  101398. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  101399. (s1.belongsTo & s2.collidesWith) == 0 ||
  101400. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  101401. ) { return false; }
  101402. var js;
  101403. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  101404. else js = b2.jointLink;
  101405. while (js !== null) {
  101406. var joint = js.joint;
  101407. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  101408. js = js.next;
  101409. }
  101410. return true;
  101411. },
  101412. // Detect overlapping pairs.
  101413. detectPairs: function () {
  101414. // clear old
  101415. this.pairs = [];
  101416. this.numPairs = 0;
  101417. this.numPairChecks = 0;
  101418. this.collectPairs();
  101419. },
  101420. collectPairs: function () {
  101421. OIMO.Error("BroadPhase", "Inheritance error.");
  101422. },
  101423. addPair: function (s1, s2) {
  101424. var pair = new OIMO.Pair(s1, s2);
  101425. this.pairs.push(pair);
  101426. this.numPairs++;
  101427. }
  101428. };
  101429. /**
  101430. * A broad-phase algorithm with brute-force search.
  101431. * This always checks for all possible pairs.
  101432. */
  101433. OIMO.BruteForceBroadPhase = function () {
  101434. OIMO.BroadPhase.call(this);
  101435. this.types = OIMO.BR_BRUTE_FORCE;;
  101436. //this.numProxies=0;
  101437. ///this.maxProxies = 256;
  101438. this.proxies = [];
  101439. //this.proxies.length = 256;
  101440. };
  101441. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101442. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  101443. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  101444. return new OIMO.BasicProxy(shape);
  101445. };
  101446. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  101447. /*if(this.numProxies==this.maxProxies){
  101448. //this.maxProxies<<=1;
  101449. this.maxProxies*=2;
  101450. var newProxies=[];
  101451. newProxies.length = this.maxProxies;
  101452. var i = this.numProxies;
  101453. while(i--){
  101454. //for(var i=0, l=this.numProxies;i<l;i++){
  101455. newProxies[i]=this.proxies[i];
  101456. }
  101457. this.proxies=newProxies;
  101458. }*/
  101459. //this.proxies[this.numProxies++] = proxy;
  101460. this.proxies.push(proxy);
  101461. //this.numProxies++;
  101462. };
  101463. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  101464. var n = this.proxies.indexOf(proxy);
  101465. if (n > -1) {
  101466. this.proxies.splice(n, 1);
  101467. //this.numProxies--;
  101468. }
  101469. /*var i = this.numProxies;
  101470. while(i--){
  101471. //for(var i=0, l=this.numProxies;i<l;i++){
  101472. if(this.proxies[i] == proxy){
  101473. this.proxies[i] = this.proxies[--this.numProxies];
  101474. this.proxies[this.numProxies] = null;
  101475. return;
  101476. }
  101477. }*/
  101478. };
  101479. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  101480. var i = 0, j, p1, p2;
  101481. var px = this.proxies;
  101482. var l = px.length;//this.numProxies;
  101483. //var ar1 = [];
  101484. //var ar2 = [];
  101485. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  101486. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  101487. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  101488. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  101489. this.numPairChecks = l * (l - 1) >> 1;
  101490. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  101491. while (i < l) {
  101492. p1 = px[i++];
  101493. j = i + 1;
  101494. while (j < l) {
  101495. p2 = px[j++];
  101496. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  101497. this.addPair(p1.shape, p2.shape);
  101498. }
  101499. }
  101500. };
  101501. /**
  101502. * A pair of shapes that may collide.
  101503. * @author saharan
  101504. */
  101505. OIMO.Pair = function (s1, s2) {
  101506. // The first shape.
  101507. this.shape1 = s1 || null;
  101508. // The second shape.
  101509. this.shape2 = s2 || null;
  101510. };
  101511. /**
  101512. * A projection axis for sweep and prune broad-phase.
  101513. * @author saharan
  101514. */
  101515. OIMO.SAPAxis = function () {
  101516. this.numElements = 0;
  101517. this.bufferSize = 256;
  101518. this.elements = [];
  101519. this.elements.length = this.bufferSize;
  101520. this.stack = new OIMO_ARRAY_TYPE(64);
  101521. };
  101522. OIMO.SAPAxis.prototype = {
  101523. constructor: OIMO.SAPAxis,
  101524. addElements: function (min, max) {
  101525. if (this.numElements + 2 >= this.bufferSize) {
  101526. //this.bufferSize<<=1;
  101527. this.bufferSize *= 2;
  101528. var newElements = [];
  101529. var i = this.numElements;
  101530. while (i--) {
  101531. //for(var i=0, l=this.numElements; i<l; i++){
  101532. newElements[i] = this.elements[i];
  101533. }
  101534. }
  101535. this.elements[this.numElements++] = min;
  101536. this.elements[this.numElements++] = max;
  101537. },
  101538. removeElements: function (min, max) {
  101539. var minIndex = -1;
  101540. var maxIndex = -1;
  101541. for (var i = 0, l = this.numElements; i < l; i++) {
  101542. var e = this.elements[i];
  101543. if (e == min || e == max) {
  101544. if (minIndex == -1) {
  101545. minIndex = i;
  101546. } else {
  101547. maxIndex = i;
  101548. break;
  101549. }
  101550. }
  101551. }
  101552. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  101553. this.elements[i - 1] = this.elements[i];
  101554. }
  101555. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  101556. this.elements[i - 2] = this.elements[i];
  101557. }
  101558. this.elements[--this.numElements] = null;
  101559. this.elements[--this.numElements] = null;
  101560. },
  101561. sort: function () {
  101562. var count = 0;
  101563. var threshold = 1;
  101564. while ((this.numElements >> threshold) != 0) threshold++;
  101565. threshold = threshold * this.numElements >> 2;
  101566. count = 0;
  101567. var giveup = false;
  101568. var elements = this.elements;
  101569. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  101570. var tmp = elements[i];
  101571. var pivot = tmp.value;
  101572. var tmp2 = elements[i - 1];
  101573. if (tmp2.value > pivot) {
  101574. var j = i;
  101575. do {
  101576. elements[j] = tmp2;
  101577. if (--j == 0) break;
  101578. tmp2 = elements[j - 1];
  101579. } while (tmp2.value > pivot);
  101580. elements[j] = tmp;
  101581. count += i - j;
  101582. if (count > threshold) {
  101583. giveup = true; // stop and use quick sort
  101584. break;
  101585. }
  101586. }
  101587. }
  101588. if (!giveup) return;
  101589. count = 2; var stack = this.stack;
  101590. stack[0] = 0;
  101591. stack[1] = this.numElements - 1;
  101592. while (count > 0) {
  101593. var right = stack[--count];
  101594. var left = stack[--count];
  101595. var diff = right - left;
  101596. if (diff > 16) { // quick sort
  101597. //var mid=left+(diff>>1);
  101598. var mid = left + (OIMO.floor(diff * 0.5));
  101599. tmp = elements[mid];
  101600. elements[mid] = elements[right];
  101601. elements[right] = tmp;
  101602. pivot = tmp.value;
  101603. i = left - 1;
  101604. j = right;
  101605. while (true) {
  101606. var ei;
  101607. var ej;
  101608. do { ei = elements[++i]; } while (ei.value < pivot);
  101609. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  101610. if (i >= j) break;
  101611. elements[i] = ej;
  101612. elements[j] = ei;
  101613. }
  101614. elements[right] = elements[i];
  101615. elements[i] = tmp;
  101616. if (i - left > right - i) {
  101617. stack[count++] = left;
  101618. stack[count++] = i - 1;
  101619. stack[count++] = i + 1;
  101620. stack[count++] = right;
  101621. } else {
  101622. stack[count++] = i + 1;
  101623. stack[count++] = right;
  101624. stack[count++] = left;
  101625. stack[count++] = i - 1;
  101626. }
  101627. } else {
  101628. for (i = left + 1; i <= right; i++) {
  101629. tmp = elements[i];
  101630. pivot = tmp.value;
  101631. tmp2 = elements[i - 1];
  101632. if (tmp2.value > pivot) {
  101633. j = i;
  101634. do {
  101635. elements[j] = tmp2;
  101636. if (--j == 0) break;
  101637. tmp2 = elements[j - 1];
  101638. } while (tmp2.value > pivot);
  101639. elements[j] = tmp;
  101640. }
  101641. }
  101642. }
  101643. }
  101644. },
  101645. calculateTestCount: function () {
  101646. var num = 1;
  101647. var sum = 0;
  101648. for (var i = 1, l = this.numElements; i < l; i++) {
  101649. if (this.elements[i].max) {
  101650. num--;
  101651. } else {
  101652. sum += num;
  101653. num++;
  101654. }
  101655. }
  101656. return sum;
  101657. }
  101658. }
  101659. /**
  101660. * A broad-phase collision detection algorithm using sweep and prune.
  101661. * @author saharan
  101662. * @author lo-th
  101663. */
  101664. OIMO.SAPBroadPhase = function () {
  101665. OIMO.BroadPhase.call(this);
  101666. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  101667. this.numElementsD = 0;
  101668. this.numElementsS = 0;
  101669. // dynamic proxies
  101670. this.axesD = [
  101671. new OIMO.SAPAxis(),
  101672. new OIMO.SAPAxis(),
  101673. new OIMO.SAPAxis()
  101674. ];
  101675. // static or sleeping proxies
  101676. this.axesS = [
  101677. new OIMO.SAPAxis(),
  101678. new OIMO.SAPAxis(),
  101679. new OIMO.SAPAxis()
  101680. ];
  101681. this.index1 = 0;
  101682. this.index2 = 1;
  101683. };
  101684. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101685. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  101686. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  101687. return new OIMO.SAPProxy(this, shape);
  101688. };
  101689. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  101690. var p = proxy;
  101691. if (p.isDynamic()) {
  101692. this.axesD[0].addElements(p.min[0], p.max[0]);
  101693. this.axesD[1].addElements(p.min[1], p.max[1]);
  101694. this.axesD[2].addElements(p.min[2], p.max[2]);
  101695. p.belongsTo = 1;
  101696. this.numElementsD += 2;
  101697. } else {
  101698. this.axesS[0].addElements(p.min[0], p.max[0]);
  101699. this.axesS[1].addElements(p.min[1], p.max[1]);
  101700. this.axesS[2].addElements(p.min[2], p.max[2]);
  101701. p.belongsTo = 2;
  101702. this.numElementsS += 2;
  101703. }
  101704. };
  101705. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  101706. var p = proxy;
  101707. if (p.belongsTo == 0) return;
  101708. /*else if ( p.belongsTo == 1 ) {
  101709. this.axesD[0].removeElements( p.min[0], p.max[0] );
  101710. this.axesD[1].removeElements( p.min[1], p.max[1] );
  101711. this.axesD[2].removeElements( p.min[2], p.max[2] );
  101712. this.numElementsD -= 2;
  101713. } else if ( p.belongsTo == 2 ) {
  101714. this.axesS[0].removeElements( p.min[0], p.max[0] );
  101715. this.axesS[1].removeElements( p.min[1], p.max[1] );
  101716. this.axesS[2].removeElements( p.min[2], p.max[2] );
  101717. this.numElementsS -= 2;
  101718. }*/
  101719. switch (p.belongsTo) {
  101720. case 1:
  101721. this.axesD[0].removeElements(p.min[0], p.max[0]);
  101722. this.axesD[1].removeElements(p.min[1], p.max[1]);
  101723. this.axesD[2].removeElements(p.min[2], p.max[2]);
  101724. this.numElementsD -= 2;
  101725. break;
  101726. case 2:
  101727. this.axesS[0].removeElements(p.min[0], p.max[0]);
  101728. this.axesS[1].removeElements(p.min[1], p.max[1]);
  101729. this.axesS[2].removeElements(p.min[2], p.max[2]);
  101730. this.numElementsS -= 2;
  101731. break;
  101732. }
  101733. p.belongsTo = 0;
  101734. };
  101735. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  101736. if (this.numElementsD == 0) return;
  101737. var axis1 = this.axesD[this.index1];
  101738. var axis2 = this.axesD[this.index2];
  101739. axis1.sort();
  101740. axis2.sort();
  101741. var count1 = axis1.calculateTestCount();
  101742. var count2 = axis2.calculateTestCount();
  101743. var elementsD;
  101744. var elementsS;
  101745. if (count1 <= count2) {// select the best axis
  101746. axis2 = this.axesS[this.index1];
  101747. axis2.sort();
  101748. elementsD = axis1.elements;
  101749. elementsS = axis2.elements;
  101750. } else {
  101751. axis1 = this.axesS[this.index2];
  101752. axis1.sort();
  101753. elementsD = axis2.elements;
  101754. elementsS = axis1.elements;
  101755. this.index1 ^= this.index2;
  101756. this.index2 ^= this.index1;
  101757. this.index1 ^= this.index2;
  101758. }
  101759. var activeD;
  101760. var activeS;
  101761. var p = 0;
  101762. var q = 0;
  101763. while (p < this.numElementsD) {
  101764. var e1;
  101765. var dyn;
  101766. if (q == this.numElementsS) {
  101767. e1 = elementsD[p];
  101768. dyn = true;
  101769. p++;
  101770. } else {
  101771. var d = elementsD[p];
  101772. var s = elementsS[q];
  101773. if (d.value < s.value) {
  101774. e1 = d;
  101775. dyn = true;
  101776. p++;
  101777. } else {
  101778. e1 = s;
  101779. dyn = false;
  101780. q++;
  101781. }
  101782. }
  101783. if (!e1.max) {
  101784. var s1 = e1.proxy.shape;
  101785. var min1 = e1.min1.value;
  101786. var max1 = e1.max1.value;
  101787. var min2 = e1.min2.value;
  101788. var max2 = e1.max2.value;
  101789. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  101790. var s2 = e2.proxy.shape;
  101791. this.numPairChecks++;
  101792. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  101793. this.addPair(s1, s2);
  101794. }
  101795. if (dyn) {
  101796. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  101797. s2 = e2.proxy.shape;
  101798. this.numPairChecks++;
  101799. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  101800. this.addPair(s1, s2);
  101801. }
  101802. e1.pair = activeD;
  101803. activeD = e1;
  101804. } else {
  101805. e1.pair = activeS;
  101806. activeS = e1;
  101807. }
  101808. } else {
  101809. var min = e1.pair;
  101810. if (dyn) {
  101811. if (min == activeD) {
  101812. activeD = activeD.pair;
  101813. continue;
  101814. } else {
  101815. e1 = activeD;
  101816. }
  101817. } else {
  101818. if (min == activeS) {
  101819. activeS = activeS.pair;
  101820. continue;
  101821. } else {
  101822. e1 = activeS;
  101823. }
  101824. }
  101825. do {
  101826. e2 = e1.pair;
  101827. if (e2 == min) {
  101828. e1.pair = e2.pair;
  101829. break;
  101830. }
  101831. e1 = e2;
  101832. } while (e1 != null);
  101833. }
  101834. }
  101835. this.index2 = (this.index1 | this.index2) ^ 3;
  101836. };
  101837. /**
  101838. * An element of proxies.
  101839. * @author saharan
  101840. */
  101841. OIMO.SAPElement = function (proxy, max) {
  101842. // The parent proxy
  101843. this.proxy = proxy;
  101844. // The pair element.
  101845. this.pair = null;
  101846. // The minimum element on other axis.
  101847. this.min1 = null;
  101848. // The maximum element on other axis.
  101849. this.max1 = null;
  101850. // The minimum element on other axis.
  101851. this.min2 = null;
  101852. // The maximum element on other axis.
  101853. this.max2 = null;
  101854. // Whether the element has maximum value or not.
  101855. this.max = max;
  101856. // The value of the element.
  101857. this.value = 0;
  101858. };
  101859. /**
  101860. * A proxy for sweep and prune broad-phase.
  101861. * @author saharan
  101862. * @author lo-th
  101863. */
  101864. OIMO.SAPProxy = function (sap, shape) {
  101865. OIMO.Proxy.call(this, shape);
  101866. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  101867. this.belongsTo = 0;
  101868. // The maximum elements on each axis.
  101869. this.max = [];
  101870. // The minimum elements on each axis.
  101871. this.min = [];
  101872. this.sap = sap;
  101873. this.min[0] = new OIMO.SAPElement(this, false);
  101874. this.max[0] = new OIMO.SAPElement(this, true);
  101875. this.min[1] = new OIMO.SAPElement(this, false);
  101876. this.max[1] = new OIMO.SAPElement(this, true);
  101877. this.min[2] = new OIMO.SAPElement(this, false);
  101878. this.max[2] = new OIMO.SAPElement(this, true);
  101879. this.max[0].pair = this.min[0];
  101880. this.max[1].pair = this.min[1];
  101881. this.max[2].pair = this.min[2];
  101882. this.min[0].min1 = this.min[1];
  101883. this.min[0].max1 = this.max[1];
  101884. this.min[0].min2 = this.min[2];
  101885. this.min[0].max2 = this.max[2];
  101886. this.min[1].min1 = this.min[0];
  101887. this.min[1].max1 = this.max[0];
  101888. this.min[1].min2 = this.min[2];
  101889. this.min[1].max2 = this.max[2];
  101890. this.min[2].min1 = this.min[0];
  101891. this.min[2].max1 = this.max[0];
  101892. this.min[2].min2 = this.min[1];
  101893. this.min[2].max2 = this.max[1];
  101894. };
  101895. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  101896. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  101897. // Returns whether the proxy is dynamic or not.
  101898. OIMO.SAPProxy.prototype.isDynamic = function () {
  101899. var body = this.shape.parent;
  101900. return body.isDynamic && !body.sleeping;
  101901. };
  101902. OIMO.SAPProxy.prototype.update = function () {
  101903. var te = this.aabb.elements;
  101904. this.min[0].value = te[0];
  101905. this.min[1].value = te[1];
  101906. this.min[2].value = te[2];
  101907. this.max[0].value = te[3];
  101908. this.max[1].value = te[4];
  101909. this.max[2].value = te[5];
  101910. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  101911. this.sap.removeProxy(this);
  101912. this.sap.addProxy(this);
  101913. }
  101914. };
  101915. /**
  101916. * A dynamic bounding volume tree for the broad-phase algorithm.
  101917. * @author saharan
  101918. * @author lo-th
  101919. */
  101920. OIMO.DBVT = function () {
  101921. // The root of the tree.
  101922. this.root = null;
  101923. this.freeNodes = [];
  101924. this.freeNodes.length = 16384;
  101925. this.numFreeNodes = 0;
  101926. this.aabb = new OIMO.AABB();
  101927. };
  101928. OIMO.DBVT.prototype = {
  101929. constructor: OIMO.DBVT,
  101930. /**
  101931. * Move a leaf.
  101932. * @param leaf
  101933. */
  101934. moveLeaf: function (leaf) {
  101935. this.deleteLeaf(leaf);
  101936. this.insertLeaf(leaf);
  101937. },
  101938. /**
  101939. * Insert a leaf to the tree.
  101940. * @param node
  101941. */
  101942. insertLeaf: function (leaf) {
  101943. if (this.root == null) {
  101944. this.root = leaf;
  101945. return;
  101946. }
  101947. var lb = leaf.aabb;
  101948. var sibling = this.root;
  101949. var oldArea;
  101950. var newArea;
  101951. while (sibling.proxy == null) { // descend the node to search the best pair
  101952. var c1 = sibling.child1;
  101953. var c2 = sibling.child2;
  101954. var b = sibling.aabb;
  101955. var c1b = c1.aabb;
  101956. var c2b = c2.aabb;
  101957. oldArea = b.surfaceArea();
  101958. this.aabb.combine(lb, b);
  101959. newArea = this.aabb.surfaceArea();
  101960. var creatingCost = newArea * 2;
  101961. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  101962. var discendingCost1 = incrementalCost;
  101963. this.aabb.combine(lb, c1b);
  101964. if (c1.proxy != null) {
  101965. // leaf cost = area(combined aabb)
  101966. discendingCost1 += this.aabb.surfaceArea();
  101967. } else {
  101968. // node cost = area(combined aabb) - area(old aabb)
  101969. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  101970. }
  101971. var discendingCost2 = incrementalCost;
  101972. this.aabb.combine(lb, c2b);
  101973. if (c2.proxy != null) {
  101974. // leaf cost = area(combined aabb)
  101975. discendingCost2 += this.aabb.surfaceArea();
  101976. } else {
  101977. // node cost = area(combined aabb) - area(old aabb)
  101978. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  101979. }
  101980. if (discendingCost1 < discendingCost2) {
  101981. if (creatingCost < discendingCost1) {
  101982. break;// stop descending
  101983. } else {
  101984. sibling = c1;// descend into first child
  101985. }
  101986. } else {
  101987. if (creatingCost < discendingCost2) {
  101988. break;// stop descending
  101989. } else {
  101990. sibling = c2;// descend into second child
  101991. }
  101992. }
  101993. }
  101994. var oldParent = sibling.parent;
  101995. var newParent;
  101996. if (this.numFreeNodes > 0) {
  101997. newParent = this.freeNodes[--this.numFreeNodes];
  101998. } else {
  101999. newParent = new OIMO.DBVTNode();
  102000. }
  102001. newParent.parent = oldParent;
  102002. newParent.child1 = leaf;
  102003. newParent.child2 = sibling;
  102004. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  102005. newParent.height = sibling.height + 1;
  102006. sibling.parent = newParent;
  102007. leaf.parent = newParent;
  102008. if (sibling == this.root) {
  102009. // replace root
  102010. this.root = newParent;
  102011. } else {
  102012. // replace child
  102013. if (oldParent.child1 == sibling) {
  102014. oldParent.child1 = newParent;
  102015. } else {
  102016. oldParent.child2 = newParent;
  102017. }
  102018. }
  102019. // update whole tree
  102020. do {
  102021. newParent = this.balance(newParent);
  102022. this.fix(newParent);
  102023. newParent = newParent.parent;
  102024. } while (newParent != null);
  102025. },
  102026. getBalance: function (node) {
  102027. if (node.proxy != null) return 0;
  102028. return node.child1.height - node.child2.height;
  102029. },
  102030. /*print:function(node,indent,text){
  102031. var hasChild=node.proxy==null;
  102032. if(hasChild)text=this.print(node.child1,indent+1,text);
  102033. for(var i=indent*2;i>=0;i--){
  102034. text+=" ";
  102035. }
  102036. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  102037. if(hasChild)text=this.print(node.child2,indent+1,text);
  102038. return text;
  102039. },*/
  102040. /**
  102041. * Delete a leaf from the tree.
  102042. * @param node
  102043. */
  102044. deleteLeaf: function (leaf) {
  102045. if (leaf == this.root) {
  102046. this.root = null;
  102047. return;
  102048. }
  102049. var parent = leaf.parent;
  102050. var sibling;
  102051. if (parent.child1 == leaf) {
  102052. sibling = parent.child2;
  102053. } else {
  102054. sibling = parent.child1;
  102055. }
  102056. if (parent == this.root) {
  102057. this.root = sibling;
  102058. sibling.parent = null;
  102059. return;
  102060. }
  102061. var grandParent = parent.parent;
  102062. sibling.parent = grandParent;
  102063. if (grandParent.child1 == parent) {
  102064. grandParent.child1 = sibling;
  102065. } else {
  102066. grandParent.child2 = sibling;
  102067. }
  102068. if (this.numFreeNodes < 16384) {
  102069. this.freeNodes[this.numFreeNodes++] = parent;
  102070. }
  102071. do {
  102072. grandParent = this.balance(grandParent);
  102073. this.fix(grandParent);
  102074. grandParent = grandParent.parent;
  102075. } while (grandParent != null);
  102076. },
  102077. balance: function (node) {
  102078. var nh = node.height;
  102079. if (nh < 2) {
  102080. return node;
  102081. }
  102082. var p = node.parent;
  102083. var l = node.child1;
  102084. var r = node.child2;
  102085. var lh = l.height;
  102086. var rh = r.height;
  102087. var balance = lh - rh;
  102088. var t;// for bit operation
  102089. // [ N ]
  102090. // / \
  102091. // [ L ] [ R ]
  102092. // / \ / \
  102093. // [L-L] [L-R] [R-L] [R-R]
  102094. // Is the tree balanced?
  102095. if (balance > 1) {
  102096. var ll = l.child1;
  102097. var lr = l.child2;
  102098. var llh = ll.height;
  102099. var lrh = lr.height;
  102100. // Is L-L higher than L-R?
  102101. if (llh > lrh) {
  102102. // set N to L-R
  102103. l.child2 = node;
  102104. node.parent = l;
  102105. // [ L ]
  102106. // / \
  102107. // [L-L] [ N ]
  102108. // / \ / \
  102109. // [...] [...] [ L ] [ R ]
  102110. // set L-R
  102111. node.child1 = lr;
  102112. lr.parent = node;
  102113. // [ L ]
  102114. // / \
  102115. // [L-L] [ N ]
  102116. // / \ / \
  102117. // [...] [...] [L-R] [ R ]
  102118. // fix bounds and heights
  102119. node.aabb.combine(lr.aabb, r.aabb);
  102120. t = lrh - rh;
  102121. node.height = lrh - (t & t >> 31) + 1;
  102122. l.aabb.combine(ll.aabb, node.aabb);
  102123. t = llh - nh;
  102124. l.height = llh - (t & t >> 31) + 1;
  102125. } else {
  102126. // set N to L-L
  102127. l.child1 = node;
  102128. node.parent = l;
  102129. // [ L ]
  102130. // / \
  102131. // [ N ] [L-R]
  102132. // / \ / \
  102133. // [ L ] [ R ] [...] [...]
  102134. // set L-L
  102135. node.child1 = ll;
  102136. ll.parent = node;
  102137. // [ L ]
  102138. // / \
  102139. // [ N ] [L-R]
  102140. // / \ / \
  102141. // [L-L] [ R ] [...] [...]
  102142. // fix bounds and heights
  102143. node.aabb.combine(ll.aabb, r.aabb);
  102144. t = llh - rh;
  102145. node.height = llh - (t & t >> 31) + 1;
  102146. l.aabb.combine(node.aabb, lr.aabb);
  102147. t = nh - lrh;
  102148. l.height = nh - (t & t >> 31) + 1;
  102149. }
  102150. // set new parent of L
  102151. if (p != null) {
  102152. if (p.child1 == node) {
  102153. p.child1 = l;
  102154. } else {
  102155. p.child2 = l;
  102156. }
  102157. } else {
  102158. this.root = l;
  102159. }
  102160. l.parent = p;
  102161. return l;
  102162. } else if (balance < -1) {
  102163. var rl = r.child1;
  102164. var rr = r.child2;
  102165. var rlh = rl.height;
  102166. var rrh = rr.height;
  102167. // Is R-L higher than R-R?
  102168. if (rlh > rrh) {
  102169. // set N to R-R
  102170. r.child2 = node;
  102171. node.parent = r;
  102172. // [ R ]
  102173. // / \
  102174. // [R-L] [ N ]
  102175. // / \ / \
  102176. // [...] [...] [ L ] [ R ]
  102177. // set R-R
  102178. node.child2 = rr;
  102179. rr.parent = node;
  102180. // [ R ]
  102181. // / \
  102182. // [R-L] [ N ]
  102183. // / \ / \
  102184. // [...] [...] [ L ] [R-R]
  102185. // fix bounds and heights
  102186. node.aabb.combine(l.aabb, rr.aabb);
  102187. t = lh - rrh;
  102188. node.height = lh - (t & t >> 31) + 1;
  102189. r.aabb.combine(rl.aabb, node.aabb);
  102190. t = rlh - nh;
  102191. r.height = rlh - (t & t >> 31) + 1;
  102192. } else {
  102193. // set N to R-L
  102194. r.child1 = node;
  102195. node.parent = r;
  102196. // [ R ]
  102197. // / \
  102198. // [ N ] [R-R]
  102199. // / \ / \
  102200. // [ L ] [ R ] [...] [...]
  102201. // set R-L
  102202. node.child2 = rl;
  102203. rl.parent = node;
  102204. // [ R ]
  102205. // / \
  102206. // [ N ] [R-R]
  102207. // / \ / \
  102208. // [ L ] [R-L] [...] [...]
  102209. // fix bounds and heights
  102210. node.aabb.combine(l.aabb, rl.aabb);
  102211. t = lh - rlh;
  102212. node.height = lh - (t & t >> 31) + 1;
  102213. r.aabb.combine(node.aabb, rr.aabb);
  102214. t = nh - rrh;
  102215. r.height = nh - (t & t >> 31) + 1;
  102216. }
  102217. // set new parent of R
  102218. if (p != null) {
  102219. if (p.child1 == node) {
  102220. p.child1 = r;
  102221. } else {
  102222. p.child2 = r;
  102223. }
  102224. } else {
  102225. this.root = r;
  102226. }
  102227. r.parent = p;
  102228. return r;
  102229. }
  102230. return node;
  102231. },
  102232. fix: function (node) {
  102233. var c1 = node.child1;
  102234. var c2 = node.child2;
  102235. node.aabb.combine(c1.aabb, c2.aabb);
  102236. //var h1 = c1.height;
  102237. //var h2 = c2.height;
  102238. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  102239. /*if( h1 < h2 ) {
  102240. node.height = h2+1;
  102241. }else{
  102242. node.height = h1+1;
  102243. }*/
  102244. }
  102245. }
  102246. /**
  102247. * A broad-phase algorithm using dynamic bounding volume tree.
  102248. * @author saharan
  102249. * @author lo-th
  102250. */
  102251. OIMO.DBVTBroadPhase = function () {
  102252. OIMO.BroadPhase.call(this);
  102253. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  102254. this.tree = new OIMO.DBVT();
  102255. this.stack = [];
  102256. this.leaves = [];
  102257. this.numLeaves = 0;
  102258. };
  102259. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102260. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  102261. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  102262. return new OIMO.DBVTProxy(shape);
  102263. };
  102264. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  102265. this.tree.insertLeaf(proxy.leaf);
  102266. this.leaves.push(proxy.leaf);
  102267. this.numLeaves++;
  102268. };
  102269. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  102270. this.tree.deleteLeaf(proxy.leaf);
  102271. var n = this.leaves.indexOf(proxy.leaf);
  102272. if (n > -1) {
  102273. this.leaves.splice(n, 1);
  102274. this.numLeaves--;
  102275. }
  102276. };
  102277. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  102278. if (this.numLeaves < 2) return;
  102279. var leaf, margin = 0.1, i = this.numLeaves;
  102280. while (i--) {
  102281. leaf = this.leaves[i];
  102282. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  102283. leaf.aabb.copy(leaf.proxy.aabb, margin);
  102284. this.tree.deleteLeaf(leaf);
  102285. this.tree.insertLeaf(leaf);
  102286. this.collide(leaf, this.tree.root);
  102287. }
  102288. }
  102289. };
  102290. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  102291. var stackCount = 2;
  102292. var s1, s2, n1, n2, l1, l2;
  102293. this.stack[0] = node1;
  102294. this.stack[1] = node2;
  102295. while (stackCount > 0) {
  102296. n1 = this.stack[--stackCount];
  102297. n2 = this.stack[--stackCount];
  102298. l1 = n1.proxy != null;
  102299. l2 = n2.proxy != null;
  102300. this.numPairChecks++;
  102301. if (l1 && l2) {
  102302. s1 = n1.proxy.shape;
  102303. s2 = n2.proxy.shape;
  102304. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  102305. this.addPair(s1, s2);
  102306. } else {
  102307. if (n1.aabb.intersectTest(n2.aabb)) continue;
  102308. /*if(stackCount+4>=this.maxStack){// expand the stack
  102309. //this.maxStack<<=1;
  102310. this.maxStack*=2;
  102311. var newStack = [];// vector
  102312. newStack.length = this.maxStack;
  102313. for(var i=0;i<stackCount;i++){
  102314. newStack[i] = this.stack[i];
  102315. }
  102316. this.stack = newStack;
  102317. }*/
  102318. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  102319. this.stack[stackCount++] = n1.child1;
  102320. this.stack[stackCount++] = n2;
  102321. this.stack[stackCount++] = n1.child2;
  102322. this.stack[stackCount++] = n2;
  102323. } else {
  102324. this.stack[stackCount++] = n1;
  102325. this.stack[stackCount++] = n2.child1;
  102326. this.stack[stackCount++] = n1;
  102327. this.stack[stackCount++] = n2.child2;
  102328. }
  102329. }
  102330. }
  102331. };
  102332. /**
  102333. * A node of the dynamic bounding volume tree.
  102334. * @author saharan
  102335. */
  102336. OIMO.DBVTNode = function () {
  102337. // The first child node of this node.
  102338. this.child1 = null;
  102339. // The second child node of this node.
  102340. this.child2 = null;
  102341. // The parent node of this tree.
  102342. this.parent = null;
  102343. // The proxy of this node. This has no value if this node is not leaf.
  102344. this.proxy = null;
  102345. // The maximum distance from leaf nodes.
  102346. this.height = 0;
  102347. // The AABB of this node.
  102348. this.aabb = new OIMO.AABB();
  102349. };
  102350. /**
  102351. * A proxy for dynamic bounding volume tree broad-phase.
  102352. * @author saharan
  102353. */
  102354. OIMO.DBVTProxy = function (shape) {
  102355. OIMO.Proxy.call(this, shape);
  102356. // The leaf of the proxy.
  102357. this.leaf = new OIMO.DBVTNode();
  102358. this.leaf.proxy = this;
  102359. };
  102360. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102361. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  102362. OIMO.DBVTProxy.prototype.update = function () {
  102363. };
  102364. OIMO.World.prototype.add = function (obj) {
  102365. obj = obj || {};
  102366. var type = obj.type || "box";
  102367. if (typeof type === 'string') type = [type];// single shape
  102368. if (type[0].substring(0, 5) == 'joint') { // is joint
  102369. if (type[0] === 'joint') type[0] = 'jointHinge';
  102370. var axe1 = obj.axe1 || [1, 0, 0];
  102371. var axe2 = obj.axe2 || [1, 0, 0];
  102372. var pos1 = obj.pos1 || [0, 0, 0];
  102373. var pos2 = obj.pos2 || [0, 0, 0];
  102374. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  102375. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  102376. var min, max;
  102377. if (type[0] === "jointDistance") {
  102378. min = obj.min || 0;
  102379. max = obj.max || 10;
  102380. min = min * OIMO.INV_SCALE;
  102381. max = max * OIMO.INV_SCALE;
  102382. } else {
  102383. min = obj.min || 57.29578;
  102384. max = obj.max || 0;
  102385. min = min * OIMO.degtorad;
  102386. max = max * OIMO.degtorad;
  102387. }
  102388. var limit = obj.limit || null;
  102389. var spring = obj.spring || null;
  102390. var motor = obj.motor || null;
  102391. // joint setting
  102392. var jc = new OIMO.JointConfig();
  102393. jc.allowCollision = obj.collision || false;;
  102394. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  102395. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  102396. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  102397. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  102398. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  102399. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  102400. jc.body1 = obj.body1;
  102401. jc.body2 = obj.body2;
  102402. var joint;
  102403. switch (type[0]) {
  102404. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  102405. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  102406. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  102407. break;
  102408. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  102409. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  102410. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  102411. break;
  102412. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  102413. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  102414. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  102415. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  102416. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  102417. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  102418. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  102419. break;
  102420. }
  102421. joint.name = obj.name || '';
  102422. // finaly add to physics world
  102423. this.addJoint(joint);
  102424. return joint;
  102425. } else { // is body
  102426. // I'm dynamique or not
  102427. var move = obj.move || false;
  102428. // I can sleep or not
  102429. var noSleep = obj.noSleep || false;
  102430. // My start position
  102431. var p = obj.pos || [0, 0, 0];
  102432. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  102433. // My size
  102434. var s = obj.size || [1, 1, 1];
  102435. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  102436. // My rotation in degre
  102437. var rot = obj.rot || [0, 0, 0];
  102438. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  102439. var r = [];
  102440. for (var i = 0; i < rot.length / 3; i++) {
  102441. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  102442. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  102443. }
  102444. // My physics setting
  102445. var sc = new OIMO.ShapeConfig();
  102446. if (obj.sc !== undefined) sc = obj.sc;
  102447. if (obj.config) {
  102448. // The density of the shape.
  102449. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  102450. // The coefficient of friction of the shape.
  102451. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  102452. // The coefficient of restitution of the shape.
  102453. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  102454. // The bits of the collision groups to which the shape belongs.
  102455. sc.belongsTo = obj.config[3] || 1;
  102456. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  102457. // The bits of the collision groups with which the shape collides.
  102458. sc.collidesWith = obj.config[4] || 0xffffffff;
  102459. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  102460. }
  102461. // direct physics setting
  102462. if (obj.density !== undefined) sc.density = obj.density;
  102463. if (obj.friction !== undefined) sc.friction = obj.friction;
  102464. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  102465. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  102466. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  102467. if (obj.massPos) {
  102468. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  102469. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  102470. }
  102471. if (obj.massRot) {
  102472. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  102473. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  102474. }
  102475. // My rigidbody
  102476. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  102477. // My shapes
  102478. var shapes = [];
  102479. //if( typeof type === 'string' ) type = [type];// single shape
  102480. var n, n2;
  102481. for (var i = 0; i < type.length; i++) {
  102482. n = i * 3;
  102483. n2 = i * 4;
  102484. switch (type[i]) {
  102485. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  102486. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  102487. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  102488. }
  102489. body.addShape(shapes[i]);
  102490. if (i > 0) {
  102491. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  102492. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  102493. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  102494. }
  102495. }
  102496. // I'm static or i move
  102497. if (move) {
  102498. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  102499. else body.setupMass(0x1, true);
  102500. if (noSleep) body.allowSleep = false;
  102501. else body.allowSleep = true;
  102502. } else {
  102503. body.setupMass(0x2);
  102504. }
  102505. body.name = obj.name || ' ';
  102506. // finaly add to physics world
  102507. this.addRigidBody(body);
  102508. return body;
  102509. }
  102510. }
  102511. //UMD simplified
  102512. var root = this;
  102513. if (!root['OIMO']) {
  102514. if (true)
  102515. module.exports = OIMO;
  102516. else if (typeof define === 'function' && define.amd)
  102517. define([], function () {
  102518. return OIMO;
  102519. });
  102520. else if (typeof exports === 'object')
  102521. exports["OIMO"] = OIMO;
  102522. else {
  102523. root["OIMO"] = OIMO;
  102524. }
  102525. }
  102526. /***/ }),
  102527. /* 17 */
  102528. /***/ (function(module, exports, __webpack_require__) {
  102529. "use strict";
  102530. Object.defineProperty(exports, "__esModule", { value: true });
  102531. var babylonjs_1 = __webpack_require__(0);
  102532. var helper_1 = __webpack_require__(3);
  102533. var TemplateManager = (function () {
  102534. function TemplateManager(containerElement) {
  102535. this.containerElement = containerElement;
  102536. this.templates = {};
  102537. this.onInit = new babylonjs_1.Observable();
  102538. this.onLoaded = new babylonjs_1.Observable();
  102539. this.onStateChange = new babylonjs_1.Observable();
  102540. this.onAllLoaded = new babylonjs_1.Observable();
  102541. }
  102542. TemplateManager.prototype.initTemplate = function (templates) {
  102543. var _this = this;
  102544. var internalInit = function (dependencyMap, name, parentTemplate) {
  102545. var template = _this.templates[name];
  102546. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  102547. return internalInit(dependencyMap[childName], childName, template);
  102548. });
  102549. var addToParent = function () {
  102550. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  102551. template.appendTo(containingElement);
  102552. _this.checkLoadedState();
  102553. };
  102554. if (parentTemplate && !parentTemplate.parent) {
  102555. parentTemplate.onAppended.add(function () {
  102556. addToParent();
  102557. });
  102558. }
  102559. else {
  102560. addToParent();
  102561. }
  102562. return template;
  102563. };
  102564. this.buildHTMLTree(templates).then(function (htmlTree) {
  102565. internalInit(htmlTree, 'main');
  102566. });
  102567. };
  102568. TemplateManager.prototype.buildHTMLTree = function (templates) {
  102569. var _this = this;
  102570. var promises = Object.keys(templates).map(function (name) {
  102571. var template = new Template(name, templates[name]);
  102572. _this.templates[name] = template;
  102573. return template.initPromise;
  102574. });
  102575. return Promise.all(promises).then(function () {
  102576. var templateStructure = {};
  102577. var buildTree = function (parentObject, name) {
  102578. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  102579. childNodes.forEach(function (element) {
  102580. parentObject[element] = {};
  102581. buildTree(parentObject[element], element);
  102582. });
  102583. };
  102584. buildTree(templateStructure, "main");
  102585. return templateStructure;
  102586. });
  102587. };
  102588. TemplateManager.prototype.getCanvas = function () {
  102589. return this.containerElement.querySelector('canvas');
  102590. };
  102591. TemplateManager.prototype.getTemplate = function (name) {
  102592. return this.templates[name];
  102593. };
  102594. TemplateManager.prototype.checkLoadedState = function () {
  102595. var _this = this;
  102596. var done = Object.keys(this.templates).every(function (key) {
  102597. return _this.templates[key].isLoaded && !!_this.templates[key].parent;
  102598. });
  102599. if (done) {
  102600. this.onAllLoaded.notifyObservers(this);
  102601. }
  102602. };
  102603. return TemplateManager;
  102604. }());
  102605. exports.TemplateManager = TemplateManager;
  102606. var Handlebars = __webpack_require__(18);
  102607. Handlebars.registerHelper('eachInMap', function (map, block) {
  102608. var out = '';
  102609. Object.keys(map).map(function (prop) {
  102610. var data = map[prop];
  102611. if (typeof data === 'object') {
  102612. data.id = data.id || prop;
  102613. out += block.fn(data);
  102614. }
  102615. else {
  102616. out += block.fn({ id: prop, value: data });
  102617. }
  102618. });
  102619. return out;
  102620. });
  102621. var Template = (function () {
  102622. function Template(name, _configuration) {
  102623. var _this = this;
  102624. this.name = name;
  102625. this._configuration = _configuration;
  102626. this.onInit = new babylonjs_1.Observable();
  102627. this.onLoaded = new babylonjs_1.Observable();
  102628. this.onAppended = new babylonjs_1.Observable();
  102629. this.onStateChange = new babylonjs_1.Observable();
  102630. this.onEventTriggered = new babylonjs_1.Observable();
  102631. this.isLoaded = false;
  102632. this.onInit.notifyObservers(this);
  102633. var htmlContentPromise = getTemplateAsHtml(_configuration);
  102634. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  102635. if (htmlTemplate) {
  102636. var compiledTemplate = Handlebars.compile(htmlTemplate);
  102637. var config = _this._configuration.params || {};
  102638. var rawHtml = compiledTemplate(config);
  102639. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  102640. _this.isLoaded = true;
  102641. _this.onLoaded.notifyObservers(_this);
  102642. }
  102643. return _this;
  102644. });
  102645. }
  102646. Object.defineProperty(Template.prototype, "configuration", {
  102647. get: function () {
  102648. return this._configuration;
  102649. },
  102650. enumerable: true,
  102651. configurable: true
  102652. });
  102653. Template.prototype.getChildElements = function () {
  102654. var childrenArray = [];
  102655. var children = this.fragment.children;
  102656. if (!children) {
  102657. children = this.fragment.querySelectorAll('*');
  102658. }
  102659. for (var i = 0; i < children.length; ++i) {
  102660. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  102661. }
  102662. return childrenArray;
  102663. };
  102664. Template.prototype.appendTo = function (parent) {
  102665. var _this = this;
  102666. if (this.parent) {
  102667. console.error('Already appanded to ', this.parent);
  102668. }
  102669. else {
  102670. this.parent = parent;
  102671. if (this._configuration.id) {
  102672. this.parent.id = this._configuration.id;
  102673. }
  102674. this.parent.appendChild(this.fragment);
  102675. setTimeout(function () {
  102676. _this.registerEvents();
  102677. _this.onAppended.notifyObservers(_this);
  102678. });
  102679. }
  102680. };
  102681. Template.prototype.show = function (visibilityFunction) {
  102682. var _this = this;
  102683. if (visibilityFunction) {
  102684. return visibilityFunction(this).then(function () {
  102685. _this.onStateChange.notifyObservers(_this);
  102686. return _this;
  102687. });
  102688. }
  102689. else {
  102690. this.parent.style.display = 'flex';
  102691. this.onStateChange.notifyObservers(this);
  102692. return Promise.resolve(this);
  102693. }
  102694. };
  102695. Template.prototype.hide = function (visibilityFunction) {
  102696. var _this = this;
  102697. if (visibilityFunction) {
  102698. return visibilityFunction(this).then(function () {
  102699. _this.onStateChange.notifyObservers(_this);
  102700. return _this;
  102701. });
  102702. }
  102703. else {
  102704. this.parent.style.display = 'none';
  102705. this.onStateChange.notifyObservers(this);
  102706. return Promise.resolve(this);
  102707. }
  102708. };
  102709. Template.prototype.registerEvents = function () {
  102710. var _this = this;
  102711. if (this._configuration.events) {
  102712. var _loop_1 = function (eventName) {
  102713. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  102714. var functionToFire_1 = function (selector, event) {
  102715. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  102716. };
  102717. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  102718. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  102719. }
  102720. else if (typeof this_1._configuration.events[eventName] === 'object') {
  102721. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  102722. var event_1 = this_1._configuration.events[eventName] || {};
  102723. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  102724. if (selector.indexOf('#') !== 0) {
  102725. selector = '#' + selector;
  102726. }
  102727. var htmlElement = _this.parent.querySelector(selector);
  102728. htmlElement && htmlElement.addEventListener(eventName, functionToFire_1.bind(_this, selector), false);
  102729. });
  102730. }
  102731. }
  102732. };
  102733. var this_1 = this;
  102734. for (var eventName in this._configuration.events) {
  102735. _loop_1(eventName);
  102736. }
  102737. }
  102738. };
  102739. return Template;
  102740. }());
  102741. exports.Template = Template;
  102742. function getTemplateAsHtml(templateConfig) {
  102743. if (!templateConfig) {
  102744. return Promise.reject('No templateConfig provided');
  102745. }
  102746. else if (templateConfig.html) {
  102747. return Promise.resolve(templateConfig.html);
  102748. }
  102749. else {
  102750. var location_1 = getTemplateLocation(templateConfig);
  102751. if (helper_1.isUrl(location_1)) {
  102752. return helper_1.loadFile(location_1);
  102753. }
  102754. else {
  102755. location_1 = location_1.replace('#', '');
  102756. var element = document.getElementById(location_1);
  102757. if (element) {
  102758. return Promise.resolve(element.innerHTML);
  102759. }
  102760. else {
  102761. return Promise.reject('Template ID not found');
  102762. }
  102763. }
  102764. }
  102765. }
  102766. exports.getTemplateAsHtml = getTemplateAsHtml;
  102767. function getTemplateLocation(templateConfig) {
  102768. if (!templateConfig || typeof templateConfig === 'string') {
  102769. return templateConfig;
  102770. }
  102771. else {
  102772. return templateConfig.location;
  102773. }
  102774. }
  102775. exports.getTemplateLocation = getTemplateLocation;
  102776. /***/ }),
  102777. /* 18 */
  102778. /***/ (function(module, exports, __webpack_require__) {
  102779. /**!
  102780. @license
  102781. handlebars v4.0.11
  102782. Copyright (C) 2011-2017 by Yehuda Katz
  102783. Permission is hereby granted, free of charge, to any person obtaining a copy
  102784. of this software and associated documentation files (the "Software"), to deal
  102785. in the Software without restriction, including without limitation the rights
  102786. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  102787. copies of the Software, and to permit persons to whom the Software is
  102788. furnished to do so, subject to the following conditions:
  102789. The above copyright notice and this permission notice shall be included in
  102790. all copies or substantial portions of the Software.
  102791. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  102792. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  102793. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  102794. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  102795. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  102796. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  102797. THE SOFTWARE.
  102798. */
  102799. !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],
  102800. 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){
  102801. 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"]}])});
  102802. /***/ }),
  102803. /* 19 */
  102804. /***/ (function(module, exports, __webpack_require__) {
  102805. "use strict";
  102806. Object.defineProperty(exports, "__esModule", { value: true });
  102807. var mappers_1 = __webpack_require__(2);
  102808. var types_1 = __webpack_require__(20);
  102809. var deepmerge = __webpack_require__(27);
  102810. var ConfigurationLoader = (function () {
  102811. function ConfigurationLoader() {
  102812. }
  102813. ConfigurationLoader.prototype.loadConfiguration = function (initConfig) {
  102814. if (initConfig === void 0) { initConfig = {}; }
  102815. var loadedConfig = deepmerge({}, initConfig);
  102816. var extendedConfiguration = types_1.getConfigurationType(loadedConfig && loadedConfig.extends);
  102817. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  102818. if (loadedConfig.configuration) {
  102819. var mapperType = "json";
  102820. var url = loadedConfig.configuration;
  102821. if (loadedConfig.configuration.url) {
  102822. url = loadedConfig.configuration.url;
  102823. mapperType = loadedConfig.configuration.mapper;
  102824. if (!mapperType) {
  102825. mapperType = loadedConfig.configuration.url.split('.').pop();
  102826. }
  102827. }
  102828. var mapper_1 = mappers_1.mapperManager.getMapper(mapperType);
  102829. return this.loadFile(url).then(function (data) {
  102830. var parsed = mapper_1.map(data);
  102831. return deepmerge(loadedConfig, parsed);
  102832. });
  102833. }
  102834. else {
  102835. return Promise.resolve(loadedConfig);
  102836. }
  102837. };
  102838. ConfigurationLoader.prototype.getConfigurationType = function (type) {
  102839. };
  102840. ConfigurationLoader.prototype.loadFile = function (url) {
  102841. var cacheReference = this.configurationCache;
  102842. if (cacheReference[url]) {
  102843. return Promise.resolve(cacheReference[url]);
  102844. }
  102845. return new Promise(function (resolve, reject) {
  102846. var xhr = new XMLHttpRequest();
  102847. xhr.open('GET', url);
  102848. xhr.send();
  102849. xhr.onreadystatechange = function () {
  102850. var DONE = 4;
  102851. var OK = 200;
  102852. if (xhr.readyState === DONE) {
  102853. if (xhr.status === OK) {
  102854. cacheReference[url] = xhr.responseText;
  102855. resolve(xhr.responseText);
  102856. }
  102857. }
  102858. else {
  102859. console.log('Error: ' + xhr.status, url);
  102860. reject('Error: ' + xhr.status);
  102861. }
  102862. };
  102863. });
  102864. };
  102865. return ConfigurationLoader;
  102866. }());
  102867. exports.ConfigurationLoader = ConfigurationLoader;
  102868. exports.configurationLoader = new ConfigurationLoader();
  102869. exports.default = exports.configurationLoader;
  102870. /***/ }),
  102871. /* 20 */
  102872. /***/ (function(module, exports, __webpack_require__) {
  102873. "use strict";
  102874. Object.defineProperty(exports, "__esModule", { value: true });
  102875. var minimal_1 = __webpack_require__(21);
  102876. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  102877. var default_1 = __webpack_require__(22);
  102878. exports.defaultConfiguration = default_1.defaultConfiguration;
  102879. var getConfigurationType = function (type) {
  102880. switch (type) {
  102881. case 'default':
  102882. return default_1.defaultConfiguration;
  102883. case 'minimal':
  102884. return minimal_1.minimalConfiguration;
  102885. default:
  102886. return default_1.defaultConfiguration;
  102887. }
  102888. };
  102889. exports.getConfigurationType = getConfigurationType;
  102890. /***/ }),
  102891. /* 21 */
  102892. /***/ (function(module, exports, __webpack_require__) {
  102893. "use strict";
  102894. Object.defineProperty(exports, "__esModule", { value: true });
  102895. exports.minimalConfiguration = {
  102896. version: "0.1",
  102897. templates: {
  102898. main: {
  102899. html: __webpack_require__(7)
  102900. },
  102901. loadingScreen: {
  102902. html: __webpack_require__(8),
  102903. params: {
  102904. backgroundColor: "#000000",
  102905. loadingImage: __webpack_require__(9)
  102906. }
  102907. },
  102908. viewer: {
  102909. html: __webpack_require__(10),
  102910. },
  102911. overlay: {
  102912. html: __webpack_require__(11),
  102913. params: {
  102914. closeImage: __webpack_require__(12),
  102915. closeText: 'Close'
  102916. }
  102917. },
  102918. error: {
  102919. html: __webpack_require__(13)
  102920. }
  102921. },
  102922. engine: {
  102923. antialiasing: true
  102924. }
  102925. };
  102926. /***/ }),
  102927. /* 22 */
  102928. /***/ (function(module, exports, __webpack_require__) {
  102929. "use strict";
  102930. Object.defineProperty(exports, "__esModule", { value: true });
  102931. exports.defaultConfiguration = {
  102932. version: "0.1",
  102933. templates: {
  102934. main: {
  102935. html: __webpack_require__(7)
  102936. },
  102937. loadingScreen: {
  102938. html: __webpack_require__(8),
  102939. params: {
  102940. backgroundColor: "#000000",
  102941. loadingImage: __webpack_require__(9)
  102942. }
  102943. },
  102944. viewer: {
  102945. html: __webpack_require__(10),
  102946. },
  102947. navBar: {
  102948. html: __webpack_require__(23),
  102949. params: {
  102950. buttons: {
  102951. "fullscreen-button": {
  102952. altText: "Fullscreen",
  102953. image: __webpack_require__(24)
  102954. }
  102955. },
  102956. visibilityTimeout: 2000
  102957. },
  102958. events: {
  102959. pointerdown: { 'fullscreen-button': true }
  102960. }
  102961. },
  102962. overlay: {
  102963. html: __webpack_require__(11),
  102964. params: {
  102965. closeImage: __webpack_require__(12),
  102966. closeText: 'Close'
  102967. }
  102968. },
  102969. help: {
  102970. html: __webpack_require__(25)
  102971. },
  102972. share: {
  102973. html: __webpack_require__(26)
  102974. },
  102975. error: {
  102976. html: __webpack_require__(13)
  102977. }
  102978. },
  102979. camera: {
  102980. behaviors: {
  102981. autoRotate: 0,
  102982. framing: {
  102983. type: 2,
  102984. zoomOnBoundingInfo: true,
  102985. zoomStopsAnimation: false
  102986. }
  102987. }
  102988. },
  102989. skybox: {
  102990. cubeTexture: {
  102991. url: 'https://playground.babylonjs.com/textures/environment.dds',
  102992. gammaSpace: false
  102993. },
  102994. pbr: true,
  102995. blur: 0.7,
  102996. infiniteDIstance: false,
  102997. material: {
  102998. imageProcessingConfiguration: {
  102999. colorCurves: {
  103000. globalDensity: 89,
  103001. globalHue: 58.88,
  103002. globalSaturation: 94
  103003. },
  103004. colorCurvesEnabled: true,
  103005. exposure: 1.5,
  103006. contrast: 1.66,
  103007. toneMappingEnabled: true,
  103008. vignetteEnabled: true,
  103009. vignetteWeight: 5,
  103010. vignetteColor: { r: 0.8, g: 0.6, b: 0.4 },
  103011. vignetteM: true
  103012. }
  103013. }
  103014. },
  103015. ground: true,
  103016. engine: {
  103017. antialiasing: true
  103018. },
  103019. scene: {
  103020. imageProcessingConfiguration: {
  103021. exposure: 1.4,
  103022. contrast: 1.66,
  103023. toneMappingEnabled: true
  103024. }
  103025. }
  103026. };
  103027. /***/ }),
  103028. /* 23 */
  103029. /***/ (function(module, exports) {
  103030. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  103031. /***/ }),
  103032. /* 24 */
  103033. /***/ (function(module, exports) {
  103034. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  103035. /***/ }),
  103036. /* 25 */
  103037. /***/ (function(module, exports) {
  103038. module.exports = "HELP";
  103039. /***/ }),
  103040. /* 26 */
  103041. /***/ (function(module, exports) {
  103042. module.exports = "SHARE";
  103043. /***/ }),
  103044. /* 27 */
  103045. /***/ (function(module, exports, __webpack_require__) {
  103046. (function (global, factory) {
  103047. true ? module.exports = factory() :
  103048. typeof define === 'function' && define.amd ? define(factory) :
  103049. (global.deepmerge = factory());
  103050. }(this, (function () { 'use strict';
  103051. var isMergeableObject = function isMergeableObject(value) {
  103052. return isNonNullObject(value)
  103053. && !isSpecial(value)
  103054. };
  103055. function isNonNullObject(value) {
  103056. return !!value && typeof value === 'object'
  103057. }
  103058. function isSpecial(value) {
  103059. var stringValue = Object.prototype.toString.call(value);
  103060. return stringValue === '[object RegExp]'
  103061. || stringValue === '[object Date]'
  103062. || isReactElement(value)
  103063. }
  103064. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  103065. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  103066. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  103067. function isReactElement(value) {
  103068. return value.$$typeof === REACT_ELEMENT_TYPE
  103069. }
  103070. function emptyTarget(val) {
  103071. return Array.isArray(val) ? [] : {}
  103072. }
  103073. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  103074. var clone = !optionsArgument || optionsArgument.clone !== false;
  103075. return (clone && isMergeableObject(value))
  103076. ? deepmerge(emptyTarget(value), value, optionsArgument)
  103077. : value
  103078. }
  103079. function defaultArrayMerge(target, source, optionsArgument) {
  103080. return target.concat(source).map(function(element) {
  103081. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  103082. })
  103083. }
  103084. function mergeObject(target, source, optionsArgument) {
  103085. var destination = {};
  103086. if (isMergeableObject(target)) {
  103087. Object.keys(target).forEach(function(key) {
  103088. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  103089. });
  103090. }
  103091. Object.keys(source).forEach(function(key) {
  103092. if (!isMergeableObject(source[key]) || !target[key]) {
  103093. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  103094. } else {
  103095. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  103096. }
  103097. });
  103098. return destination
  103099. }
  103100. function deepmerge(target, source, optionsArgument) {
  103101. var sourceIsArray = Array.isArray(source);
  103102. var targetIsArray = Array.isArray(target);
  103103. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  103104. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  103105. if (!sourceAndTargetTypesMatch) {
  103106. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  103107. } else if (sourceIsArray) {
  103108. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  103109. return arrayMerge(target, source, optionsArgument)
  103110. } else {
  103111. return mergeObject(target, source, optionsArgument)
  103112. }
  103113. }
  103114. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  103115. if (!Array.isArray(array)) {
  103116. throw new Error('first argument should be an array')
  103117. }
  103118. return array.reduce(function(prev, next) {
  103119. return deepmerge(prev, next, optionsArgument)
  103120. }, {})
  103121. };
  103122. var deepmerge_1 = deepmerge;
  103123. return deepmerge_1;
  103124. })));
  103125. /***/ }),
  103126. /* 28 */
  103127. /***/ (function(module, exports, __webpack_require__) {
  103128. "use strict";
  103129. var __extends = (this && this.__extends) || (function () {
  103130. var extendStatics = Object.setPrototypeOf ||
  103131. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103132. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103133. return function (d, b) {
  103134. extendStatics(d, b);
  103135. function __() { this.constructor = d; }
  103136. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103137. };
  103138. })();
  103139. Object.defineProperty(exports, "__esModule", { value: true });
  103140. var babylonjs_1 = __webpack_require__(0);
  103141. var PromiseObservable = (function (_super) {
  103142. __extends(PromiseObservable, _super);
  103143. function PromiseObservable() {
  103144. return _super !== null && _super.apply(this, arguments) || this;
  103145. }
  103146. PromiseObservable.prototype.notifyWithPromise = function (eventData, mask, target, currentTarget) {
  103147. if (mask === void 0) { mask = -1; }
  103148. var p = Promise.resolve();
  103149. if (!this._observers.length) {
  103150. return p;
  103151. }
  103152. var state = this['_eventState'];
  103153. state.mask = mask;
  103154. state.target = target;
  103155. state.currentTarget = currentTarget;
  103156. state.skipNextObservers = false;
  103157. this._observers.forEach(function (obs) {
  103158. if (state.skipNextObservers) {
  103159. return;
  103160. }
  103161. if (obs.mask & mask) {
  103162. if (obs.scope) {
  103163. p = p.then(function () {
  103164. return obs.callback.apply(obs.scope, [eventData, state]);
  103165. });
  103166. }
  103167. else {
  103168. p = p.then(function () {
  103169. return obs.callback(eventData, state);
  103170. });
  103171. }
  103172. }
  103173. });
  103174. return p;
  103175. };
  103176. return PromiseObservable;
  103177. }(babylonjs_1.Observable));
  103178. exports.PromiseObservable = PromiseObservable;
  103179. /***/ }),
  103180. /* 29 */
  103181. /***/ (function(module, exports, __webpack_require__) {
  103182. /* 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 _=f+12*m;i[a]=n.getFloat32(_,!0),i[a+2]=n.getFloat32(_+4,!0),i[a+1]=n.getFloat32(_+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=0,T=!1,A=[],y=[],v=[],g=[],L="",b="",x=new t,N=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},S=function(e,t,n,o,a,i){var s;s=r.OPTIMIZE_WITH_UV?F(_,[e,n,t]):O(_,[e,n]),-1==s?(d.push(h.length),h.push(o),p.push(a),m.push(i),_[e].normals.push(n),_[e].idx.push(E++),r.OPTIMIZE_WITH_UV&&_[e].uv.push(t)):d.push(s)},R=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),v.push(p[e].x,p[e].y);h=[],m=[],p=[],_=[],E=0},w=function(e,t){t+1<e.length&&(g.push(e[0],e[t],e[t+1]),t+=1,w(e,t))},I=function(){f.length>0&&(s=f[f.length-1],R(),d.reverse(),s.indices=d.slice(),s.positions=A.slice(),s.normals=y.slice(),s.uvs=v.slice(),d=[],A=[],y=[],v=[])},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){w(e,t);for(var r=0;r<g.length;r++){var n=g[r].split("/"),o=parseInt(n[0])-1,a=parseInt(n[1])-1,i=parseInt(n[2])-1;S(o,a,i,l[o],c[a],u[i])}g=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern4.exec(G)))!(function(t,r){w(t,r);for(var n=0;n<g.length;n++){var o=g[n].split("//"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;S(a,1,i,l[a],e.Vector2.Zero(),u[i])}g=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern2.exec(G)))!(function(t,r){w(t,r);for(var n=0;n<g.length;n++){var o=g[n].split("/"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;S(a,i,0,l[a],c[i],e.Vector3.Up())}g=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern1.exec(G)))!(function(t,r){w(t,r);for(var n=0;n<g.length;n++){var o=parseInt(g[n])-1;S(o,0,0,l[o],e.Vector2.Zero(),e.Vector3.Up())}g=[]})(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:""};I(),f.push(D),T=!0,M=!0,N=1}else if(this.usemtl.test(G)){if(L=G.substring(7).trim(),!M){I();var D={name:"_mm"+N.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:L};N++,f.push(D)}T&&M&&(f[f.length-1].materialName=L,M=!1)}else this.mtllib.test(G)?b=G.substring(7).trim():this.smooth.test(G)||console.log("Unhandled expression at line : "+G)}T&&(s=f[f.length-1],d.reverse(),R(),s.indices=d,s.positions=A,s.normals=y,s.uvs=v),T||(d.reverse(),R(),f.push({name:e.Geometry.RandomId(),indices:d,positions:A,normals:y,uvs:v,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""!==b&&this._loadMTL(b,i,(function(e){x.parseMTL(o,e,i);for(var t=0;t<x.materials.length;t++){for(var r,n=0,a=[];(r=U.indexOf(x.materials[t].name,n))>-1;)a.push(r),n=r+1;if(-1==r&&0==a.length)x.materials[t].dispose();else for(var s=0;s<a.length;s++)V[a[s]].material=x.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.compileMaterials=!1,this.compileShadowGenerators=!1,this.useClipPlane=!1,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.prototype.createPlugin=function(){return new e},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,_=r.scene.getNodeByID(m);if(null===_&&(_=r.scene.getNodeByName(m)),null!==_){var E=_ instanceof e.Bone,T=u.target.path,A=i.indexOf(T);-1!==A&&(T=s[A]);var y=e.Animation.ANIMATIONTYPE_MATRIX;E||("rotationQuaternion"===T?(y=e.Animation.ANIMATIONTYPE_QUATERNION,_.rotationQuaternion=new e.Quaternion):y=e.Animation.ANIMATIONTYPE_VECTOR3);var v=null,g=[],L=0,b=!1;E&&a&&a.getKeys().length===h.length&&(v=a,b=!0),b||(v=new e.Animation(n,E?"_matrix":T,1,y,e.Animation.ANIMATIONLOOPMODE_CYCLE));for(var x=0;x<h.length;x++){var N=null;if("rotationQuaternion"===T?(N=e.Quaternion.FromArray([p[L],p[L+1],p[L+2],p[L+3]]),L+=4):(N=e.Vector3.FromArray([p[L],p[L+1],p[L+2]]),L+=3),E){var M=_,O=e.Vector3.Zero(),F=new e.Quaternion,S=e.Vector3.Zero(),R=M.getBaseMatrix();b&&a&&(R=a.getKeys()[x].value),R.decompose(S,F,O),"position"===T?O=N:"rotationQuaternion"===T?F=N:S=N,N=e.Matrix.Compose(S,F,O)}b?a&&(a.getKeys()[x].value=N):g.push({frame:h[x],value:N})}!b&&v&&(v.setKeys(g),_.animations.push(v)),a=v,r.scene.stopAnimation(_),r.scene.beginAnimation(_,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},_=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},E=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},T=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&&!T(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,_=0;_<o.length;_++)if(o[_].id===d[h]){m=o[_];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=E(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,T=0;T<l;T++){var y=E(t,r.jointNames[T]);if(y){var v=y.node;if(v){var g=v.children;if(g){d=!1;for(var L=0;L<g.length;L++)if(g[L]===a){h=m(t,r,r.jointNames[T],o),d=!0;break}if(d)break}}else e.Tools.Warn("Joint named "+r.jointNames[T]+" does not exist when looking for parent")}}var b=p(c);!h&&i.length>0&&(h=_(i,a))&&-1===s.indexOf(h)&&s.push(h);new e.Bone(c.jointName||"",o,h,b).id=a}}else e.Tools.Warn("Joint named "+r.jointNames[l]+" does not exist")}}var x=o.bones;o.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=E(t,r.jointNames[l]);if(u)for(var T=0;T<x.length;T++)if(x[T].id===u.id){o.bones.push(x[T]);break}}o.prepare();for(var l=0;l<s.length;l++)o.bones.push(s[l]);return o},v=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 _=o[m],E=r.meshes[_];if(E)for(var T=0;T<E.primitives.length;T++){var A=new e.VertexData,y=E.primitives[T];y.mode;var v=y.attributes,g=null,L=null;for(var b in v)if(g=r.accessors[v[b]],L=t.GLTFUtils.GetBufferFromAccessor(r,g),"NORMAL"===b)A.normals=new Float32Array(L.length),A.normals.set(L);else if("POSITION"===b){if(e.GLTFFileLoader.HomogeneousCoordinates){A.positions=new Float32Array(L.length-L.length/4);for(var x=0;x<L.length;x+=4)A.positions[x]=L[x],A.positions[x+1]=L[x+1],A.positions[x+2]=L[x+2]}else A.positions=new Float32Array(L.length),A.positions.set(L);d.push(A.positions.length)}else if(-1!==b.indexOf("TEXCOORD_")){var N=Number(b.split("_")[1]),M=e.VertexBuffer.UVKind+(0===N?"":N+1),O=new Float32Array(L.length);O.set(L),f(O),A.set(O,M)}else"JOINT"===b?(A.matricesIndices=new Float32Array(L.length),A.matricesIndices.set(L)):"WEIGHT"===b?(A.matricesWeights=new Float32Array(L.length),A.matricesWeights.set(L)):"COLOR"===b&&(A.colors=new Float32Array(L.length),A.colors.set(L));if(g=r.accessors[y.indices])L=t.GLTFUtils.GetBufferFromAccessor(r,g),A.indices=new Int32Array(L.length),A.indices.set(L),p.push(A.indices.length);else{for(var F=[],x=0;x<A.positions.length/3;x++)F.push(x);A.indices=new Int32Array(F),p.push(A.indices.length)}l.merge(A);var S=r.scene.getMaterialByID(y.material);s.subMaterials.push(null===S?t.GLTFUtils.GetDefaultMaterial(r.scene):S),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 R=0,m=0;m<o.length;m++){var _=o[m],E=r.meshes[_];if(E)for(var T=0;T<E.primitives.length;T++)E.primitives[T].mode,e.SubMesh.AddToMesh(R,c[R],d[R],h[R],p[R],i,i,!0),R++}return i},g=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),g(t,o,a,i)}else r.translation&&r.rotation&&r.scale&&g(t,e.Vector3.FromArray(r.translation),e.Quaternion.FromArray(r.rotation),e.Vector3.FromArray(r.scale));t.computeWorldMatrix(!0)},b=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=v(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=v(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],_=new e.DirectionalLight(r.light,e.Vector3.Zero(),t.scene);_.name=r.name||"",m.color&&(_.diffuse=e.Color3.FromArray(m.color)),a=_}else if("point"===d.type){var E=d[d.type],T=new e.PointLight(r.light,e.Vector3.Zero(),t.scene);T.name=r.name||"",E.color&&(T.diffuse=e.Color3.FromArray(E.color)),a=T}else if("spot"===d.type){var A=d[d.type],b=new e.SpotLight(r.light,e.Vector3.Zero(),e.Vector3.Zero(),0,0,t.scene);b.name=r.name||"",A.color&&(b.diffuse=e.Color3.FromArray(A.color)),A.fallOfAngle&&(b.angle=A.fallOfAngle),A.fallOffExponent&&(b.exponent=A.fallOffExponent),a=b}}if(!r.jointName){if(r.babylonNode)return r.babylonNode;if(null===a){var x=new e.Mesh(r.name||"",t.scene);r.babylonNode=x,a=x}}if(null!==a){if(r.matrix&&a instanceof e.Mesh)L(a,r);else{var N=r.translation||[0,0,0],M=r.rotation||[0,0,0,1],O=r.scale||[1,1,1];g(a,e.Vector3.FromArray(N),e.Quaternion.FromArray(M),e.Vector3.FromArray(O))}a.updateCache(!0),r.babylonNode=a}return a},x=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=b(e,o,t))&&(a.id=t,a.parent=r),o.children)for(var i=0;i<o.children.length;i++)x(e,o.children[i],a,n)},N=function(e){var t=e.currentScene;if(t)for(var r=0;r<t.nodes.length;r++)x(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++)x(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")}},S=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)}}},R=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},w=function(e){for(var r in e.materials)t.GLTFLoaderExtension.LoadMaterialAsync(e,r,(function(e){}),(function(){}))},I=(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)
  103183. ;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)},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.Effect.ShadersStore[p.vertexShader+"VertexShader"],E=e.Effect.ShadersStore[p.fragmentShader+"PixelShader"],T="",A="",y=new n(_),v=new n(E),g={},L=[],b=[],x=[];for(var N in f.uniforms){var M=f.uniforms[N],O=f.parameters[M];if(g[N]=O,!O.semantic||O.node||O.source)O.type===t.EParameterType.SAMPLER_2D?x.push(N):L.push(N);else{var w=o.indexOf(O.semantic);-1!==w?(L.push(a[w]),delete g[N]):L.push(N)}}for(var I in f.attributes){var P=f.attributes[I],B=f.parameters[P];B.semantic&&b.push(d(B))}for(;!y.isEnd()&&y.getNextToken();){var C=y.currentToken;if(C===r.IDENTIFIER){var G=!1;for(var I in f.attributes){var P=f.attributes[I],B=f.parameters[P];if(y.currentIdentifier===I&&B.semantic){T+=d(B),G=!0;break}}G||(T+=R(y,f,g))}else T+=y.currentString}for(;!v.isEnd()&&v.getNextToken();){var C=v.currentToken;C===r.IDENTIFIER?A+=R(v,f,g):A+=v.currentString}var D={vertex:p.vertexShader+s,fragment:p.fragmentShader+s},V={attributes:b,uniforms:L,samplers:x,needAlphaBlending:m&&m.enable&&-1!==m.enable.indexOf(3042)};e.Effect.ShadersStore[p.vertexShader+s+"VertexShader"]=T,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=S(i,U,f,c,g,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=I;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(){w(t),N(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(){w(r),N(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++)x(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++)x(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,n._progressEventFactory||("function"==typeof window.ProgressEvent?n._progressEventFactory=n._createProgressEventByConstructor:n._progressEventFactory=n._createProgressEventByDocument)}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._createProgressEventByConstructor=function(e,t){return new ProgressEvent(e,t)},n._createProgressEventByDocument=function(e,t){var r=document.createEvent("ProgressEvent");return r.initProgressEvent(e,!1,!1,t.lengthComputable,t.loaded,t.total),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(){if(this._progressCallback){for(var e=0,t=0,r=0,o=this._requests;r<o.length;r++){var a=o[r];if(!a._loaded||!a._total)return;e+=a._loaded,t+=a._total}this._progressCallback(n._progressEventFactory("GLTFLoaderProgress",{lengthComputable:!0,loaded:e,total:t}))}},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)}this._parent.onMeshLoaded&&this._parent.onMeshLoaded(this._rootNode.babylonMesh);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(!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=o.babylonAnimationTargets||[],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)}this._parent.onMeshLoaded&&this._parent.onMeshLoaded(o.babylonMesh)}},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 r=i[e];if(null==r.material)l[e]=u._getDefaultMaterial();else{var o=n._GetProperty(u._gltf.materials,r.material);if(!o)throw new Error(t+": Failed to find material "+r.material);u._loadMaterial("#/materials/"+o.index,o,(function(t,r){r&&a._parent.onMaterialLoaded&&a._parent.onMaterialLoaded(t),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=t.babylonBones||{},t.babylonBones[r.index]=s,t.babylonAnimationTargets=t.babylonAnimationTargets||[],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)
  103184. ;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);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 _=t.name||"anim"+t.index,E=new e.Animation(_,l,1,u);if(E.setKeys(d),s.babylonAnimationTargets)for(var T=0,A=s.babylonAnimationTargets;T<A.length;T++){var y=A[T];y.animations.push(E.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(t,r,n){var o=this;if(this._addPendingData(r),r.loadedData)n(r.loadedData),this._removePendingData(r);else if(r.loadedObservable)r.loadedObservable.add((function(e){n(e.loadedData),o._removePendingData(e)}));else{if(!r.uri)throw new Error(t+": Uri is missing");r.loadedObservable=new e.Observable,r.loadedObservable.add((function(e){n(e.loadedData),o._removePendingData(e)})),this._loadUriAsync(t,r.uri,(function(e){r.loadedData=e,r.loadedObservable.notifyObservers(r),r.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){var t=this;this._renderReady||0==--this._renderPendingCount&&(this._addLoaderPendingData(this),this._compileMaterialsAsync((function(){t._compileShadowGeneratorsAsync((function(){t._removeLoaderPendingData(t),t._renderReady=!0,t._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._loadImageAsync("#/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._loadImageAsync=function(e,t,r){if(t.uri)this._loadUriAsync(e,t.uri,r);else{var o=n._GetProperty(this._gltf.bufferViews,t.bufferView);if(!o)throw new Error(e+": Failed to find buffer view "+t.bufferView);this._loadBufferViewAsync("#/bufferViews/"+o.index,o,r)}},n.prototype._loadUriAsync=function(r,n,o){var a=this;if(t.GLTFUtils.IsBase64(n))return void o(new Uint8Array(t.GLTFUtils.DecodeBase64(n)));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(){i&&!a._renderReady&&(i._loaded=e.loaded,i._total=e.total,a._onProgress())}))}),this._babylonScene.database,!0,(function(e){a._tryCatchOnError((function(){throw new Error(r+": Failed to load '"+n+"'"+(e?": "+e.status+" "+e.statusText:""))}))}));i&&(i._loaded=null,i._total=null,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.prototype._compileMaterialAsync=function(e,t,r){var n=this;if(!this._parent.compileMaterials)return void r();this._parent.useClipPlane?e.forceCompilation(t,(function(){e.forceCompilation(t,(function(){n._tryCatchOnError(r)}),{clipPlane:!0})})):e.forceCompilation(t,(function(){n._tryCatchOnError(r)}))},n.prototype._compileMaterialsAsync=function(t){if(!this._parent.compileMaterials||!this._gltf.materials)return void t();for(var r=this._getMeshes(),n=0,o=0,a=r;o<a.length;o++){var i=a[o];if(i.material instanceof e.MultiMaterial)for(var s=0,l=i.material.subMaterials;s<l.length;s++){var u=l[s];u&&n++}}if(0===n)return void t();for(var c=0,f=r;c<f.length;c++){var i=f[c];if(i.material instanceof e.MultiMaterial)for(var d=0,h=i.material.subMaterials;d<h.length;d++){var u=h[d];u&&this._compileMaterialAsync(u,i,(function(){0==--n&&t()}))}}},n.prototype._compileShadowGeneratorsAsync=function(e){var t=this;if(!this._parent.compileShadowGenerators)return void e();for(var r=this._babylonScene.lights,n=0,o=0,a=r;o<a.length;o++){var i=a[o],s=i.getShadowGenerator();s&&n++}if(0===n)return void e();for(var l=0,u=r;l<u.length;l++){var i=u[l],s=i.getShadowGenerator();s&&s.forceCompilation((function(){0==--n&&t._tryCatchOnError(e)}))}},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(){var e=null!==r&&r.apply(this,arguments)||this;return e.Delay=250,e}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,n,o){var a=this;e._whenAction((function(){e._loadNode(t,r[n])}),(function(){if(n!==r.length-1){r[n+1].babylonMesh.setEnabled(!1)}if(0===n)return void o();setTimeout((function(){e._tryCatchOnError((function(){a._loadNodeLOD(e,t,r,n-1,o)}))}),a.Delay)}))},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,n,o,a,i){var s=this;t._loadMaterial(r,n[o],(function(l,u){o===n.length-1?(a(l,u),t._executeWhenRenderReady((function(){s._loadMaterialLOD(t,r,n,o-1,a,i)}))):e.BaseTexture.WhenAllReady(l.getActiveTextures(),(function(){a(l,u),0===o?i():setTimeout((function(){t._tryCatchOnError((function(){s._loadMaterialLOD(t,r,n,o-1,a,i)}))}),s.Delay)}))}))},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),i()}))},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}));
  103185. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  103186. /***/ }),
  103187. /* 30 */
  103188. /***/ (function(module, exports, __webpack_require__) {
  103189. /*!
  103190. * PEP v0.4.3 | https://github.com/jquery/PEP
  103191. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  103192. */
  103193. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  103194. // define inherited MouseEvent properties
  103195. // skip bubbles and cancelable since they're set above in initEvent()
  103196. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  103197. // Spec requires that pointers without pressure specified use 0.5 for down
  103198. // state and 0 for up state.
  103199. var f=0;
  103200. // add x/y properties aliased to clientX/Y
  103201. // define the properties of the PointerEvent interface
  103202. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  103203. // only activate if this platform does not have pointer events
  103204. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  103205. * This is the constructor for new PointerEvents.
  103206. *
  103207. * New Pointer Events must be given a type, and an optional dictionary of
  103208. * initialization properties.
  103209. *
  103210. * Due to certain platform requirements, events returned from the constructor
  103211. * identify as MouseEvents.
  103212. *
  103213. * @constructor
  103214. * @param {String} inType The type of the event to create.
  103215. * @param {Object} [inDict] An optional dictionary of initial event properties.
  103216. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  103217. */
  103218. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  103219. // return value, key, map
  103220. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  103221. // MouseEvent
  103222. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  103223. // DOM Level 3
  103224. "buttons",
  103225. // PointerEvent
  103226. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  103227. // event instance
  103228. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  103229. // MouseEvent
  103230. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  103231. // DOM Level 3
  103232. 0,
  103233. // PointerEvent
  103234. 0,0,0,0,0,0,"",0,!1,
  103235. // event instance
  103236. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  103237. // Scope objects for native events.
  103238. // This exists for ease of testing.
  103239. eventSources:Object.create(null),eventSourceList:[],/**
  103240. * Add a new event source that will generate pointer events.
  103241. *
  103242. * `inSource` must contain an array of event names named `events`, and
  103243. * functions with the names specified in the `events` array.
  103244. * @param {string} name A name for the event source
  103245. * @param {Object} source A new source of platform events.
  103246. */
  103247. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  103248. // call eventsource register
  103249. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  103250. // call eventsource register
  103251. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  103252. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  103253. return!1}},
  103254. // EVENTS
  103255. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  103256. // LISTENER LOGIC
  103257. eventHandler:function(a){
  103258. // This is used to prevent multiple dispatch of pointerevents from
  103259. // platform events. This can happen when two elements in different scopes
  103260. // are set up to create pointer events, which is relevant to Shadow DOM.
  103261. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  103262. // set up event listeners
  103263. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  103264. // remove event listeners
  103265. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  103266. // EVENT CREATION AND TRACKING
  103267. /**
  103268. * Creates a new Event of type `inType`, based on the information in
  103269. * `inEvent`.
  103270. *
  103271. * @param {string} inType A string representing the type of event to create
  103272. * @param {Event} inEvent A platform event with a target
  103273. * @return {Event} A PointerEvent of type `inType`
  103274. */
  103275. makeEvent:function(b,c){
  103276. // relatedTarget must be null if pointer is captured
  103277. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  103278. // make and dispatch an event in one call
  103279. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  103280. * Returns a snapshot of inEvent, with writable properties.
  103281. *
  103282. * @param {Event} inEvent An event that contains properties to copy.
  103283. * @return {Object} An object containing shallow copies of `inEvent`'s
  103284. * properties.
  103285. */
  103286. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  103287. // Work around SVGInstanceElement shadow tree
  103288. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  103289. // This is the behavior implemented by Firefox.
  103290. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  103291. // keep the semantics of preventDefault
  103292. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  103293. // Order of conditions due to document.contains() missing in IE.
  103294. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  103295. // Touch: Do not propagate if node is detached.
  103296. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  103297. * Dispatches the event to its target.
  103298. *
  103299. * @param {Event} inEvent The event to be dispatched.
  103300. * @return {Boolean} True if an event handler returns true, false otherwise.
  103301. */
  103302. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  103303. // is element a shadow host?
  103304. e=this.targetingShadow(f);e;){if(
  103305. // find the the element inside the shadow root
  103306. d=e.elementFromPoint(b,c)){
  103307. // shadowed element may contain a shadow root
  103308. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  103309. // check for older shadows
  103310. e=this.olderShadow(e)}
  103311. // light dom element is the target
  103312. return f}},owner:function(a){
  103313. // walk up until you hit the shadow root or document
  103314. for(var b=a;b.parentNode;)b=b.parentNode;
  103315. // the owner element is expected to be a Document or ShadowRoot
  103316. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  103317. // if x, y is not in this root, fall back to document search
  103318. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  103319. // Only watch scopes that can target find, as these are top-level.
  103320. // Otherwise we can see duplicate additions and removals that add noise.
  103321. //
  103322. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  103323. // a removal without an insertion when a node is redistributed among
  103324. // shadows. Since it all ends up correct in the document, watching only
  103325. // the document will yield the correct mutations to watch.
  103326. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  103327. // register all touch-action = none nodes on document load
  103328. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  103329. // find children with touch-action
  103330. var b=x(a,this.findElements,this);
  103331. // flatten the list
  103332. // make sure the added nodes are accounted for
  103333. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  103334. // handler block for native mouse events
  103335. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  103336. // collide with the global mouse listener
  103337. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  103338. // simulated mouse events will be swallowed near a primary touchend
  103339. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  103340. // Update buttons state after possible out-of-document mouseup.
  103341. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  103342. // Produces wrong state of buttons in Browsers without `buttons` support
  103343. // when a mouse button that was pressed outside the document is released
  103344. // inside and other buttons are still pressed down.
  103345. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  103346. // Support: Firefox <=44 only
  103347. // FF Ubuntu includes the lifted button in the `buttons` property on
  103348. // mouseup.
  103349. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  103350. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  103351. // set touch-action on shadows as well
  103352. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  103353. // remove touch-action from shadow
  103354. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  103355. // simply update scrollType if listeners are already established
  103356. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  103357. // set primary touch if there no pointers, or the only pointer is the mouse
  103358. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  103359. // forward modifier keys
  103360. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  103361. // forward touch preventDefaults
  103362. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  103363. // For single axis scrollers, determines whether the element should emit
  103364. // pointer events or behave as a scroller
  103365. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  103366. // this element is a touch-action: none, should never scroll
  103367. b=!1;else if("XY"===c)
  103368. // this element should always scroll
  103369. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  103370. // if delta in the scroll axis > delta other axis, scroll instead of
  103371. // making events
  103372. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  103373. // In some instances, a touchstart can happen without a touchend. This
  103374. // leaves the pointermap in a broken state.
  103375. // Therefore, on every touchstart, we remove the touches that did not fire a
  103376. // touchend event.
  103377. // To keep state globally consistent, we fire a
  103378. // pointercancel for this "abandoned" touch
  103379. vacuumTouches:function(a){var b=a.touches;
  103380. // pointermap.size should be < tl.length here, as the touchstart has not
  103381. // been processed yet.
  103382. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  103383. // Never remove pointerId == 1, which is mouse.
  103384. // Touch identifiers are 2 smaller than their pointerId, which is the
  103385. // index in pointermap.
  103386. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  103387. // a finger drifted off the screen, ignore it
  103388. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  103389. // recover from retargeting by shadow
  103390. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  103391. // clean up case when finger leaves the screen
  103392. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  103393. // prevent synth mouse events from creating pointer events
  103394. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  103395. // only the primary finger will synth mouse events
  103396. if(this.isPrimaryTouch(c)){
  103397. // remember x/y of last touch
  103398. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  103399. /***/ }),
  103400. /* 31 */
  103401. /***/ (function(module, exports, __webpack_require__) {
  103402. "use strict";
  103403. Object.defineProperty(exports, "__esModule", { value: true });
  103404. var defaultViewer_1 = __webpack_require__(5);
  103405. var mappers_1 = __webpack_require__(2);
  103406. function InitTags(selector) {
  103407. if (selector === void 0) { selector = 'babylon'; }
  103408. var elements = document.querySelectorAll(selector);
  103409. for (var i = 0; i < elements.length; ++i) {
  103410. var element = elements.item(i);
  103411. var configMapper = mappers_1.mapperManager.getMapper('dom');
  103412. var config = configMapper.map(element);
  103413. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  103414. }
  103415. }
  103416. exports.InitTags = InitTags;
  103417. /***/ }),
  103418. /* 32 */
  103419. /***/ (function(module, exports, __webpack_require__) {
  103420. /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
  103421. * @overview es6-promise - a tiny implementation of Promises/A+.
  103422. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  103423. * @license Licensed under MIT license
  103424. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  103425. * @version 4.1.1
  103426. */
  103427. (function (global, factory) {
  103428. true ? module.exports = factory() :
  103429. typeof define === 'function' && define.amd ? define(factory) :
  103430. (global.ES6Promise = factory());
  103431. }(this, (function () { 'use strict';
  103432. function objectOrFunction(x) {
  103433. var type = typeof x;
  103434. return x !== null && (type === 'object' || type === 'function');
  103435. }
  103436. function isFunction(x) {
  103437. return typeof x === 'function';
  103438. }
  103439. var _isArray = undefined;
  103440. if (Array.isArray) {
  103441. _isArray = Array.isArray;
  103442. } else {
  103443. _isArray = function (x) {
  103444. return Object.prototype.toString.call(x) === '[object Array]';
  103445. };
  103446. }
  103447. var isArray = _isArray;
  103448. var len = 0;
  103449. var vertxNext = undefined;
  103450. var customSchedulerFn = undefined;
  103451. var asap = function asap(callback, arg) {
  103452. queue[len] = callback;
  103453. queue[len + 1] = arg;
  103454. len += 2;
  103455. if (len === 2) {
  103456. // If len is 2, that means that we need to schedule an async flush.
  103457. // If additional callbacks are queued before the queue is flushed, they
  103458. // will be processed by this flush that we are scheduling.
  103459. if (customSchedulerFn) {
  103460. customSchedulerFn(flush);
  103461. } else {
  103462. scheduleFlush();
  103463. }
  103464. }
  103465. };
  103466. function setScheduler(scheduleFn) {
  103467. customSchedulerFn = scheduleFn;
  103468. }
  103469. function setAsap(asapFn) {
  103470. asap = asapFn;
  103471. }
  103472. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  103473. var browserGlobal = browserWindow || {};
  103474. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  103475. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  103476. // test for web worker but not in IE10
  103477. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  103478. // node
  103479. function useNextTick() {
  103480. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  103481. // see https://github.com/cujojs/when/issues/410 for details
  103482. return function () {
  103483. return process.nextTick(flush);
  103484. };
  103485. }
  103486. // vertx
  103487. function useVertxTimer() {
  103488. if (typeof vertxNext !== 'undefined') {
  103489. return function () {
  103490. vertxNext(flush);
  103491. };
  103492. }
  103493. return useSetTimeout();
  103494. }
  103495. function useMutationObserver() {
  103496. var iterations = 0;
  103497. var observer = new BrowserMutationObserver(flush);
  103498. var node = document.createTextNode('');
  103499. observer.observe(node, { characterData: true });
  103500. return function () {
  103501. node.data = iterations = ++iterations % 2;
  103502. };
  103503. }
  103504. // web worker
  103505. function useMessageChannel() {
  103506. var channel = new MessageChannel();
  103507. channel.port1.onmessage = flush;
  103508. return function () {
  103509. return channel.port2.postMessage(0);
  103510. };
  103511. }
  103512. function useSetTimeout() {
  103513. // Store setTimeout reference so es6-promise will be unaffected by
  103514. // other code modifying setTimeout (like sinon.useFakeTimers())
  103515. var globalSetTimeout = setTimeout;
  103516. return function () {
  103517. return globalSetTimeout(flush, 1);
  103518. };
  103519. }
  103520. var queue = new Array(1000);
  103521. function flush() {
  103522. for (var i = 0; i < len; i += 2) {
  103523. var callback = queue[i];
  103524. var arg = queue[i + 1];
  103525. callback(arg);
  103526. queue[i] = undefined;
  103527. queue[i + 1] = undefined;
  103528. }
  103529. len = 0;
  103530. }
  103531. function attemptVertx() {
  103532. try {
  103533. var r = require;
  103534. var vertx = __webpack_require__(34);
  103535. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  103536. return useVertxTimer();
  103537. } catch (e) {
  103538. return useSetTimeout();
  103539. }
  103540. }
  103541. var scheduleFlush = undefined;
  103542. // Decide what async method to use to triggering processing of queued callbacks:
  103543. if (isNode) {
  103544. scheduleFlush = useNextTick();
  103545. } else if (BrowserMutationObserver) {
  103546. scheduleFlush = useMutationObserver();
  103547. } else if (isWorker) {
  103548. scheduleFlush = useMessageChannel();
  103549. } else if (browserWindow === undefined && "function" === 'function') {
  103550. scheduleFlush = attemptVertx();
  103551. } else {
  103552. scheduleFlush = useSetTimeout();
  103553. }
  103554. function then(onFulfillment, onRejection) {
  103555. var _arguments = arguments;
  103556. var parent = this;
  103557. var child = new this.constructor(noop);
  103558. if (child[PROMISE_ID] === undefined) {
  103559. makePromise(child);
  103560. }
  103561. var _state = parent._state;
  103562. if (_state) {
  103563. (function () {
  103564. var callback = _arguments[_state - 1];
  103565. asap(function () {
  103566. return invokeCallback(_state, child, callback, parent._result);
  103567. });
  103568. })();
  103569. } else {
  103570. subscribe(parent, child, onFulfillment, onRejection);
  103571. }
  103572. return child;
  103573. }
  103574. /**
  103575. `Promise.resolve` returns a promise that will become resolved with the
  103576. passed `value`. It is shorthand for the following:
  103577. ```javascript
  103578. let promise = new Promise(function(resolve, reject){
  103579. resolve(1);
  103580. });
  103581. promise.then(function(value){
  103582. // value === 1
  103583. });
  103584. ```
  103585. Instead of writing the above, your code now simply becomes the following:
  103586. ```javascript
  103587. let promise = Promise.resolve(1);
  103588. promise.then(function(value){
  103589. // value === 1
  103590. });
  103591. ```
  103592. @method resolve
  103593. @static
  103594. @param {Any} value value that the returned promise will be resolved with
  103595. Useful for tooling.
  103596. @return {Promise} a promise that will become fulfilled with the given
  103597. `value`
  103598. */
  103599. function resolve$1(object) {
  103600. /*jshint validthis:true */
  103601. var Constructor = this;
  103602. if (object && typeof object === 'object' && object.constructor === Constructor) {
  103603. return object;
  103604. }
  103605. var promise = new Constructor(noop);
  103606. resolve(promise, object);
  103607. return promise;
  103608. }
  103609. var PROMISE_ID = Math.random().toString(36).substring(16);
  103610. function noop() {}
  103611. var PENDING = void 0;
  103612. var FULFILLED = 1;
  103613. var REJECTED = 2;
  103614. var GET_THEN_ERROR = new ErrorObject();
  103615. function selfFulfillment() {
  103616. return new TypeError("You cannot resolve a promise with itself");
  103617. }
  103618. function cannotReturnOwn() {
  103619. return new TypeError('A promises callback cannot return that same promise.');
  103620. }
  103621. function getThen(promise) {
  103622. try {
  103623. return promise.then;
  103624. } catch (error) {
  103625. GET_THEN_ERROR.error = error;
  103626. return GET_THEN_ERROR;
  103627. }
  103628. }
  103629. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  103630. try {
  103631. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  103632. } catch (e) {
  103633. return e;
  103634. }
  103635. }
  103636. function handleForeignThenable(promise, thenable, then$$1) {
  103637. asap(function (promise) {
  103638. var sealed = false;
  103639. var error = tryThen(then$$1, thenable, function (value) {
  103640. if (sealed) {
  103641. return;
  103642. }
  103643. sealed = true;
  103644. if (thenable !== value) {
  103645. resolve(promise, value);
  103646. } else {
  103647. fulfill(promise, value);
  103648. }
  103649. }, function (reason) {
  103650. if (sealed) {
  103651. return;
  103652. }
  103653. sealed = true;
  103654. reject(promise, reason);
  103655. }, 'Settle: ' + (promise._label || ' unknown promise'));
  103656. if (!sealed && error) {
  103657. sealed = true;
  103658. reject(promise, error);
  103659. }
  103660. }, promise);
  103661. }
  103662. function handleOwnThenable(promise, thenable) {
  103663. if (thenable._state === FULFILLED) {
  103664. fulfill(promise, thenable._result);
  103665. } else if (thenable._state === REJECTED) {
  103666. reject(promise, thenable._result);
  103667. } else {
  103668. subscribe(thenable, undefined, function (value) {
  103669. return resolve(promise, value);
  103670. }, function (reason) {
  103671. return reject(promise, reason);
  103672. });
  103673. }
  103674. }
  103675. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  103676. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  103677. handleOwnThenable(promise, maybeThenable);
  103678. } else {
  103679. if (then$$1 === GET_THEN_ERROR) {
  103680. reject(promise, GET_THEN_ERROR.error);
  103681. GET_THEN_ERROR.error = null;
  103682. } else if (then$$1 === undefined) {
  103683. fulfill(promise, maybeThenable);
  103684. } else if (isFunction(then$$1)) {
  103685. handleForeignThenable(promise, maybeThenable, then$$1);
  103686. } else {
  103687. fulfill(promise, maybeThenable);
  103688. }
  103689. }
  103690. }
  103691. function resolve(promise, value) {
  103692. if (promise === value) {
  103693. reject(promise, selfFulfillment());
  103694. } else if (objectOrFunction(value)) {
  103695. handleMaybeThenable(promise, value, getThen(value));
  103696. } else {
  103697. fulfill(promise, value);
  103698. }
  103699. }
  103700. function publishRejection(promise) {
  103701. if (promise._onerror) {
  103702. promise._onerror(promise._result);
  103703. }
  103704. publish(promise);
  103705. }
  103706. function fulfill(promise, value) {
  103707. if (promise._state !== PENDING) {
  103708. return;
  103709. }
  103710. promise._result = value;
  103711. promise._state = FULFILLED;
  103712. if (promise._subscribers.length !== 0) {
  103713. asap(publish, promise);
  103714. }
  103715. }
  103716. function reject(promise, reason) {
  103717. if (promise._state !== PENDING) {
  103718. return;
  103719. }
  103720. promise._state = REJECTED;
  103721. promise._result = reason;
  103722. asap(publishRejection, promise);
  103723. }
  103724. function subscribe(parent, child, onFulfillment, onRejection) {
  103725. var _subscribers = parent._subscribers;
  103726. var length = _subscribers.length;
  103727. parent._onerror = null;
  103728. _subscribers[length] = child;
  103729. _subscribers[length + FULFILLED] = onFulfillment;
  103730. _subscribers[length + REJECTED] = onRejection;
  103731. if (length === 0 && parent._state) {
  103732. asap(publish, parent);
  103733. }
  103734. }
  103735. function publish(promise) {
  103736. var subscribers = promise._subscribers;
  103737. var settled = promise._state;
  103738. if (subscribers.length === 0) {
  103739. return;
  103740. }
  103741. var child = undefined,
  103742. callback = undefined,
  103743. detail = promise._result;
  103744. for (var i = 0; i < subscribers.length; i += 3) {
  103745. child = subscribers[i];
  103746. callback = subscribers[i + settled];
  103747. if (child) {
  103748. invokeCallback(settled, child, callback, detail);
  103749. } else {
  103750. callback(detail);
  103751. }
  103752. }
  103753. promise._subscribers.length = 0;
  103754. }
  103755. function ErrorObject() {
  103756. this.error = null;
  103757. }
  103758. var TRY_CATCH_ERROR = new ErrorObject();
  103759. function tryCatch(callback, detail) {
  103760. try {
  103761. return callback(detail);
  103762. } catch (e) {
  103763. TRY_CATCH_ERROR.error = e;
  103764. return TRY_CATCH_ERROR;
  103765. }
  103766. }
  103767. function invokeCallback(settled, promise, callback, detail) {
  103768. var hasCallback = isFunction(callback),
  103769. value = undefined,
  103770. error = undefined,
  103771. succeeded = undefined,
  103772. failed = undefined;
  103773. if (hasCallback) {
  103774. value = tryCatch(callback, detail);
  103775. if (value === TRY_CATCH_ERROR) {
  103776. failed = true;
  103777. error = value.error;
  103778. value.error = null;
  103779. } else {
  103780. succeeded = true;
  103781. }
  103782. if (promise === value) {
  103783. reject(promise, cannotReturnOwn());
  103784. return;
  103785. }
  103786. } else {
  103787. value = detail;
  103788. succeeded = true;
  103789. }
  103790. if (promise._state !== PENDING) {
  103791. // noop
  103792. } else if (hasCallback && succeeded) {
  103793. resolve(promise, value);
  103794. } else if (failed) {
  103795. reject(promise, error);
  103796. } else if (settled === FULFILLED) {
  103797. fulfill(promise, value);
  103798. } else if (settled === REJECTED) {
  103799. reject(promise, value);
  103800. }
  103801. }
  103802. function initializePromise(promise, resolver) {
  103803. try {
  103804. resolver(function resolvePromise(value) {
  103805. resolve(promise, value);
  103806. }, function rejectPromise(reason) {
  103807. reject(promise, reason);
  103808. });
  103809. } catch (e) {
  103810. reject(promise, e);
  103811. }
  103812. }
  103813. var id = 0;
  103814. function nextId() {
  103815. return id++;
  103816. }
  103817. function makePromise(promise) {
  103818. promise[PROMISE_ID] = id++;
  103819. promise._state = undefined;
  103820. promise._result = undefined;
  103821. promise._subscribers = [];
  103822. }
  103823. function Enumerator$1(Constructor, input) {
  103824. this._instanceConstructor = Constructor;
  103825. this.promise = new Constructor(noop);
  103826. if (!this.promise[PROMISE_ID]) {
  103827. makePromise(this.promise);
  103828. }
  103829. if (isArray(input)) {
  103830. this.length = input.length;
  103831. this._remaining = input.length;
  103832. this._result = new Array(this.length);
  103833. if (this.length === 0) {
  103834. fulfill(this.promise, this._result);
  103835. } else {
  103836. this.length = this.length || 0;
  103837. this._enumerate(input);
  103838. if (this._remaining === 0) {
  103839. fulfill(this.promise, this._result);
  103840. }
  103841. }
  103842. } else {
  103843. reject(this.promise, validationError());
  103844. }
  103845. }
  103846. function validationError() {
  103847. return new Error('Array Methods must be provided an Array');
  103848. }
  103849. Enumerator$1.prototype._enumerate = function (input) {
  103850. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  103851. this._eachEntry(input[i], i);
  103852. }
  103853. };
  103854. Enumerator$1.prototype._eachEntry = function (entry, i) {
  103855. var c = this._instanceConstructor;
  103856. var resolve$$1 = c.resolve;
  103857. if (resolve$$1 === resolve$1) {
  103858. var _then = getThen(entry);
  103859. if (_then === then && entry._state !== PENDING) {
  103860. this._settledAt(entry._state, i, entry._result);
  103861. } else if (typeof _then !== 'function') {
  103862. this._remaining--;
  103863. this._result[i] = entry;
  103864. } else if (c === Promise$2) {
  103865. var promise = new c(noop);
  103866. handleMaybeThenable(promise, entry, _then);
  103867. this._willSettleAt(promise, i);
  103868. } else {
  103869. this._willSettleAt(new c(function (resolve$$1) {
  103870. return resolve$$1(entry);
  103871. }), i);
  103872. }
  103873. } else {
  103874. this._willSettleAt(resolve$$1(entry), i);
  103875. }
  103876. };
  103877. Enumerator$1.prototype._settledAt = function (state, i, value) {
  103878. var promise = this.promise;
  103879. if (promise._state === PENDING) {
  103880. this._remaining--;
  103881. if (state === REJECTED) {
  103882. reject(promise, value);
  103883. } else {
  103884. this._result[i] = value;
  103885. }
  103886. }
  103887. if (this._remaining === 0) {
  103888. fulfill(promise, this._result);
  103889. }
  103890. };
  103891. Enumerator$1.prototype._willSettleAt = function (promise, i) {
  103892. var enumerator = this;
  103893. subscribe(promise, undefined, function (value) {
  103894. return enumerator._settledAt(FULFILLED, i, value);
  103895. }, function (reason) {
  103896. return enumerator._settledAt(REJECTED, i, reason);
  103897. });
  103898. };
  103899. /**
  103900. `Promise.all` accepts an array of promises, and returns a new promise which
  103901. is fulfilled with an array of fulfillment values for the passed promises, or
  103902. rejected with the reason of the first passed promise to be rejected. It casts all
  103903. elements of the passed iterable to promises as it runs this algorithm.
  103904. Example:
  103905. ```javascript
  103906. let promise1 = resolve(1);
  103907. let promise2 = resolve(2);
  103908. let promise3 = resolve(3);
  103909. let promises = [ promise1, promise2, promise3 ];
  103910. Promise.all(promises).then(function(array){
  103911. // The array here would be [ 1, 2, 3 ];
  103912. });
  103913. ```
  103914. If any of the `promises` given to `all` are rejected, the first promise
  103915. that is rejected will be given as an argument to the returned promises's
  103916. rejection handler. For example:
  103917. Example:
  103918. ```javascript
  103919. let promise1 = resolve(1);
  103920. let promise2 = reject(new Error("2"));
  103921. let promise3 = reject(new Error("3"));
  103922. let promises = [ promise1, promise2, promise3 ];
  103923. Promise.all(promises).then(function(array){
  103924. // Code here never runs because there are rejected promises!
  103925. }, function(error) {
  103926. // error.message === "2"
  103927. });
  103928. ```
  103929. @method all
  103930. @static
  103931. @param {Array} entries array of promises
  103932. @param {String} label optional string for labeling the promise.
  103933. Useful for tooling.
  103934. @return {Promise} promise that is fulfilled when all `promises` have been
  103935. fulfilled, or rejected if any of them become rejected.
  103936. @static
  103937. */
  103938. function all$1(entries) {
  103939. return new Enumerator$1(this, entries).promise;
  103940. }
  103941. /**
  103942. `Promise.race` returns a new promise which is settled in the same way as the
  103943. first passed promise to settle.
  103944. Example:
  103945. ```javascript
  103946. let promise1 = new Promise(function(resolve, reject){
  103947. setTimeout(function(){
  103948. resolve('promise 1');
  103949. }, 200);
  103950. });
  103951. let promise2 = new Promise(function(resolve, reject){
  103952. setTimeout(function(){
  103953. resolve('promise 2');
  103954. }, 100);
  103955. });
  103956. Promise.race([promise1, promise2]).then(function(result){
  103957. // result === 'promise 2' because it was resolved before promise1
  103958. // was resolved.
  103959. });
  103960. ```
  103961. `Promise.race` is deterministic in that only the state of the first
  103962. settled promise matters. For example, even if other promises given to the
  103963. `promises` array argument are resolved, but the first settled promise has
  103964. become rejected before the other promises became fulfilled, the returned
  103965. promise will become rejected:
  103966. ```javascript
  103967. let promise1 = new Promise(function(resolve, reject){
  103968. setTimeout(function(){
  103969. resolve('promise 1');
  103970. }, 200);
  103971. });
  103972. let promise2 = new Promise(function(resolve, reject){
  103973. setTimeout(function(){
  103974. reject(new Error('promise 2'));
  103975. }, 100);
  103976. });
  103977. Promise.race([promise1, promise2]).then(function(result){
  103978. // Code here never runs
  103979. }, function(reason){
  103980. // reason.message === 'promise 2' because promise 2 became rejected before
  103981. // promise 1 became fulfilled
  103982. });
  103983. ```
  103984. An example real-world use case is implementing timeouts:
  103985. ```javascript
  103986. Promise.race([ajax('foo.json'), timeout(5000)])
  103987. ```
  103988. @method race
  103989. @static
  103990. @param {Array} promises array of promises to observe
  103991. Useful for tooling.
  103992. @return {Promise} a promise which settles in the same way as the first passed
  103993. promise to settle.
  103994. */
  103995. function race$1(entries) {
  103996. /*jshint validthis:true */
  103997. var Constructor = this;
  103998. if (!isArray(entries)) {
  103999. return new Constructor(function (_, reject) {
  104000. return reject(new TypeError('You must pass an array to race.'));
  104001. });
  104002. } else {
  104003. return new Constructor(function (resolve, reject) {
  104004. var length = entries.length;
  104005. for (var i = 0; i < length; i++) {
  104006. Constructor.resolve(entries[i]).then(resolve, reject);
  104007. }
  104008. });
  104009. }
  104010. }
  104011. /**
  104012. `Promise.reject` returns a promise rejected with the passed `reason`.
  104013. It is shorthand for the following:
  104014. ```javascript
  104015. let promise = new Promise(function(resolve, reject){
  104016. reject(new Error('WHOOPS'));
  104017. });
  104018. promise.then(function(value){
  104019. // Code here doesn't run because the promise is rejected!
  104020. }, function(reason){
  104021. // reason.message === 'WHOOPS'
  104022. });
  104023. ```
  104024. Instead of writing the above, your code now simply becomes the following:
  104025. ```javascript
  104026. let promise = Promise.reject(new Error('WHOOPS'));
  104027. promise.then(function(value){
  104028. // Code here doesn't run because the promise is rejected!
  104029. }, function(reason){
  104030. // reason.message === 'WHOOPS'
  104031. });
  104032. ```
  104033. @method reject
  104034. @static
  104035. @param {Any} reason value that the returned promise will be rejected with.
  104036. Useful for tooling.
  104037. @return {Promise} a promise rejected with the given `reason`.
  104038. */
  104039. function reject$1(reason) {
  104040. /*jshint validthis:true */
  104041. var Constructor = this;
  104042. var promise = new Constructor(noop);
  104043. reject(promise, reason);
  104044. return promise;
  104045. }
  104046. function needsResolver() {
  104047. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  104048. }
  104049. function needsNew() {
  104050. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  104051. }
  104052. /**
  104053. Promise objects represent the eventual result of an asynchronous operation. The
  104054. primary way of interacting with a promise is through its `then` method, which
  104055. registers callbacks to receive either a promise's eventual value or the reason
  104056. why the promise cannot be fulfilled.
  104057. Terminology
  104058. -----------
  104059. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  104060. - `thenable` is an object or function that defines a `then` method.
  104061. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  104062. - `exception` is a value that is thrown using the throw statement.
  104063. - `reason` is a value that indicates why a promise was rejected.
  104064. - `settled` the final resting state of a promise, fulfilled or rejected.
  104065. A promise can be in one of three states: pending, fulfilled, or rejected.
  104066. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  104067. state. Promises that are rejected have a rejection reason and are in the
  104068. rejected state. A fulfillment value is never a thenable.
  104069. Promises can also be said to *resolve* a value. If this value is also a
  104070. promise, then the original promise's settled state will match the value's
  104071. settled state. So a promise that *resolves* a promise that rejects will
  104072. itself reject, and a promise that *resolves* a promise that fulfills will
  104073. itself fulfill.
  104074. Basic Usage:
  104075. ------------
  104076. ```js
  104077. let promise = new Promise(function(resolve, reject) {
  104078. // on success
  104079. resolve(value);
  104080. // on failure
  104081. reject(reason);
  104082. });
  104083. promise.then(function(value) {
  104084. // on fulfillment
  104085. }, function(reason) {
  104086. // on rejection
  104087. });
  104088. ```
  104089. Advanced Usage:
  104090. ---------------
  104091. Promises shine when abstracting away asynchronous interactions such as
  104092. `XMLHttpRequest`s.
  104093. ```js
  104094. function getJSON(url) {
  104095. return new Promise(function(resolve, reject){
  104096. let xhr = new XMLHttpRequest();
  104097. xhr.open('GET', url);
  104098. xhr.onreadystatechange = handler;
  104099. xhr.responseType = 'json';
  104100. xhr.setRequestHeader('Accept', 'application/json');
  104101. xhr.send();
  104102. function handler() {
  104103. if (this.readyState === this.DONE) {
  104104. if (this.status === 200) {
  104105. resolve(this.response);
  104106. } else {
  104107. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  104108. }
  104109. }
  104110. };
  104111. });
  104112. }
  104113. getJSON('/posts.json').then(function(json) {
  104114. // on fulfillment
  104115. }, function(reason) {
  104116. // on rejection
  104117. });
  104118. ```
  104119. Unlike callbacks, promises are great composable primitives.
  104120. ```js
  104121. Promise.all([
  104122. getJSON('/posts'),
  104123. getJSON('/comments')
  104124. ]).then(function(values){
  104125. values[0] // => postsJSON
  104126. values[1] // => commentsJSON
  104127. return values;
  104128. });
  104129. ```
  104130. @class Promise
  104131. @param {function} resolver
  104132. Useful for tooling.
  104133. @constructor
  104134. */
  104135. function Promise$2(resolver) {
  104136. this[PROMISE_ID] = nextId();
  104137. this._result = this._state = undefined;
  104138. this._subscribers = [];
  104139. if (noop !== resolver) {
  104140. typeof resolver !== 'function' && needsResolver();
  104141. this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
  104142. }
  104143. }
  104144. Promise$2.all = all$1;
  104145. Promise$2.race = race$1;
  104146. Promise$2.resolve = resolve$1;
  104147. Promise$2.reject = reject$1;
  104148. Promise$2._setScheduler = setScheduler;
  104149. Promise$2._setAsap = setAsap;
  104150. Promise$2._asap = asap;
  104151. Promise$2.prototype = {
  104152. constructor: Promise$2,
  104153. /**
  104154. The primary way of interacting with a promise is through its `then` method,
  104155. which registers callbacks to receive either a promise's eventual value or the
  104156. reason why the promise cannot be fulfilled.
  104157. ```js
  104158. findUser().then(function(user){
  104159. // user is available
  104160. }, function(reason){
  104161. // user is unavailable, and you are given the reason why
  104162. });
  104163. ```
  104164. Chaining
  104165. --------
  104166. The return value of `then` is itself a promise. This second, 'downstream'
  104167. promise is resolved with the return value of the first promise's fulfillment
  104168. or rejection handler, or rejected if the handler throws an exception.
  104169. ```js
  104170. findUser().then(function (user) {
  104171. return user.name;
  104172. }, function (reason) {
  104173. return 'default name';
  104174. }).then(function (userName) {
  104175. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  104176. // will be `'default name'`
  104177. });
  104178. findUser().then(function (user) {
  104179. throw new Error('Found user, but still unhappy');
  104180. }, function (reason) {
  104181. throw new Error('`findUser` rejected and we're unhappy');
  104182. }).then(function (value) {
  104183. // never reached
  104184. }, function (reason) {
  104185. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  104186. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  104187. });
  104188. ```
  104189. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  104190. ```js
  104191. findUser().then(function (user) {
  104192. throw new PedagogicalException('Upstream error');
  104193. }).then(function (value) {
  104194. // never reached
  104195. }).then(function (value) {
  104196. // never reached
  104197. }, function (reason) {
  104198. // The `PedgagocialException` is propagated all the way down to here
  104199. });
  104200. ```
  104201. Assimilation
  104202. ------------
  104203. Sometimes the value you want to propagate to a downstream promise can only be
  104204. retrieved asynchronously. This can be achieved by returning a promise in the
  104205. fulfillment or rejection handler. The downstream promise will then be pending
  104206. until the returned promise is settled. This is called *assimilation*.
  104207. ```js
  104208. findUser().then(function (user) {
  104209. return findCommentsByAuthor(user);
  104210. }).then(function (comments) {
  104211. // The user's comments are now available
  104212. });
  104213. ```
  104214. If the assimliated promise rejects, then the downstream promise will also reject.
  104215. ```js
  104216. findUser().then(function (user) {
  104217. return findCommentsByAuthor(user);
  104218. }).then(function (comments) {
  104219. // If `findCommentsByAuthor` fulfills, we'll have the value here
  104220. }, function (reason) {
  104221. // If `findCommentsByAuthor` rejects, we'll have the reason here
  104222. });
  104223. ```
  104224. Simple Example
  104225. --------------
  104226. Synchronous Example
  104227. ```javascript
  104228. let result;
  104229. try {
  104230. result = findResult();
  104231. // success
  104232. } catch(reason) {
  104233. // failure
  104234. }
  104235. ```
  104236. Errback Example
  104237. ```js
  104238. findResult(function(result, err){
  104239. if (err) {
  104240. // failure
  104241. } else {
  104242. // success
  104243. }
  104244. });
  104245. ```
  104246. Promise Example;
  104247. ```javascript
  104248. findResult().then(function(result){
  104249. // success
  104250. }, function(reason){
  104251. // failure
  104252. });
  104253. ```
  104254. Advanced Example
  104255. --------------
  104256. Synchronous Example
  104257. ```javascript
  104258. let author, books;
  104259. try {
  104260. author = findAuthor();
  104261. books = findBooksByAuthor(author);
  104262. // success
  104263. } catch(reason) {
  104264. // failure
  104265. }
  104266. ```
  104267. Errback Example
  104268. ```js
  104269. function foundBooks(books) {
  104270. }
  104271. function failure(reason) {
  104272. }
  104273. findAuthor(function(author, err){
  104274. if (err) {
  104275. failure(err);
  104276. // failure
  104277. } else {
  104278. try {
  104279. findBoooksByAuthor(author, function(books, err) {
  104280. if (err) {
  104281. failure(err);
  104282. } else {
  104283. try {
  104284. foundBooks(books);
  104285. } catch(reason) {
  104286. failure(reason);
  104287. }
  104288. }
  104289. });
  104290. } catch(error) {
  104291. failure(err);
  104292. }
  104293. // success
  104294. }
  104295. });
  104296. ```
  104297. Promise Example;
  104298. ```javascript
  104299. findAuthor().
  104300. then(findBooksByAuthor).
  104301. then(function(books){
  104302. // found books
  104303. }).catch(function(reason){
  104304. // something went wrong
  104305. });
  104306. ```
  104307. @method then
  104308. @param {Function} onFulfilled
  104309. @param {Function} onRejected
  104310. Useful for tooling.
  104311. @return {Promise}
  104312. */
  104313. then: then,
  104314. /**
  104315. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  104316. as the catch block of a try/catch statement.
  104317. ```js
  104318. function findAuthor(){
  104319. throw new Error('couldn't find that author');
  104320. }
  104321. // synchronous
  104322. try {
  104323. findAuthor();
  104324. } catch(reason) {
  104325. // something went wrong
  104326. }
  104327. // async with promises
  104328. findAuthor().catch(function(reason){
  104329. // something went wrong
  104330. });
  104331. ```
  104332. @method catch
  104333. @param {Function} onRejection
  104334. Useful for tooling.
  104335. @return {Promise}
  104336. */
  104337. 'catch': function _catch(onRejection) {
  104338. return this.then(null, onRejection);
  104339. }
  104340. };
  104341. /*global self*/
  104342. function polyfill$1() {
  104343. var local = undefined;
  104344. if (typeof global !== 'undefined') {
  104345. local = global;
  104346. } else if (typeof self !== 'undefined') {
  104347. local = self;
  104348. } else {
  104349. try {
  104350. local = Function('return this')();
  104351. } catch (e) {
  104352. throw new Error('polyfill failed because global object is unavailable in this environment');
  104353. }
  104354. }
  104355. var P = local.Promise;
  104356. if (P) {
  104357. var promiseToString = null;
  104358. try {
  104359. promiseToString = Object.prototype.toString.call(P.resolve());
  104360. } catch (e) {
  104361. // silently ignored
  104362. }
  104363. if (promiseToString === '[object Promise]' && !P.cast) {
  104364. return;
  104365. }
  104366. }
  104367. local.Promise = Promise$2;
  104368. }
  104369. // Strange compat..
  104370. Promise$2.polyfill = polyfill$1;
  104371. Promise$2.Promise = Promise$2;
  104372. return Promise$2;
  104373. })));
  104374. //# sourceMappingURL=es6-promise.map
  104375. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33), __webpack_require__(1)))
  104376. /***/ }),
  104377. /* 33 */
  104378. /***/ (function(module, exports) {
  104379. // shim for using process in browser
  104380. var process = module.exports = {};
  104381. // cached from whatever global is present so that test runners that stub it
  104382. // don't break things. But we need to wrap it in a try catch in case it is
  104383. // wrapped in strict mode code which doesn't define any globals. It's inside a
  104384. // function because try/catches deoptimize in certain engines.
  104385. var cachedSetTimeout;
  104386. var cachedClearTimeout;
  104387. function defaultSetTimout() {
  104388. throw new Error('setTimeout has not been defined');
  104389. }
  104390. function defaultClearTimeout () {
  104391. throw new Error('clearTimeout has not been defined');
  104392. }
  104393. (function () {
  104394. try {
  104395. if (typeof setTimeout === 'function') {
  104396. cachedSetTimeout = setTimeout;
  104397. } else {
  104398. cachedSetTimeout = defaultSetTimout;
  104399. }
  104400. } catch (e) {
  104401. cachedSetTimeout = defaultSetTimout;
  104402. }
  104403. try {
  104404. if (typeof clearTimeout === 'function') {
  104405. cachedClearTimeout = clearTimeout;
  104406. } else {
  104407. cachedClearTimeout = defaultClearTimeout;
  104408. }
  104409. } catch (e) {
  104410. cachedClearTimeout = defaultClearTimeout;
  104411. }
  104412. } ())
  104413. function runTimeout(fun) {
  104414. if (cachedSetTimeout === setTimeout) {
  104415. //normal enviroments in sane situations
  104416. return setTimeout(fun, 0);
  104417. }
  104418. // if setTimeout wasn't available but was latter defined
  104419. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  104420. cachedSetTimeout = setTimeout;
  104421. return setTimeout(fun, 0);
  104422. }
  104423. try {
  104424. // when when somebody has screwed with setTimeout but no I.E. maddness
  104425. return cachedSetTimeout(fun, 0);
  104426. } catch(e){
  104427. try {
  104428. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  104429. return cachedSetTimeout.call(null, fun, 0);
  104430. } catch(e){
  104431. // 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
  104432. return cachedSetTimeout.call(this, fun, 0);
  104433. }
  104434. }
  104435. }
  104436. function runClearTimeout(marker) {
  104437. if (cachedClearTimeout === clearTimeout) {
  104438. //normal enviroments in sane situations
  104439. return clearTimeout(marker);
  104440. }
  104441. // if clearTimeout wasn't available but was latter defined
  104442. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  104443. cachedClearTimeout = clearTimeout;
  104444. return clearTimeout(marker);
  104445. }
  104446. try {
  104447. // when when somebody has screwed with setTimeout but no I.E. maddness
  104448. return cachedClearTimeout(marker);
  104449. } catch (e){
  104450. try {
  104451. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  104452. return cachedClearTimeout.call(null, marker);
  104453. } catch (e){
  104454. // 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.
  104455. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  104456. return cachedClearTimeout.call(this, marker);
  104457. }
  104458. }
  104459. }
  104460. var queue = [];
  104461. var draining = false;
  104462. var currentQueue;
  104463. var queueIndex = -1;
  104464. function cleanUpNextTick() {
  104465. if (!draining || !currentQueue) {
  104466. return;
  104467. }
  104468. draining = false;
  104469. if (currentQueue.length) {
  104470. queue = currentQueue.concat(queue);
  104471. } else {
  104472. queueIndex = -1;
  104473. }
  104474. if (queue.length) {
  104475. drainQueue();
  104476. }
  104477. }
  104478. function drainQueue() {
  104479. if (draining) {
  104480. return;
  104481. }
  104482. var timeout = runTimeout(cleanUpNextTick);
  104483. draining = true;
  104484. var len = queue.length;
  104485. while(len) {
  104486. currentQueue = queue;
  104487. queue = [];
  104488. while (++queueIndex < len) {
  104489. if (currentQueue) {
  104490. currentQueue[queueIndex].run();
  104491. }
  104492. }
  104493. queueIndex = -1;
  104494. len = queue.length;
  104495. }
  104496. currentQueue = null;
  104497. draining = false;
  104498. runClearTimeout(timeout);
  104499. }
  104500. process.nextTick = function (fun) {
  104501. var args = new Array(arguments.length - 1);
  104502. if (arguments.length > 1) {
  104503. for (var i = 1; i < arguments.length; i++) {
  104504. args[i - 1] = arguments[i];
  104505. }
  104506. }
  104507. queue.push(new Item(fun, args));
  104508. if (queue.length === 1 && !draining) {
  104509. runTimeout(drainQueue);
  104510. }
  104511. };
  104512. // v8 likes predictible objects
  104513. function Item(fun, array) {
  104514. this.fun = fun;
  104515. this.array = array;
  104516. }
  104517. Item.prototype.run = function () {
  104518. this.fun.apply(null, this.array);
  104519. };
  104520. process.title = 'browser';
  104521. process.browser = true;
  104522. process.env = {};
  104523. process.argv = [];
  104524. process.version = ''; // empty string to avoid regexp issues
  104525. process.versions = {};
  104526. function noop() {}
  104527. process.on = noop;
  104528. process.addListener = noop;
  104529. process.once = noop;
  104530. process.off = noop;
  104531. process.removeListener = noop;
  104532. process.removeAllListeners = noop;
  104533. process.emit = noop;
  104534. process.prependListener = noop;
  104535. process.prependOnceListener = noop;
  104536. process.listeners = function (name) { return [] }
  104537. process.binding = function (name) {
  104538. throw new Error('process.binding is not supported');
  104539. };
  104540. process.cwd = function () { return '/' };
  104541. process.chdir = function (dir) {
  104542. throw new Error('process.chdir is not supported');
  104543. };
  104544. process.umask = function() { return 0; };
  104545. /***/ }),
  104546. /* 34 */
  104547. /***/ (function(module, exports) {
  104548. /* (ignored) */
  104549. /***/ })
  104550. /******/ ]);
  104551. });
  104552. //# sourceMappingURL=viewer.js.map